Example usage for com.google.gson GsonBuilder create

List of usage examples for com.google.gson GsonBuilder create

Introduction

In this page you can find the example usage for com.google.gson GsonBuilder create.

Prototype

public Gson create() 

Source Link

Document

Creates a Gson instance based on the current configuration.

Usage

From source file:cd.education.data.collector.android.tasks.GoogleMapsEngineAbstractUploader.java

License:Apache License

private String buildJSONSubmission(HashMap<String, String> answersToUpload,
        HashMap<String, PhotoEntry> uploadedPhotos) throws GeoPointNotFoundException {
    final GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Feature.class, new FeatureSerializer());
    gsonBuilder.registerTypeAdapter(ArrayList.class, new FeatureListSerializer());
    final Gson gson = gsonBuilder.create();

    Map<String, String> properties = new HashMap<String, String>();
    properties.put("gx_id", String.valueOf(System.currentTimeMillis()));

    // there has to be a geo point, else we can't upload
    boolean foundGeo = false;
    PointGeometry pg = null;//w w  w  . j  a va 2s  .  co  m

    Iterator<String> answerIterator = answersToUpload.keySet().iterator();
    while (answerIterator.hasNext()) {
        String path = answerIterator.next();
        String answer = answersToUpload.get(path);

        // the instances don't have data types, so we try to match a
        // fairly specific pattern to determine geo coordinates, so we
        // pattern match against our answer
        // [-]#.# [-]#.# #.# #.#
        if (!foundGeo) {
            Pattern p = Pattern
                    .compile("^-?[0-9]+\\.[0-9]+\\s-?[0-9]+\\.[0-9]+\\s-?[0-9]+\\.[0-9]+\\s[0-9]+\\.[0-9]+$");
            Matcher m = p.matcher(answer);
            if (m.matches()) {
                foundGeo = true;
                // split on spaces, take the first two, which are lat
                // long
                String[] tokens = answer.split(" ");
                pg = new PointGeometry();
                pg.type = "Point";
                pg.setCoordinates(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[0]));
            }
        }

        // geo or not, add to properties
        properties.put(path, answer);
    }

    if (!foundGeo) {
        throw new GeoPointNotFoundException("Instance has no Coordinates! Unable to upload");
    }

    // then add the urls for photos
    Iterator<String> photoIterator = uploadedPhotos.keySet().iterator();
    while (photoIterator.hasNext()) {
        String path = photoIterator.next();
        String url = uploadedPhotos.get(path).getImageLink();
        properties.put(path, url);
    }

    Feature f = new Feature();
    f.geometry = pg;
    f.properties = properties;

    // gme expects an array of features for uploads, even though we only
    // send one
    ArrayList<Feature> features = new ArrayList<Feature>();
    features.add(f);

    return gson.toJson(features);
}

From source file:cd.education.data.collector.android.tasks.GoogleMapsEngineAbstractUploader.java

License:Apache License

