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:ch.ethz.inf.vs.hypermedia.corehal.block.CoREHalResourceFuture.java

License:Open Source License

public static GsonBuilder getGsonBuilder() {
    return new GsonBuilder().registerTypeAdapter(LinkList.class, new LinkListDeserializer())
            .registerTypeAdapter(OptionalList.class, new OptionalListDeserializer())
            .registerTypeAdapter(FormList.class, new FormListDeserializer()).serializeNulls();
}

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

License:Open Source License

/**
 * To save the state of the software, the tab, the servers and the databases.
 *//*from  w  w  w . j av a2  s . c o  m*/
public void saveState() {
    try {
        os = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("save.json")));
        Gson jsonEngine = new GsonBuilder().setPrettyPrinting().create();
        JsonArray mainArray = new JsonArray();

        for (Server s : servers) {
            JsonObject server = new JsonObject();

            server.addProperty("serverDescription", s.getDescription());
            server.addProperty("serverDriver", s.getDiverName());
            server.addProperty("serverHost", s.getHost());
            server.addProperty("serverPort", s.getPort());

            JsonArray databases = new JsonArray();

            for (Database db : s.getDatabases()) {

                JsonObject database = new JsonObject();

                database.addProperty("databaseDescritpion", db.getDescritpion());
                database.addProperty("databaseName", db.getName());
                database.addProperty("databaseUsername", db.getUsername());

                JsonArray tabsJson = new JsonArray();

                tabs.forEach(editorTab -> {
                    if (editorTab.getDatabase() == db) {

                        JsonObject tabJson = new JsonObject();
                        tabJson.addProperty("tabName", "name");
                        tabJson.addProperty("moduleName", editorTab.getModuleName());
                        tabJson.addProperty("content", editorTab.getEditorController().getContent());
                        tabsJson.add(tabJson);
                    }
                });

                database.add("tabs", tabsJson);

                databases.add(database);

            }
            server.add("databases", databases);

            mainArray.add(server);
        }

        os.write(jsonEngine.toJson(mainArray));
        os.flush();

    } catch (IOException e) {
        addToUserCommunication(e.getMessage());
    }
}

From source file:ch.njol.skript.update.ReleaseManifest.java

License:Open Source License

/**
 * Loads a release manifest from JSON.//from  ww w .  j a v  a  2s  . c o  m
 * @param json Release manifest.
 * @return A release manifest.
 * @throws JsonParseException If the given JSON was not valid.
 */
@SuppressWarnings("null")
public static ReleaseManifest load(String json) throws JsonParseException {
    return new GsonBuilder().registerTypeAdapter(Class.class, new ClassSerializer()).create().fromJson(json,
            ReleaseManifest.class);
}

From source file:ch.puzzle.itc.mobiliar.business.generator.control.extracted.templates.BaseTemplateProcessor.java

License:Open Source License

private void logBeforeException(TemplateException te, Map<String, Object> contextualizedMap) {
    log.info("Template Fehler: ");
    log.severe(te.getLocalizedMessage());
    log.severe(new GsonBuilder().setPrettyPrinting().create().toJson(contextualizedMap));
}

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();
        }/* ww w .  j  a v a 2  s  . c  om*/

        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:ching.icecreaming.action.ResourceDescriptors.java

License:Open Source License

