Example usage for com.fasterxml.jackson.core JsonParser close

List of usage examples for com.fasterxml.jackson.core JsonParser close

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonParser close.

Prototype

@Override
public abstract void close() throws IOException;

Source Link

Document

Closes the parser so that no further iteration or data access can be made; will also close the underlying input source if parser either owns the input source, or feature Feature#AUTO_CLOSE_SOURCE is enabled.

Usage

From source file:com.ksc.http.JsonResponseHandler.java

/**
 * @see HttpResponseHandler#handle(HttpResponse)
 *///from  w w  w  . ja  v a 2s. c  o m
public KscWebServiceResponse<T> handle(HttpResponse response) throws Exception {
    log.trace("Parsing service response JSON");

    // TODOFIX
    String CRC32Checksum = response.getHeaders().get("x-amz-crc32");
    CRC32ChecksumCalculatingInputStream crc32ChecksumInputStream = null;

    JsonParser jsonParser = null;

    if (shouldParsePayloadAsJson()) {
        if (CRC32Checksum != null) {
            crc32ChecksumInputStream = new CRC32ChecksumCalculatingInputStream(response.getContent());
            jsonParser = jsonFactory.createParser(crc32ChecksumInputStream);
        } else {
            jsonParser = jsonFactory.createParser(response.getContent());
        }
    }

    try {
        KscWebServiceResponse<T> awsResponse = new KscWebServiceResponse<T>();
        JsonUnmarshallerContext unmarshallerContext = new JsonUnmarshallerContextImpl(jsonParser,
                simpleTypeUnmarshallers, response);
        registerAdditionalMetadataExpressions(unmarshallerContext);

        T result = responseUnmarshaller.unmarshall(unmarshallerContext);

        if (CRC32Checksum != null) {
            long serverSideCRC = Long.parseLong(CRC32Checksum);
            long clientSideCRC = crc32ChecksumInputStream.getCRC32Checksum();
            if (clientSideCRC != serverSideCRC) {
                throw new CRC32MismatchException(
                        "Client calculated crc32 checksum didn't match that calculated by server side");
            }
        }

        awsResponse.setResult(result);

        Map<String, String> metadata = unmarshallerContext.getMetadata();
        metadata.put(ResponseMetadata.KSC_REQUEST_ID, response.getHeaders().get(X_KSC_REQUEST_ID_HEADER));
        awsResponse.setResponseMetadata(new ResponseMetadata(metadata));

        log.trace("Done parsing service response");
        return awsResponse;
    } finally {
        if (shouldParsePayloadAsJson()) {
            try {
                jsonParser.close();
            } catch (IOException e) {
                log.warn("Error closing json parser", e);
            }
        }
    }
}

