Example usage for com.google.gson.stream JsonReader JsonReader

List of usage examples for com.google.gson.stream JsonReader JsonReader

Introduction

In this page you can find the example usage for com.google.gson.stream JsonReader JsonReader.

Prototype

public JsonReader(Reader in) 

Source Link

Document

Creates a new instance that reads a JSON-encoded stream from in .

Usage

From source file:ch.cyberduck.core.importer.ExpandriveBookmarkCollection.java

License:Open Source License

@Override
protected void parse(final Local file) throws AccessDeniedException {
    try {/*  ww  w .  ja  v a 2  s . c  o  m*/
        final JsonReader reader = new JsonReader(new InputStreamReader(file.getInputStream(), "UTF-8"));
        reader.beginArray();
        while (reader.hasNext()) {
            reader.beginObject();
            final Host current = new Host(new FTPProtocol(),
                    PreferencesFactory.get().getProperty("connection.hostname.default"));
            while (reader.hasNext()) {
                final String name = reader.nextName();
                switch (name) {
                case "server":
                    current.setHostname(reader.nextString());
                    break;
                case "username":
                    current.getCredentials().setUsername(reader.nextString());
                    break;
                case "private_key_file":
                    current.getCredentials().setIdentity(LocalFactory.get(reader.nextString()));
                    break;
                case "remotePath":
                    current.setDefaultPath(reader.nextString());
                    break;
                case "type":
                    final Protocol type = ProtocolFactory.forName(reader.nextString());
                    if (null != type) {
                        current.setProtocol(type);
                    }
                    break;
                case "protocol":
                    final Protocol protocol = ProtocolFactory.forName(reader.nextString());
                    if (null != protocol) {
                        current.setProtocol(protocol);
                        // Reset port to default
                        current.setPort(-1);
                    }
                    break;
                case "name":
                    current.setNickname(reader.nextString());
                    break;
                case "region":
                    current.setRegion(reader.nextString());
                    break;
                default:
                    log.warn(String.format("Ignore property %s", name));
                    reader.skipValue();
                    break;
                }
            }
            reader.endObject();
            this.add(current);
        }
        reader.endArray();
    } catch (IllegalStateException | IOException e) {
        throw new LocalAccessDeniedException(e.getMessage(), e);
    }
}

From source file:ch.cyberduck.core.importer.NetDrive2BookmarkCollection.java

License:Open Source License

@Override
protected void parse(final ProtocolFactory protocols, final Local file) throws AccessDeniedException {
    try {//w w w .  j  av a  2s .co m
        final JsonReader reader = new JsonReader(new InputStreamReader(file.getInputStream(), "UTF-8"));
        reader.beginArray();
        String url;
        String user;
        boolean ssl;
        Protocol protocol;
        while (reader.hasNext()) {
            reader.beginObject();
            boolean skip = false;
            url = null;
            ssl = false;
            protocol = null;
            user = null;
            while (reader.hasNext()) {
                final String name = reader.nextName();
                switch (name) {
                case "url":
                    url = this.readNext(name, reader);
                    if (StringUtils.isBlank(url)) {
                        skip = true;
                    }
                    break;
                case "ssl":
                    ssl = reader.nextBoolean();
                    break;
                case "user":
                    user = this.readNext(name, reader);
                    break;
                case "type":
                    final String type = this.readNext(name, reader);
                    switch (type) {
                    case "google_cloud_storage":
                        protocol = protocols.forType(Protocol.Type.googlestorage);
                        break;
                    case "gdrive":
                        protocol = protocols.forType(Protocol.Type.googledrive);
                        break;
                    default:
                        protocol = protocols.forName(type);
                    }
                    break;

                default:
                    log.warn(String.format("Ignore property %s", name));
                    reader.skipValue();
                    break;
                }
            }
            reader.endObject();
            if (!skip && protocol != null && StringUtils.isNotBlank(user)) {
                if (ssl) {
                    switch (protocol.getType()) {
                    case ftp:
                        protocol = protocols.forScheme(Scheme.ftps);
                        break;
                    case dav:
                        protocol = protocols.forScheme(Scheme.davs);
                        break;
                    }
                }
                this.add(HostParser.parse(protocols, protocol, url));
            }
        }
        reader.endArray();
    } catch (IllegalStateException | IOException e) {
        throw new LocalAccessDeniedException(e.getMessage(), e);
    }
}