private String getGmeTableID(String projectid, String jrformid, String token, String md5) throws IOException {

    String gmetableid = null;// ww w  .j a va 2s .c  o  m
    // first check to see if form exists.

    // if a project ID has been defined
    String url = "https://www.googleapis.com/mapsengine/v1/tables";
    if (projectid != null) {
        url = url + "?projectId=" + projectid;
    }

    HttpURLConnection conn = null;
    TablesListResponse tables = null;
    boolean found = false;

    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();

    // keep fetching while nextToken exists
    // and we haven't found a matching table
    findtableloop: while (tables == null || tables.nextPageToken != null) {
        String openUrl = url + "&where=Name=" + jrformid;

        if (tables != null && tables.nextPageToken != null) {
            openUrl = url + "&pageToken=" + tables.nextPageToken;
        } else {
            openUrl = url;
        }
        Log.i(tag, "trying to open url: " + openUrl);
        URL fullUrl = new URL(openUrl);

        conn = (HttpURLConnection) fullUrl.openConnection();
        conn.setRequestMethod("GET");
        conn.addRequestProperty("Authorization", "OAuth " + token);
        conn.connect();

        if (conn.getResponseCode() != 200) {
            String errorString = getErrorMesssage(conn.getErrorStream());
            throw new IOException(errorString);
        }

        BufferedReader br = null;
        br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        if (tables != null) {
            tables.nextPageToken = null;
            tables = null;
        }
        tables = gson.fromJson(br, TablesListResponse.class);

        for (int i = 0; i < tables.tables.length; i++) {
            Table t = tables.tables[i];
            for (int j = 0; j < t.tags.length; j++) {
                if (md5.equalsIgnoreCase(t.tags[j])) {
                    found = true;
                    gmetableid = t.id;
                    break findtableloop;
                }
            }
        }

        br.close();

        // GME has 1q/s limit
        try {
            Thread.sleep(GME_SLEEP_TIME);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    if (!found) {
        return null;
    } else {
        return gmetableid;
    }

}

From source file:cd.education.data.collector.android.tasks.GoogleMapsEngineAbstractUploader.java

License:Apache License

private String createTable(String jrformid, String projectid, String md5, String token, String formFilePath)
        throws FileNotFoundException, XmlPullParserException, IOException, FormException {
    ArrayList<String> columnNames = new ArrayList<String>();
    getColumns(formFilePath, columnNames);

    String gmetableid = null;//from   ww  w  .ja  va2s. c o m
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();

    Table t = new Table();
    t.name = jrformid;
    Log.i(tag, "Using GME projectid : " + projectid);
    t.projectId = projectid;

    Column first = new Column();
    first.name = "geometry";
    first.type = "points";

    Column[] columns = new Column[columnNames.size() + 1];
    columns[0] = first;

    for (int i = 0; i < columnNames.size(); i++) {
        Column c = new Column();
        c.name = columnNames.get(i);
        c.type = "string";
        columns[i + 1] = c;
    }

    Schema s = new Schema();
    s.columns = columns;
    t.schema = s;
    String[] tags = { md5 };
    t.tags = tags;
    t.description = "auto-created by ODK Collect for formid " + jrformid;

    URL createTableUrl = new URL("https://www.googleapis.com/mapsengine/v1/tables");
    HttpURLConnection sendConn = null;
    int status = -1;

    final String json = gson.toJson(t);

    sendConn = (HttpURLConnection) createTableUrl.openConnection();
    sendConn.setReadTimeout(10000 /* milliseconds */);
    sendConn.setConnectTimeout(15000 /* milliseconds */);
    sendConn.setRequestMethod("POST");
    sendConn.setDoInput(true);
    sendConn.setDoOutput(true);
    sendConn.setFixedLengthStreamingMode(json.getBytes().length);

    // make some HTTP header nicety
    sendConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
    sendConn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
    sendConn.addRequestProperty("Authorization", "OAuth " + token);

    // setup send
    OutputStream os = new BufferedOutputStream(sendConn.getOutputStream());
    os.write(json.getBytes());
    // clean up
    os.flush();

    status = sendConn.getResponseCode();
    if (status != 200) {
        String errorString = getErrorMesssage(sendConn.getErrorStream());
        throw new IOException(errorString);
    } else {
        BufferedReader br = new BufferedReader(new InputStreamReader(sendConn.getInputStream()));

        Table table = gson.fromJson(br, Table.class);
        Log.i(tag, "found table id :: " + table.id);
        gmetableid = table.id;
    }

    return gmetableid;
}

From source file:cd.education.data.collector.android.tasks.GoogleMapsEngineTask.java

License:Apache License

protected String getErrorMesssage(InputStream is) {
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();

    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    StringBuilder jsonResponseBuilder = new StringBuilder();

    String line = null;//from   w w  w.j  a va2s. c  o  m
    try {
        while ((line = br.readLine()) != null) {
            jsonResponseBuilder.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    String jsonResponse = jsonResponseBuilder.toString();
    Log.i(tag, "GME json response : " + jsonResponse);

    GMEErrorResponse errResp = gson.fromJson(jsonResponse, GMEErrorResponse.class);
    StringBuilder sb = new StringBuilder();
    sb.append(gme_fail + "\n");

    if (errResp.error.errors != null) {
        for (int i = 0; i < errResp.error.errors.length; i++) {
            sb.append(errResp.error.errors[i].message + "\n");
        }
    } else {
        sb.append(errResp.error.message + "\n");
    }
    return sb.toString();
}

From source file:ch.admin.suis.msghandler.servlet.MonitorServlet.java

License:Open Source License

private String toJson(Object obj, Class c) {
    GsonBuilder gsonBilder = new GsonBuilder();
    Gson gson = gsonBilder.create();

    return gson.toJson(obj, c);
}

From source file:ch.berta.fabio.popularmovies.data.rest.MovieDbClient.java

License:Apache License

/**
 * Returns a custom date deserializer that handles empty strings and returns today's date instead.
 *
 * @return the Gson object to use/*from www. j  a v  a 2  s .  com*/
 */
private static Gson getGsonObject() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        final DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US);

        @Override
        public Date deserialize(final JsonElement json, final Type typeOfT,
                final JsonDeserializationContext context) throws JsonParseException {
            try {
                return dateFormat.parse(json.getAsString());
            } catch (ParseException e) {
                return new Date();
            }
        }
    });

    return gsonBuilder.create();
}