@Action(value = "resource-descriptors", results = { @Result(name = "success", location = "json.jsp") })
public String execute() throws Exception {
    int int1 = 401, int0 = 0;
    String string1 = null;/* w  w  w. java  2  s  .  c  om*/
    URL url1 = null;
    URI uri1 = null;
    HttpGet httpGet1 = null;
    HttpResponse httpResponse1 = null;
    HttpEntity httpEntity1 = null;
    HttpPost httpPost1 = null;
    HttpHost httpHost1 = null;
    DefaultHttpClient httpClient1 = null;
    File file1 = null;
    InputStream inputStream1 = null;
    OutputStream outputStream1 = null;
    BeanComparator beanComparator1 = null;
    List<Map<String, Object>> list1 = null, list2 = null;
    Map<String, Object> map1 = null;
    Object object1 = null;
    int toIndex = rows * page;
    int fromIndex = toIndex - rows;
    GridModel1 jsonObject1 = null;
    Gson gson = null;
    Long long1 = -1L;
    java.util.Date date1 = null;
    URIBuilder uriBuilder1 = null;
    Node node1 = null;
    Element element1 = null;
    NodeList nodeList1 = null;
    Document document1 = null;
    DocumentBuilder documentBuilder1 = null;
    DocumentBuilderFactory documentBuilderFactory1 = null;
    org.joda.time.DateTime dateTime1 = null, dateTime2 = null;

    try {
        if (StringUtils.isNotEmpty(sid) && StringUtils.isNotEmpty(uid) && StringUtils.isNotEmpty(pid)) {
            sid = new String(Base64.decodeBase64(sid.getBytes()));
            uid = new String(Base64.decodeBase64(uid.getBytes()));
            pid = new String(Base64.decodeBase64(pid.getBytes()));
            httpClient1 = new DefaultHttpClient();
            url1 = new URL(sid);
            uriBuilder1 = new URIBuilder(sid);
            uriBuilder1.setParameter("j_username", uid);
            uriBuilder1.setParameter("j_password", pid);
            uriBuilder1.setPath(url1.getPath() + "/rest/resources" + urlString);
            uriBuilder1.setUserInfo(uid, pid);
            uri1 = uriBuilder1.build();
            httpGet1 = new HttpGet(uri1);
            httpResponse1 = httpClient1.execute(httpGet1);
            int1 = httpResponse1.getStatusLine().getStatusCode();
            if (int1 == HttpStatus.SC_OK) {
                httpEntity1 = httpResponse1.getEntity();
                inputStream1 = httpResponse1.getEntity().getContent();
                if (inputStream1 != null) {
                    documentBuilderFactory1 = DocumentBuilderFactory.newInstance();
                    documentBuilder1 = documentBuilderFactory1.newDocumentBuilder();
                    document1 = documentBuilder1.parse(inputStream1);
                    document1.getDocumentElement().normalize();
                    nodeList1 = document1.getElementsByTagName("resourceDescriptor");
                    int1 = nodeList1.getLength();
                    list1 = new ArrayList<Map<String, Object>>();
                    for (int0 = 0; int0 < int1; int0++) {
                        node1 = nodeList1.item(int0);
                        if (node1.getNodeType() == Node.ELEMENT_NODE) {
                            element1 = (Element) node1;
                            map1 = new HashMap<String, Object>();
                            map1.put("wsType", element1.getAttribute("wsType"));
                            map1.put("uriString", element1.getAttribute("uriString"));
                            string1 = getTagValue("label", element1);
                            map1.put("label1", StringUtils.defaultString(string1));
                            string1 = getTagValue("description", element1);
                            map1.put("description", StringUtils.defaultString(string1));
                            string1 = getTagValue("creationDate", element1);
                            long1 = (string1 == null) ? -1L
                                    : NumberUtils.toLong(StringUtils.trim(string1), -1L);
                            if (long1 > 0) {
                                if (StringUtils.isNotBlank(timeZone1)) {
                                    dateTime1 = new org.joda.time.DateTime(long1);
                                    dateTime2 = dateTime1.withZone(DateTimeZone.forID(timeZone1));
                                    date1 = dateTime2.toLocalDateTime().toDate();
                                } else {
                                    date1 = new java.util.Date(long1);
                                }
                            } else {
                                date1 = null;
                            }
                            map1.put("creationDate", date1);
                            map1.put("type1", getText(element1.getAttribute("wsType")));
                            list1.add(map1);
                        }
                    }
                }
                EntityUtils.consume(httpEntity1);
            }
        }
    } catch (UnsupportedEncodingException | URISyntaxException | ParserConfigurationException
            | SAXException exception1) {
        exception1.printStackTrace();
        return ERROR;
    } catch (org.apache.http.conn.HttpHostConnectException | java.net.NoRouteToHostException
            | java.net.MalformedURLException | java.net.UnknownHostException exception1) {
        exception1.printStackTrace();
        return ERROR;
    } catch (IOException exception1) {
        httpGet1.abort();
        exception1.printStackTrace();
        return ERROR;
    } finally {
        if (httpClient1 != null)
            httpClient1.getConnectionManager().shutdown();
        if (list1 != null) {
            records = list1.size();
            if (list1.size() > 0) {
                if (StringUtils.isNotEmpty(sidx)) {
                    if (StringUtils.equals(sord, "desc")) {
                        beanComparator1 = new BeanComparator(sidx,
                                new ReverseComparator(new ComparableComparator()));
                    } else {
                        beanComparator1 = new BeanComparator(sidx);
                    }
                    Collections.sort(list1, beanComparator1);
                }
                if (StringUtils.isNotBlank(searchField) && StringUtils.isNotEmpty(searchOper)) {
                    Iterator iterator1 = list1.iterator();
                    while (iterator1.hasNext()) {
                        map1 = (Map<String, Object>) iterator1.next();
                        for (Map.Entry<String, Object> entry1 : map1.entrySet()) {
                            if (StringUtils.equals(entry1.getKey(), searchField)) {
                                object1 = entry1.getValue();
                                if (searchFilter(searchField, searchOper, searchString, object1))
                                    iterator1.remove();
                                break;
                            }
                        }
                    }
                    records = list1.size();
                }
                if (toIndex > records)
                    toIndex = records;
                if (fromIndex > toIndex) {
                    fromIndex = toIndex - rows;
                    if (fromIndex < 0)
                        fromIndex = 0;
                }
                if (list1.size() > 0 && fromIndex >= 0 && toIndex <= list1.size() && fromIndex <= toIndex)
                    list2 = list1.subList(fromIndex, toIndex);

            }
            total = (int) Math.ceil((double) records / (double) rows);
            if (page > total)
                page = total;
            jsonObject1 = new GridModel1(rows, page, sord, sidx, searchField, searchString, searchOper, total,
                    records, id, list2);
            gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSS").create();
            jsonData = gson.toJson(jsonObject1);
        }
        IOUtils.closeQuietly(inputStream1);
    }
    return SUCCESS;
}