From source file:ch.cyberduck.core.s3.S3SessionCredentialsRetriever.java

License:Open Source License

protected AWSCredentials parse(final InputStream in) throws BackgroundException {
    try {/* ww w  .  ja  v  a 2 s. c  o  m*/
        final JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
        reader.beginObject();
        String key = null;
        String secret = null;
        String token = null;
        while (reader.hasNext()) {
            final String name = reader.nextName();
            final String value = reader.nextString();
            switch (name) {
            case "AccessKeyId":
                key = value;
                break;
            case "SecretAccessKey":
                secret = value;
                break;
            case "Token":
                token = value;
                break;
            }
        }
        reader.endObject();
        return new AWSSessionCredentials(key, secret, token);
    } catch (UnsupportedEncodingException e) {
        throw new BackgroundException(e);
    } catch (MalformedJsonException e) {
        throw new InteroperabilityException("Invalid JSON response", e);
    } catch (IOException e) {
        throw new DefaultIOExceptionMappingService().map(e);
    }
}

From source file:ch.gaps.slasher.views.main.MainController.java

License:Open Source License

/**
 * Read the save file and laod all the data in the software
 *
 * @throws IOException//from  www . jav  a  2 s  .c  o m
 */
private void readSave() {
    try {
        Gson gson = new Gson();
        JsonReader reader = new JsonReader(new FileReader("save.json"));
        JsonArray mainArray = gson.fromJson(reader, JsonArray.class);

        LinkedList<Driver> drivers = DriverService.instance().getAll();

        if (mainArray != null) {
            for (JsonElement e : mainArray) {
                JsonObject server = e.getAsJsonObject();

                Driver driver = null;

                String serverDriver = server.get("serverDriver").getAsString();

                for (Driver d : drivers) {
                    if (d.toString().equals(serverDriver)) {
                        driver = d.getClass().newInstance();
                    }
                }

                Server s = new Server(driver, server.get("serverHost").getAsString(),
                        server.get("serverPort").getAsInt(), server.get("serverDescription").getAsString());
                ServerTreeItem serverTreeItem = new ServerTreeItem(s);
                servers.add(s);

                JsonArray databases = server.get("databases").getAsJsonArray();

                if (databases != null) {
                    for (JsonElement d : databases) {
                        if (!serverDriver.equals("Sqlite")) {
                            driver = driver.getClass().newInstance();
                        }
                        JsonObject database = d.getAsJsonObject();

                        Database db = new Database(driver, database.get("databaseName").getAsString(),
                                database.get("databaseDescritpion").getAsString(), s,
                                database.get("databaseUsername").getAsString());
                        s.addDatabase(db);

                        if (serverDriver.equals("Sqlite")) {
                            try {
                                db.connect("");
                            } catch (SQLException | ClassNotFoundException e1) {
                                e1.printStackTrace();
                            }
                        }

                        JsonArray tabs = database.get("tabs").getAsJsonArray();

                        for (JsonElement t : tabs) {
                            JsonObject tab = t.getAsJsonObject();

                            if (tab.get("moduleName").getAsString().equals("Editor")) {
                                loadEditorTab(db, tab.get("content").getAsString());
                            }

                        }

                    }
                }
                rootTreeItem.getChildren().add(serverTreeItem);
            }
        }
    } catch (IOException | IllegalAccessException | InstantiationException e) {
        addToUserCommunication(e.getMessage());
    }
}

From source file:challenge.ona.CodeChallenge.java