From source file:com.irccloud.android.GCMIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        String messageType = gcm.getMessageType(intent);

        if (extras != null && !extras.isEmpty()) {
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                //Log.d("IRCCloud", "Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
                //Log.d("IRCCloud", "Deleted messages on server: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                if (!IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences("prefs", 0)
                        .getBoolean("gcm_registered", false)) {
                    String regId = IRCCloudApplication.getInstance().getApplicationContext()
                            .getSharedPreferences("prefs", 0).getString("gcm_reg_id", "");
                    if (regId.length() > 0) {
                        scheduleUnregisterTimer(100, regId, false);
                    }/*ww w .  j  a  v  a 2s. co  m*/
                } else {
                    //Log.d("IRCCloud", "GCM K/V pairs: " + intent.getExtras().toString());
                    try {
                        String type = intent.getStringExtra("type");
                        if (type.equalsIgnoreCase("heartbeat_echo")) {
                            NetworkConnection conn = NetworkConnection.getInstance();
                            ObjectMapper mapper = new ObjectMapper();
                            JsonParser parser = mapper.getFactory()
                                    .createParser(intent.getStringExtra("seenEids"));
                            JsonNode seenEids = mapper.readTree(parser);
                            Iterator<Map.Entry<String, JsonNode>> iterator = seenEids.fields();
                            while (iterator.hasNext()) {
                                Map.Entry<String, JsonNode> entry = iterator.next();
                                JsonNode eids = entry.getValue();
                                Iterator<Map.Entry<String, JsonNode>> j = eids.fields();
                                while (j.hasNext()) {
                                    Map.Entry<String, JsonNode> eidentry = j.next();
                                    String bid = eidentry.getKey();
                                    long eid = eidentry.getValue().asLong();
                                    if (conn.ready && conn.getState() != NetworkConnection.STATE_CONNECTED)
                                        BuffersDataSource.getInstance().updateLastSeenEid(Integer.valueOf(bid),
                                                eid);
                                    Notifications.getInstance().deleteOldNotifications(Integer.valueOf(bid),
                                            eid);
                                    Notifications.getInstance().updateLastSeenEid(Integer.valueOf(bid), eid);
                                }
                            }
                            parser.close();
                        } else {
                            int cid = Integer.valueOf(intent.getStringExtra("cid"));
                            int bid = Integer.valueOf(intent.getStringExtra("bid"));
                            long eid = Long.valueOf(intent.getStringExtra("eid"));
                            if (Notifications.getInstance().getNotification(eid) != null) {
                                Log.e("IRCCloud", "GCM got EID that already exists");
                                return;
                            }
                            String from = intent.getStringExtra("from_nick");
                            String msg = intent.getStringExtra("msg");
                            if (msg != null)
                                msg = ColorFormatter
                                        .html_to_spanned(ColorFormatter.irc_to_html(TextUtils.htmlEncode(msg)))
                                        .toString();
                            String chan = intent.getStringExtra("chan");
                            if (chan == null)
                                chan = "";
                            String buffer_type = intent.getStringExtra("buffer_type");
                            String server_name = intent.getStringExtra("server_name");
                            if (server_name == null || server_name.length() == 0)
                                server_name = intent.getStringExtra("server_hostname");

                            String network = Notifications.getInstance().getNetwork(cid);
                            if (network == null)
                                Notifications.getInstance().addNetwork(cid, server_name);

                            Notifications.getInstance().addNotification(cid, bid, eid, from, msg, chan,
                                    buffer_type, type);

                            if (from == null || from.length() == 0)
                                Notifications.getInstance().showNotifications(server_name + ": " + msg);
                            else if (buffer_type.equals("channel")) {
                                if (type.equals("buffer_me_msg"))
                                    Notifications.getInstance()
                                            .showNotifications(chan + ":  " + from + " " + msg);
                                else
                                    Notifications.getInstance()
                                            .showNotifications(chan + ": <" + from + "> " + msg);
                            } else {
                                if (type.equals("buffer_me_msg"))
                                    Notifications.getInstance().showNotifications(" " + from + " " + msg);
                                else
                                    Notifications.getInstance().showNotifications(from + ": " + msg);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.w("IRCCloud", "Unable to parse GCM message");
                    }
                }
            }
        }
        GCMBroadcastReceiver.completeWakefulIntent(intent);
    }
}

From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java

@Override
public double parseNeanderthalProportion(final InputStream inputStream) {
    checkNotNull(inputStream);/*  ww  w .  j a  v  a 2 s. c o m*/
    JsonParser parser = null;
    try {
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        double proportion = -1d;
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();

            if ("neanderthal".equals(field)) {
                while (parser.nextToken() != JsonToken.END_OBJECT) {
                    String neanderthalField = parser.getCurrentName();
                    parser.nextToken();

                    if ("proportion".equals(neanderthalField)) {
                        proportion = Double.parseDouble(parser.getText());
                    }
                }
            }
        }
        return proportion;
    } catch (IOException e) {
        logger.warn("could not parse neanderthal proportion", e);
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
    return -1d;
}

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

protected void runLoop() {
    paused = false;//ww w  .j a v  a  2 s  .  co  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);
}

From source file:net.floodlightcontroller.loadbalancer.PoolsResource.java