From source file:ching.icecreaming.action.TimeZones.java

License:Open Source License

@Action(value = "time-zones", results = { @Result(name = "success", location = "json.jsp") })
public String execute() {
    String[] array1 = TimeZone.getAvailableIDs();
    List<String> list1 = Arrays.asList(array1);
    Arrays.sort(array1);/*from w  ww .  j  a  va 2  s.  co  m*/
    Map<String, List<String>> map0 = new HashMap<String, List<String>>();
    map0.put("timeZones", list1);
    Gson gson = new GsonBuilder().create();
    jsonData = gson.toJson(map0);
    return SUCCESS;
}

From source file:cht.Parser.java

License:Apache License

public static void main(String[] args) throws IOException {

    // TODO get from google drive
    boolean isUnicode = false;
    boolean isRemoveInputFileOnComplete = false;
    int rowNum;//w  w  w .  j  ava2 s . com
    int colNum;
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    Properties prop = new Properties();

    try {
        prop.load(new FileInputStream("config.txt"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    String inputFilePath = prop.getProperty("inputFile");
    String outputDirectory = prop.getProperty("outputDirectory");
    System.out.println(outputDirectory);
    // optional
    String unicode = prop.getProperty("unicode");
    String removeInputFileOnComplete = prop.getProperty("removeInputFileOnComplete");

    inputFilePath = inputFilePath.trim();
    outputDirectory = outputDirectory.trim();

    if (unicode != null) {
        isUnicode = Boolean.parseBoolean(unicode.trim());
    }
    if (removeInputFileOnComplete != null) {
        isRemoveInputFileOnComplete = Boolean.parseBoolean(removeInputFileOnComplete.trim());
    }

    Writer out = null;
    FileInputStream in = null;
    final String newLine = System.getProperty("line.separator").toString();
    final String separator = File.separator;
    try {
        in = new FileInputStream(inputFilePath);

        Workbook workbook = new XSSFWorkbook(in);

        Sheet sheet = workbook.getSheetAt(0);

        rowNum = sheet.getLastRowNum() + 1;
        colNum = sheet.getRow(0).getPhysicalNumberOfCells();

        for (int j = 1; j < colNum; ++j) {
            String outputFilename = sheet.getRow(0).getCell(j).getStringCellValue();
            // guess directory
            int slash = outputFilename.indexOf('/');
            if (slash != -1) { // has directory
                outputFilename = outputFilename.substring(0, slash) + separator
                        + outputFilename.substring(slash + 1);
            }

            String outputPath = FilenameUtils.concat(outputDirectory, outputFilename);
            System.out.println("--Writing " + outputPath);
            out = new OutputStreamWriter(new FileOutputStream(outputPath), "UTF-8");
            TreeMap<String, Object> map = new TreeMap<String, Object>();
            for (int i = 1; i < rowNum; i++) {
                try {
                    String key = sheet.getRow(i).getCell(0).getStringCellValue();
                    //String value = "";
                    Cell tmp = sheet.getRow(i).getCell(j);
                    if (tmp != null) {
                        // not empty string!
                        value = sheet.getRow(i).getCell(j).getStringCellValue();
                    }
                    if (!key.equals("") && !key.startsWith("#") && !key.startsWith(".")) {
                        value = isUnicode ? StringEscapeUtils.escapeJava(value) : value;

                        int firstdot = key.indexOf(".");
                        String keyName, keyAttribute;
                        if (firstdot > 0) {// a.b.c.d 
                            keyName = key.substring(0, firstdot); // a
                            keyAttribute = key.substring(firstdot + 1); // b.c.d
                            TreeMap oldhash = null;
                            Object old = null;
                            if (map.get(keyName) != null) {
                                old = map.get(keyName);
                                if (old instanceof TreeMap == false) {
                                    System.out.println("different type of key:" + key);
                                    continue;
                                }
                                oldhash = (TreeMap) old;
                            } else {
                                oldhash = new TreeMap();
                            }

                            int firstdot2 = keyAttribute.indexOf(".");
                            String rootName, childName;
                            if (firstdot2 > 0) {// c, d.f --> d, f
                                rootName = keyAttribute.substring(0, firstdot2);
                                childName = keyAttribute.substring(firstdot2 + 1);
                            } else {// c, d  -> d, null
                                rootName = keyAttribute;
                                childName = null;
                            }

                            TreeMap<String, Object> object = myPut(oldhash, rootName, childName);
                            map.put(keyName, object);

                        } else {// c, d  -> d, null
                            keyName = key;
                            keyAttribute = null;
                            // simple string mode
                            map.put(key, value);
                        }

                    }

                } catch (Exception e) {
                    // just ingore empty rows
                }

            }
            String json = gson.toJson(map);
            // output json
            out.write(json + newLine);
            out.close();
        }
        in.close();

        System.out.println("\n---Complete!---");
        System.out.println("Read input file from " + inputFilePath);
        System.out.println(colNum - 1 + " output files ate generated at " + outputDirectory);
        System.out.println(rowNum + " records are generated for each output file.");
        System.out.println("output file is ecoded as unicode? " + (isUnicode ? "yes" : "no"));
        if (isRemoveInputFileOnComplete) {
            File input = new File(inputFilePath);
            input.deleteOnExit();
            System.out.println("Deleted " + inputFilePath);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            in.close();
        }
    }

}

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  . jav  a2  s. co m*/
    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.magnet.magnetrestclient.requests.GsonRequest.java

License:Open Source License

/**
 * This method is used to obtain the {com.google.gson.Gson} object that will parse the
 * response. It can be overriden in order to customize {com.google.gson.Gson}
 * with various configuration settings./*from   w w  w .  j  ava 2 s.  c  om*/
 *
 * @return The gson object that will parse the response
 */
protected Gson getGson() {
    return new GsonBuilder().setDateFormat(DATE_FORMAT).create();
}