public Object calculate(String url) throws IOException {

    System.out.println("Calculate: ");

    JSONObject result = new JSONObject();

    int working = 0;
    int not_working = 0;
    ArrayList<String> village_list = new ArrayList<String>();
    Map community_points = new HashMap();
    Map community_ranks = new HashMap();
    Map community_works = new HashMap();
    Map community_no_works = new HashMap();
    try {/* www  . j a va2 s .c om*/
        URL ona_json = new URL(url);
        URLConnection urlconn = ona_json.openConnection();
        InputStreamReader in = new InputStreamReader(urlconn.getInputStream());
        String name;
        String villages = "";
        String works;
        int counter;
        try (JsonReader jread = new JsonReader(in)) {
            jread.beginArray();
            while (jread.hasNext()) {
                jread.beginObject();
                while (jread.hasNext()) {
                    name = jread.nextName();
                    if (name.equals("communities_villages")) {
                        villages = jread.nextString();
                        village_list.add(villages);
                    } else if (name.equals("water_functioning")) {
                        works = jread.nextString();
                        if (works.equals("yes")) {
                            working++;
                            if (community_works.containsKey(villages)) {
                                counter = (Integer) community_works.get(villages);
                                community_works.put(villages, ++counter);
                            } else {
                                community_works.put(villages, 1);
                            }
                        } else if (works.equals("no")) {
                            not_working++;
                            if (community_no_works.containsKey(villages)) {
                                counter = (Integer) community_no_works.get(villages);
                                community_no_works.put(villages, ++counter);
                            } else {
                                community_no_works.put(villages, 1);
                            }
                        }
                    } else {
                        jread.skipValue();
                    }
                }
                jread.endObject();
            }
            jread.endArray();
        }

        Iterator it = village_list.iterator();
        while (it.hasNext()) {
            String unique_village = (String) it.next();
            int freq = Collections.frequency(village_list, unique_village);
            community_points.put(unique_village, freq);
            //                if (community_works.containsKey(unique_village)) {
            //                    worked = (Integer) community_works.get(unique_village);
            //                }
            //                if (community_no_works.containsKey(unique_village)) {
            //                    not_worked = (Integer) community_works.get(unique_village);
            //                }
            int worked = community_works.containsKey(unique_village) ? (int) community_works.get(unique_village)
                    : 0;
            int not_worked = community_no_works.containsKey(unique_village)
                    ? (int) community_no_works.get(unique_village)
                    : 0;
            int village_total = worked + not_worked;
            float percents = (float) not_worked / village_total * 100;
            community_ranks.put(unique_village, percents);
        }
        result.put("number_functional: ", working);
        result.put("number_water_points: ", community_points);
        result.put("community_ranking: ", community_ranks);
    } catch (MalformedURLException | JSONException ex) {
        Logger.getLogger(CodeChallenge.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:classifiers.DummyClassifier.java

License:Apache License

public void parseStreamAndClassify(String jsonFile, String resultsFile) throws IOException {

    String journalName;/*  w  w  w  . j  av  a 2s .  c  o  m*/
    int count = 0;
    int abstract_count = 0;

    try {
        JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(jsonFile)));
        JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(resultsFile), "UTF-8"));
        writer.setIndent("    ");

        //reader.setLenient(true);
        reader.beginArray();
        writer.beginArray();
        while (reader.hasNext()) {

            reader.beginObject();
            writer.beginObject();
            while (reader.hasNext()) {
                String name = reader.nextName();

                if (name.equals("abstract")) {
                    abstract_count++;
                    reader.skipValue();

                } else if (name.equals("pmid")) {
                    String pmid = reader.nextString();
                    writer.name("labels");
                    writeLabels(writer);
                    writer.name("pmid").value(pmid);
                } else if (name.equals("title")) {
                    reader.skipValue();
                } else {
                    System.out.println(name);
                    reader.skipValue();
                }
            }
            reader.endObject();
            writer.endObject();
        }
        reader.endArray();
        writer.endArray();

        System.out.println("Abstracts: " + abstract_count);

        writer.close();
    } catch (FileNotFoundException ex) {

    }
}

From source file:co.cask.cdap.client.StreamClient.java

License:Apache License