protected LBPool jsonToPool(String json) throws IOException {
    if (json == null)
        return null;

    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    LBPool pool = new LBPool();

    try {//ww  w.j av  a2  s.c  o  m
        jp = f.createJsonParser(json);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }

    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }

    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }

        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals(""))
            continue;
        if (n.equals("id")) {
            pool.id = jp.getText();
            continue;
        }
        if (n.equals("tenant_id")) {
            pool.tenantId = jp.getText();
            continue;
        }
        if (n.equals("name")) {
            pool.name = jp.getText();
            continue;
        }
        if (n.equals("network_id")) {
            pool.netId = jp.getText();
            continue;
        }
        if (n.equals("lb_method")) {
            pool.lbMethod = Short.parseShort(jp.getText());
            continue;
        }
        if (n.equals("protocol")) {
            String tmp = jp.getText();
            if (tmp.equalsIgnoreCase("TCP")) {
                pool.protocol = IPv4.PROTOCOL_TCP;
            } else if (tmp.equalsIgnoreCase("UDP")) {
                pool.protocol = IPv4.PROTOCOL_UDP;
            } else if (tmp.equalsIgnoreCase("ICMP")) {
                pool.protocol = IPv4.PROTOCOL_ICMP;
            }
            continue;
        }
        if (n.equals("vip_id")) {
            pool.vipId = jp.getText();
            continue;
        }

        log.warn("Unrecognized field {} in " + "parsing Pools", jp.getText());
    }
    jp.close();

    return pool;
}

From source file:com.unboundid.scim2.client.requests.SearchRequestBuilder.java

/**
 * Invoke the SCIM retrieve request./*  w w  w .  ja v a  2  s. c om*/
 *
 * @param post {@code true} to send the request using POST or {@code false}
 *             to send the request using GET.
 * @param <T> The type of objects to return.
 * @param resultHandler The search result handler that should be used to
 *                      process the resources.
 * @param cls The Java class object used to determine the type to return.
 * @throws ScimException If an error occurred.
 */
private <T> void invoke(final boolean post, final SearchResultHandler<T> resultHandler, final Class<T> cls)
        throws ScimException {
    Response response;
    if (post) {
        Set<String> attributeSet = null;
        Set<String> excludedAttributeSet = null;
        if (attributes != null && attributes.size() > 0) {
            if (!excluded) {
                attributeSet = attributes;
            } else {
                excludedAttributeSet = attributes;
            }
        }

        SearchRequest searchRequest = new SearchRequest(attributeSet, excludedAttributeSet, filter, sortBy,
                sortOrder, startIndex, count);

        Invocation.Builder builder = target().path(ApiConstants.SEARCH_WITH_POST_PATH_EXTENSION)
                .request(ScimService.MEDIA_TYPE_SCIM_TYPE, MediaType.APPLICATION_JSON_TYPE);
        for (Map.Entry<String, List<Object>> header : headers.entrySet()) {
            builder = builder.header(header.getKey(), StaticUtils.listToString(header.getValue(), ", "));
        }
        response = builder.post(Entity.entity(searchRequest, getContentType()));
    } else {
        response = buildRequest().get();
    }

    try {
        if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) {
            InputStream inputStream = response.readEntity(InputStream.class);
            try {
                JsonParser parser = JsonUtils.getObjectReader().getFactory().createParser(inputStream);
                try {
                    parser.nextToken();
                    boolean stop = false;
                    while (!stop && parser.nextToken() != JsonToken.END_OBJECT) {
                        String field = parser.getCurrentName();
                        parser.nextToken();
                        if (field.equals("schemas")) {
                            parser.skipChildren();
                        } else if (field.equals("totalResults")) {
                            resultHandler.totalResults(parser.getIntValue());
                        } else if (field.equals("startIndex")) {
                            resultHandler.startIndex(parser.getIntValue());
                        } else if (field.equals("itemsPerPage")) {
                            resultHandler.itemsPerPage(parser.getIntValue());
                        } else if (field.equals("Resources")) {
                            while (parser.nextToken() != JsonToken.END_ARRAY) {
                                if (!resultHandler.resource(parser.readValueAs(cls))) {
                                    stop = true;
                                    break;
                                }
                            }
                        } else if (SchemaUtils.isUrn(field)) {
                            resultHandler.extension(field, parser.<ObjectNode>readValueAsTree());
                        } else {
                            // Just skip this field
                            parser.nextToken();
                        }
                    }
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    parser.close();
                }
            } catch (IOException e) {
                throw new ResponseProcessingException(response, e);
            }
        } else {
            throw toScimException(response);
        }
    } finally {
        response.close();
    }
}