From source file:ch.devmine.javaparser.utils.GsonFactory.java

License:Open Source License

public static Gson build() {
    GsonBuilder builder = new GsonBuilder();
    builder.addSerializationExclusionStrategy(new ExclusionStrategy() {

        @Override/*  w  ww. jav  a  2  s  .co m*/
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getAnnotation(GsonTransient.class) != null;
        }

        @Override
        public boolean shouldSkipClass(Class<?> c) {
            return c.getAnnotation(GsonTransient.class) != null;
        }
    });
    return builder.create();
}

From source file:ch.uzh.supersede.feedbacklibrary.FeedbackActivity.java

License:Apache License

public void sendButtonClicked(View view) {
    if (baseURL != null && language != null) {
        // The mechanism models are updated with the view values
        for (MechanismView mechanismView : allMechanismViews) {
            mechanismView.updateModel();
        }/*from   w  ww.ja  v  a 2  s .  com*/

        final ArrayList<String> messages = new ArrayList<>();
        if (validateInput(allMechanisms, messages)) {
            if (fbAPI == null) {
                Retrofit rtf = new Retrofit.Builder().baseUrl(baseURL)
                        .addConverterFactory(GsonConverterFactory.create()).build();
                fbAPI = rtf.create(feedbackAPI.class);
            }

            Call<ResponseBody> checkUpAndRunning = fbAPI.pingRepository();
            if (checkUpAndRunning != null) {
                checkUpAndRunning.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.e(TAG, "Failed to ping the server. onFailure method called", t);
                        DialogUtils
                                .showInformationDialog(FeedbackActivity.this,
                                        new String[] { getResources()
                                                .getString(R.string.supersede_feedbacklibrary_error_text) },
                                        true);
                    }

                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (response.code() == 200) {
                            Feedback feedback = new Feedback(allMechanisms);
                            feedback.setTitle(getResources().getString(
                                    R.string.supersede_feedbacklibrary_feedback_title_text,
                                    System.currentTimeMillis()));
                            feedback.setApplicationId(orchestratorConfiguration.getId());
                            feedback.setConfigurationId(activeConfiguration.getId());
                            feedback.setLanguage(language);
                            feedback.setUserIdentification(Settings.Secure.getString(getContentResolver(),
                                    Settings.Secure.ANDROID_ID));

                            // The JSON string of the feedback
                            GsonBuilder builder = new GsonBuilder();
                            builder.excludeFieldsWithoutExposeAnnotation();
                            builder.serializeNulls();
                            Gson gson = builder.create();
                            Type feedbackType = new TypeToken<Feedback>() {
                            }.getType();
                            String feedbackJsonString = gson.toJson(feedback, feedbackType);
                            RequestBody feedbackJSONPart = RequestBody
                                    .create(MediaType.parse("multipart/form-data"), feedbackJsonString);

                            Map<String, RequestBody> files = new HashMap<>();
                            // Audio multipart
                            List<AudioFeedback> audioFeedbackList = feedback.getAudioFeedbacks();
                            if (audioFeedbackList != null) {
                                for (int pos = 0; pos < audioFeedbackList.size(); ++pos) {
                                    RequestBody requestBody = createRequestBody(
                                            new File(audioFeedbackList.get(pos).getAudioPath()));
                                    String fileName = audioFeedbackList.get(pos).getFileName();
                                    String key = String.format("%1$s\"; filename=\"%2$s",
                                            audioFeedbackList.get(pos).getPartString() + String.valueOf(pos),
                                            fileName);
                                    files.put(key, requestBody);
                                }
                            }
                            // Screenshots multipart
                            List<ScreenshotFeedback> screenshotFeedbackList = feedback.getScreenshotFeedbacks();
                            if (screenshotFeedbackList != null) {
                                for (int pos = 0; pos < screenshotFeedbackList.size(); ++pos) {
                                    RequestBody requestBody = createRequestBody(
                                            new File(screenshotFeedbackList.get(pos).getImagePath()));
                                    String fileName = screenshotFeedbackList.get(pos).getFileName();
                                    String key = String.format("%1$s\"; filename=\"%2$s",
                                            screenshotFeedbackList.get(pos).getPartString()
                                                    + String.valueOf(pos),
                                            fileName);
                                    files.put(key, requestBody);
                                }
                            }

                            // Send the feedback
                            Call<JsonObject> result = fbAPI.createFeedbackVariant(language,
                                    feedback.getApplicationId(), feedbackJSONPart, files);
                            if (result != null) {
                                result.enqueue(new Callback<JsonObject>() {
                                    @Override
                                    public void onFailure(Call<JsonObject> call, Throwable t) {
                                        Log.e(TAG, "Failed to send the feedback. onFailure method called", t);
                                        DialogUtils.showInformationDialog(FeedbackActivity.this,
                                                new String[] { getResources().getString(
                                                        R.string.supersede_feedbacklibrary_error_text) },
                                                true);
                                    }

                                    @Override
                                    public void onResponse(Call<JsonObject> call,
                                            Response<JsonObject> response) {
                                        if (response.code() == 201) {
                                            Log.i(TAG, "Feedback successfully sent");
                                            Toast toast = Toast.makeText(getApplicationContext(),
                                                    getResources().getString(
                                                            R.string.supersede_feedbacklibrary_success_text),
                                                    Toast.LENGTH_SHORT);
                                            toast.show();
                                        } else {
                                            Log.e(TAG, "Failed to send the feedback. Response code == "
                                                    + response.code());
                                            DialogUtils.showInformationDialog(FeedbackActivity.this,
                                                    new String[] { getResources().getString(
                                                            R.string.supersede_feedbacklibrary_error_text) },
                                                    true);
                                        }
                                    }
                                });
                            } else {
                                Log.e(TAG, "Failed to send the feebdkack. Call<JsonObject> result is null");
                                DialogUtils.showInformationDialog(FeedbackActivity.this,
                                        new String[] { getResources()
                                                .getString(R.string.supersede_feedbacklibrary_error_text) },
                                        true);
                            }
                        } else {
                            Log.e(TAG, "The server is not up and running. Response code == " + response.code());
                            DialogUtils
                                    .showInformationDialog(FeedbackActivity.this,
                                            new String[] { getResources()
                                                    .getString(R.string.supersede_feedbacklibrary_error_text) },
                                            true);
                        }
                    }
                });
            } else {
                Log.e(TAG, "Failed to ping the server. Call<ResponseBody> checkUpAndRunning result is null");
                DialogUtils.showInformationDialog(FeedbackActivity.this,
                        new String[] {
                                getResources().getString(R.string.supersede_feedbacklibrary_error_text) },
                        true);
            }
        } else {
            Log.v(TAG, "Validation of the mechanism failed");
            DialogUtils.showInformationDialog(this, messages.toArray(new String[messages.size()]), false);
        }
    } else {
        if (baseURL == null) {
            Log.e(TAG, "Failed to send the feedback. baseURL is null");
        } else {
            Log.e(TAG, "Failed to send the feedback. language is null");
        }
        DialogUtils.showInformationDialog(this,
                new String[] { getResources().getString(R.string.supersede_feedbacklibrary_error_text) }, true);
    }
}

From source file:citysdk.tourism.client.parser.JsonParser.java

License:Open Source License

private Deserializable parseJson(Class<? extends Deserializable> clazz) throws UnknownErrorException {
    if (json == null)
        return null;

    Logger logger = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
    logger.fine("Deserializing for " + clazz);
    logger.finest("JSON is: " + json);
    Deserializable deserialize;//from  w w  w.j a v a2s.  com
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(clazz, new POIDeserializer());

    Gson gson = builder.create();
    try {
        deserialize = gson.fromJson(json, clazz);
    } catch (Exception e) {
        throw new UnknownErrorException("There was an error handling the request: " + e.getMessage(), e);
    }

    logger.fine("Done deserialization");
    return deserialize;
}

From source file:cl.niclabs.cb.common.MethodParser.java

License:Open Source License

public static Gson makeGson(MethodFactory factory) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Method.class, new MethodParser(factory));
    return gsonBuilder.create();
}