/**
 * Reads events from a stream/*from   ww w .jav  a2 s  .  c  o  m*/
 *
 * @param streamId ID of the stream
 * @param start Timestamp in milliseconds or now-xs format to start reading event from (inclusive)
 * @param end Timestamp in milliseconds or now-xs format for the last event to read (exclusive)
 * @param limit Maximum number of events to read
 * @param callback Callback to invoke for each stream event read. If the callback function returns {@code false}
 *                 upon invocation, it will stops the reading
 * @throws IOException If fails to read from stream
 * @throws StreamNotFoundException If the given stream does not exists
 */
public void getEvents(Id.Stream streamId, String start, String end, int limit,
        Function<? super StreamEvent, Boolean> callback)
        throws IOException, StreamNotFoundException, UnauthenticatedException {

    long startTime = TimeMathParser.parseTime(start, TimeUnit.MILLISECONDS);
    long endTime = TimeMathParser.parseTime(end, TimeUnit.MILLISECONDS);

    URL url = config.resolveNamespacedURLV3(streamId.getNamespace(), String
            .format("streams/%s/events?start=%d&end=%d&limit=%d", streamId.getId(), startTime, endTime, limit));
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
    AccessToken accessToken = config.getAccessToken();
    if (accessToken != null) {
        urlConn.setRequestProperty(HttpHeaders.AUTHORIZATION,
                accessToken.getTokenType() + " " + accessToken.getValue());
    }

    if (urlConn instanceof HttpsURLConnection && !config.isVerifySSLCert()) {
        try {
            HttpRequests.disableCertCheck((HttpsURLConnection) urlConn);
        } catch (Exception e) {
            // TODO: Log "Got exception while disabling SSL certificate check for request.getURL()"
        }
    }

    try {
        if (urlConn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            throw new UnauthenticatedException("Unauthorized status code received from the server.");
        }
        if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
            throw new StreamNotFoundException(streamId);
        }
        if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
            return;
        }

        // The response is an array of stream event object
        InputStream inputStream = urlConn.getInputStream();
        JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, Charsets.UTF_8));
        jsonReader.beginArray();
        while (jsonReader.peek() != JsonToken.END_ARRAY) {
            Boolean result = callback.apply(GSON.<StreamEvent>fromJson(jsonReader, StreamEvent.class));
            if (result == null || !result) {
                break;
            }
        }
        drain(inputStream);
        // No need to close reader, the urlConn.disconnect in finally will close all underlying streams
    } finally {
        urlConn.disconnect();
    }
}

From source file:co.cask.cdap.data.stream.StreamDataFileReader.java

License:Apache License

private void verifySchema(Map<String, String> properties) throws IOException {
    String schemaKey = StreamDataFileConstants.Property.Key.SCHEMA;
    String schemaStr = properties.get(schemaKey);
    if (schemaStr == null) {
        throw new IOException("Missing '" + schemaKey + "' property.");
    }//w w  w .jav  a  2  s  .  c  o  m

    try {
        Schema schema = new SchemaTypeAdapter().read(new JsonReader(new StringReader(schemaStr)));
        if (!StreamEventDataCodec.STREAM_DATA_SCHEMA.equals(schema)) {
            throw new IOException("Unsupported schema " + schemaStr);
        }

    } catch (JsonSyntaxException e) {
        throw new IOException("Invalid schema.", e);
    }
}

From source file:co.cask.cdap.format.StructuredRecordStringConverter.java

License:Apache License

/**
 * Converts a json string to a {@link StructuredRecord} based on the schema.
 *//*from   w  w  w  .  j ava2  s.  com*/
public static StructuredRecord fromJsonString(String json, Schema schema) throws IOException {
    JsonReader reader = new JsonReader(new StringReader(json));
    try {
        return (StructuredRecord) readJson(reader, schema);
    } finally {
        reader.close();
    }
}

From source file:co.cask.cdap.internal.MockResponder.java

License:Apache License

public <T> T decodeResponseContent(Type type, Gson gson) {
    JsonReader jsonReader = new JsonReader(
            new InputStreamReader(new ChannelBufferInputStream(content), Charsets.UTF_8));
    return gson.fromJson(jsonReader, type);
}