From source file:com.github.heuermh.ensemblrestclient.JacksonVariationConverter.java

static Variation parseVariation(final JsonFactory jsonFactory, final InputStream inputStream)
        throws IOException {
    JsonParser parser = null;
    try {/* w  w  w  .j  av a 2  s  .c  o  m*/
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        String identifier = null;
        String referenceAllele = null;
        List<String> alternateAlleles = new ArrayList<String>();

        String locationName = null;
        String coordinateSystem = "chromosome";
        int start = -1;
        int end = -1;
        int strand = -1;

        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();
            if ("name".equals(field)) {
                identifier = parser.getText();
            } else if ("mappings".equals(field)) {
                // todo:  will only catch last mapping
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    while (parser.nextToken() != JsonToken.END_OBJECT) {
                        String mappingsField = parser.getCurrentName();
                        parser.nextToken();

                        if ("seq_region_name".equals(mappingsField)) {
                            locationName = parser.getText();
                        } else if ("start".equals(mappingsField)) {
                            start = Integer.parseInt(parser.getText());
                        } else if ("end".equals(mappingsField)) {
                            end = Integer.parseInt(parser.getText());
                        } else if ("strand".equals(mappingsField)) {
                            strand = Integer.parseInt(parser.getText());
                        } else if ("allele_string".equals(mappingsField)) {
                            String[] tokens = parser.getText().split("/");
                            // todo:  check ref here against ancestral_allele
                            referenceAllele = tokens[0];
                            for (int i = 1; i < tokens.length; i++) {
                                alternateAlleles.add(tokens[i]);
                            }
                        }
                    }
                }
            } else if ("synonyms".equals(field)) {
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    // ignore
                }
            } else if ("evidence".equals(field)) {
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    // ignore
                }
            }
        }
        return new Variation(identifier, referenceAllele, alternateAlleles,
                new Location(locationName, coordinateSystem, start, end, strand));
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
}

From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java

/**
 * Parses the first GeoJSON feature to create the PreparedStatement.
 *
 * @throws SQLException//from ww w .  j  av  a2 s  .c  o  m
 * @throws IOException
 */
private boolean parseMetadata() throws SQLException, IOException {
    FileInputStream fis = null;
    StringBuilder metadataBuilder = new StringBuilder();
    try {
        fis = new FileInputStream(fileName);
        this.fc = fis.getChannel();
        this.fileSize = fc.size();
        // Given the file size and an average node file size.
        // Skip how many nodes in order to update progression at a step of 1%
        readFileSizeEachNode = Math.max(1, (this.fileSize / AVERAGE_NODE_SIZE) / 100);
        nodeCountProgress = 0;

        JsonParser jp = jsFactory.createParser(fis);
        metadataBuilder.append("CREATE TABLE ");
        metadataBuilder.append(tableLocation);
        metadataBuilder.append(" (");

        jp.nextToken();//START_OBJECT
        jp.nextToken(); // field_name (type)
        jp.nextToken(); // value_string (FeatureCollection)
        String geomType = jp.getText();

        if (geomType.equalsIgnoreCase(GeoJsonField.FEATURECOLLECTION)) {
            jp.nextToken(); // FIELD_NAME features
            String firstParam = jp.getText();
            //Read the CRS
            if (firstParam.equalsIgnoreCase(GeoJsonField.CRS)) {
                parsedSRID = readCRS(jp);
                readFeatures(jp, geomType, metadataBuilder);
            } else if (firstParam.equalsIgnoreCase(GeoJsonField.FEATURES)) {
                readFeatures(jp, geomType, metadataBuilder);
            } else {
                throw new SQLException(
                        "Malformed GeoJSON file. Expected 'features', found '" + firstParam + "'");
            }
        } else {
            throw new SQLException(
                    "Malformed GeoJSON file. Expected 'FeatureCollection', found '" + geomType + "'");
        }
        jp.close();
    } catch (FileNotFoundException ex) {
        throw new SQLException(ex);

    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (IOException ex) {
            throw new IOException(ex);
        }
    }

    // Now we create the table if there is at leat one geometry field.
    if (hasGeometryField) {
        Statement stmt = connection.createStatement();
        stmt.execute(metadataBuilder.toString());
        stmt.close();

        if (fieldIndex > 0) {
            StringBuilder insert = new StringBuilder("INSERT INTO ").append(tableLocation)
                    .append(" VALUES ( ?");
            for (int i = 1; i < fieldIndex; i++) {
                insert.append(",?");
            }
            insert.append(");");
            preparedStatement = connection.prepareStatement(insert.toString());
            return true;
        }
    } else {
        throw new SQLException("The first feature must contains a geometry field.");
    }
    return false;
}

