Example usage for com.google.gson GsonBuilder GsonBuilder

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

Introduction

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

Prototype

public GsonBuilder() 

Source Link

Document

Creates a GsonBuilder instance that can be used to build Gson with various configuration settings.

Usage

From source file:cc.telepath.phage.PhageGroup.java

License:GNU General Public License

/**
 * Announce a new AES Key on all private channels.
 *//*w  w  w  .ja va2  s  .  c  o m*/
public void newEpochAnnouncement(String newKey, PhageFCPClient pcl)
        throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException,
        SignatureException, InvalidKeyException, IOException, FcpException, NoSuchProviderException {
    Crypto c = new Crypto();
    Base64 base64 = new Base64();
    GsonBuilder b = new GsonBuilder();
    b.disableHtmlEscaping();
    Gson g = b.create();
    for (PhageIdentity pi : identityList) {
        EpochAnnouncement announcement = new EpochAnnouncement(newKey, identityList);
        String stringAnnouncement = g.toJson(announcement);
        String AESkey = c.generateAESKey();
        byte[] encryptedAnnouncement = c.AESEncrypt(stringAnnouncement.getBytes(), AESkey);
        //EncrypotAndSign adds a colon to the string so we've been checking the wrong string
        //FIXME
        String encryptedKey = c.encryptAndSign(pi.getPubkey(), this.PrivateKey, AESkey);
        try {
            System.out.println(
                    c.AESDecrypt(base64.decode(new String(base64.encode(encryptedAnnouncement))), AESkey));
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        System.out.println("Membership announcement on "
                + pcl.putData(privateChannels.get(pi.getFreenetPubkey()).replace("KSK@", ""),
                        (encryptedKey + ":" + new String(base64.encode(encryptedAnnouncement))).getBytes(),
                        null, null, "text/plain", false));
    }
}

From source file:cc.tochat.webserver.model.message.AbstractMessage.java

License:Apache License

public AbstractMessage() {
    this.gson = new GsonBuilder().setExclusionStrategies(new AnnotationExclusionStrategy()).create();
}

From source file:ccm.pay2spawn.configurator.Configurator.java

License:Open Source License

public void saveMainJsonToFile() {
    try {/*  ww w.j a  va 2 s . c  o m*/
        BufferedWriter bw = new BufferedWriter(new FileWriter(Pay2Spawn.getRewardDBFile()));
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        bw.write(gson.toJson(rootArray));
        bw.close();
    } catch (IOException e) {
        Pay2Spawn.getLogger().warn("Could not save JSON file from configurator!");
        e.printStackTrace();
    }

    Pay2Spawn.reloadDB();
}

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  av a 2s. c o  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;/*from   w  w  w .  ja  v a 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   w  ww .j a v  a 2 s.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();/*from ww  w . ja v a2 s.c o m*/

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

    String line = null;
    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:cd.go.contrib.elasticagents.docker.Agent.java

License:Apache License

public static String toJSONArray(Collection<Agent> metadata) {
    return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create()
            .toJson(metadata);/*from  ww w  . j  av a 2 s  .  co m*/
}

From source file:cd.go.contrib.task.skeleton.ExecuteRequest.java

License:Apache License

public GoPluginApiResponse execute(GoPluginApiRequest request) {
    CurlTaskExecutor executor = new CurlTaskExecutor();
    Map executionRequest = (Map) new GsonBuilder().create().fromJson(request.requestBody(), Object.class);
    Map config = (Map) executionRequest.get("config");
    Map context = (Map) executionRequest.get("context");

    Result result = executor.execute(new TaskConfig(config), new Context(context),
            JobConsoleLogger.getConsoleLogger());
    return new DefaultGoPluginApiResponse(result.responseCode(), TaskPlugin.GSON.toJson(result.toMap()));
}

From source file:cd.go.contrib.task.skeleton.ValidateRequest.java

License:Apache License

public GoPluginApiResponse execute(GoPluginApiRequest request) {
    HashMap<String, Object> validationResult = new HashMap<>();
    int responseCode = DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE;
    Map configMap = (Map) new GsonBuilder().create().fromJson(request.requestBody(), Object.class);
    HashMap errorMap = new HashMap();
    if (!configMap.containsKey(TaskPlugin.URL_PROPERTY)
            || ((Map) configMap.get(TaskPlugin.URL_PROPERTY)).get("value") == null
            || ((String) ((Map) configMap.get(TaskPlugin.URL_PROPERTY)).get("value")).trim().isEmpty()) {
        errorMap.put(TaskPlugin.URL_PROPERTY, "URL cannot be empty");
    }//w w  w.  ja  v a2 s  . c  o  m
    validationResult.put("errors", errorMap);
    return new DefaultGoPluginApiResponse(responseCode, TaskPlugin.GSON.toJson(validationResult));
}