From source file:com.amazonaws.http.JsonRxNettyResponseHandler.java

public Observable<AmazonWebServiceResponse<T>> handle(HttpClientResponse<ByteBuf> response) throws Exception {

    return response.getContent().reduce(new ByteArrayOutputStream(), (out, bb) -> {
        try {/*from  w  ww . j  a  v  a  2  s  .  co  m*/
            bb.readBytes(out, bb.readableBytes());
            return out;
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        } finally {
            ReferenceCountUtil.safeRelease(bb);
        }
    }).observeOn(RxSchedulers.computation()).map(out -> {
        return new ByteArrayInputStream(out.toByteArray());
    }).map(in -> {
        String CRC32Checksum = response.getHeaders().get("x-amz-crc32");
        CRC32ChecksumCalculatingInputStream crc32ChecksumInputStream = null;
        JsonParser jsonParser = null;
        try {
            if (!needsConnectionLeftOpen) {
                if (CRC32Checksum != null) {
                    crc32ChecksumInputStream = new CRC32ChecksumCalculatingInputStream(in);
                    jsonParser = jsonFactory.createJsonParser(crc32ChecksumInputStream);
                } else {
                    jsonParser = jsonFactory.createJsonParser(in);
                }
            }

            AmazonWebServiceResponse<T> awsResponse = new AmazonWebServiceResponse<T>();
            JsonUnmarshallerContext unmarshallerContext = new JsonRxNettyUnmarshallerContextImpl(jsonParser,
                    response.getHeaders());
            registerAdditionalMetadataExpressions(unmarshallerContext);

            T result = responseUnmarshaller.unmarshall(unmarshallerContext);

            if (CRC32Checksum != null) {
                long serverSideCRC = Long.parseLong(CRC32Checksum);
                long clientSideCRC = crc32ChecksumInputStream.getCRC32Checksum();
                if (clientSideCRC != serverSideCRC) {
                    throw new CRC32MismatchException(
                            "Client calculated crc32 checksum didn't match that calculated by server side ["
                                    + clientSideCRC + " != " + serverSideCRC + "]");
                }
            }

            awsResponse.setResult(result);

            Map<String, String> metadata = unmarshallerContext.getMetadata();
            metadata.put(ResponseMetadata.AWS_REQUEST_ID, response.getHeaders().get("x-amzn-RequestId"));
            awsResponse.setResponseMetadata(new ResponseMetadata(metadata));

            log.trace("Done parsing service response");
            return awsResponse;
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        } catch (java.lang.Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (!needsConnectionLeftOpen) {
                try {
                    jsonParser.close();
                } catch (Exception e) {
                }
            }
        }
    });
}

From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java

@Override
public PersonalGenomeClientException parseException(final InputStream inputStream) {
    checkNotNull(inputStream);/*from  w  w  w . j  av a2  s .c  om*/
    JsonParser parser = null;
    try {
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        String error = null;
        String errorDescription = null;
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();

            if ("error".equals(field)) {
                error = parser.getText();
            } else if ("error_description".equals(field)) {
                errorDescription = parser.getText();
            }
        }
        if ("access_denied".equals(error)) {
            return new AccessDeniedException(errorDescription);
        } else if ("invalid_client".equals(error)) {
            return new InvalidClientException(errorDescription);
        } else if ("invalid_request".equals(error)) {
            return new InvalidRequestException(errorDescription);
        } else if ("invalid_scope".equals(error)) {
            return new InvalidScopeException(errorDescription);
        }
        return new PersonalGenomeClientException(errorDescription);
    } catch (IOException e) {
        logger.warn("could not parse exception", e);
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
    return new PersonalGenomeClientException("unknown error");
}