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:at.ac.tuwien.big.we14.lab2.api.impl.JSONQuestionDataProvider.java

License:Open Source License

@Override
public List<Category> loadCategoryData() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Category.class, new CategoryDeserializer(factory));

    gsonBuilder.registerTypeAdapter(Question.class, new QuestionDeserialzier(factory));

    Gson gson = gsonBuilder.create();/*ww  w. ja  v a 2 s. c  om*/

    Type collectionType = new TypeToken<List<Category>>() {
    }.getType();
    List<Category> categories = gson.fromJson(new InputStreamReader(inputStream, Charsets.UTF_8),
            collectionType);

    return categories;
}

From source file:at.ac.tuwien.big.we15.lab2.api.impl.JSONQuestionDataProvider.java

License:Open Source License

@Override
public List<Category> getCategoryData() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Category.class, new CategoryDeserializer());
    gsonBuilder.registerTypeAdapter(Question.class, new QuestionDeserialzier());

    Gson gson = gsonBuilder.create();/* w w  w.j  a va 2s  .  co  m*/
    Type collectionType = new TypeToken<List<Category>>() {
    }.getType();
    List<Category> categories = gson.fromJson(new InputStreamReader(inputStream, Charsets.UTF_8),
            collectionType);

    return categories;
}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.services.AppRepository.java

License:Apache License

private String listFolderToJson(String pathName) {
    try {//from  ww w  .  j  a  va2 s .co m
        FolderJsonList serviceList = new FolderJsonList(pathName);
        Gson json = new GsonBuilder().setPrettyPrinting().create();
        return json.toJson(serviceList);
    } catch (Exception e) {
        logger.error("Could not list the folder: " + pathName);
        return "";
    }
}

From source file:at.ac.uniklu.mobile.sportal.api.UnikluApiClient.java

License:Open Source License

private void init() {
    // init http client
    int timeout = 20000;
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setSoTimeout(httpParams, timeout);
    mHttpClient = new DefaultHttpClient(httpParams);
    mHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        @Override/*from  w ww  . j av  a2  s  .c  o m*/
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            logDebug("request retry " + executionCount + ": " + exception.getClass().getName());
            if (executionCount < 3) {
                if (exception instanceof SSLException) {
                    return true;
                }
                if (exception instanceof SocketTimeoutException) {
                    return true;
                }
                if (exception instanceof ConnectTimeoutException) {
                    return true;
                }
            }
            return false;
        }
    });

    // init gson & configure it to match server's output format
    mGson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
            .registerTypeAdapter(Notification.Type.class, new GsonNotificationTypeDeserializer()).create();
}

From source file:at.ac.uniklu.mobile.sportal.MapActivity.java

License:Open Source License

@TargetApi(11)
@SuppressLint("SetJavaScriptEnabled")
@Override//from w w w. ja  v  a  2 s.c  om
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map);
    mActionBar = new ActionBarHelper(this).setupHeader();

    mGson = new GsonBuilder().create();

    mWebView = (WebView) findViewById(R.id.web_view);
    mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); // hide right scroll border on android < 3
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(false);
    mWebView.getSettings().setUseWideViewPort(false);
    mWebView.addJavascriptInterface(new SpJavaScriptInterface(), "sp");
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1
            && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        /* disable hardware acceleration:
         * - results in better rendering performance on Android 3.x & 4.0
         * - avoids webkit bugs in Android 4.x with OpenLayers and Leaflet
         */
        mWebView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
    }
    mWebView.setWebViewClient(new WebViewTimeoutClient(30000) {
        private boolean timeout;

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            progressNotificationOn();
            timeout = false;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            progressNotificationOff();
            if (failingUrl != null && failingUrl.equals(MAP_URL)) {
                showTimeoutMessage();
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            if (MapActivity.this.isFinishing()) {
                /* do nothing if activity has already been closed
                 * (avoids android.view.WindowManager$BadTokenException because of
                 * a following showDialog() call)
                 */
                return;
            }

            // this method is only called once since the remaining data is loaded asynchronously
            progressNotificationOff();
            if (!timeout) {
                getCampusLayers();
                getPoiLayers();
                if (mPendingSearch) {
                    mPendingSearch = false;
                    searchRoom(mPendingSearchQuery);
                }
            }
        }

        @Override
        public void onTimeout() {
            Log.d(TAG, "timeout");
            timeout = true;
            mWebView.stopLoading();
            showTimeoutMessage();
            Analytics.onEvent(Analytics.EVENT_MAP_UNAVAILABLE);
        }
    });

    View uniPositionButton = findViewById(R.id.uni_position);
    uniPositionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            zoomToUni();
        }
    });

    View searchButton = findViewById(R.id.search);
    searchButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mSearchPanels[mActiveSearchPanel].getVisibility() != View.GONE) {
                onSearchRequested(); // hide current form
            }
            mActiveSearchPanel = 0;
            onSearchRequested();
        }
    });

    View routeButton = findViewById(R.id.route);
    routeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mSearchPanels[mActiveSearchPanel].getVisibility() != View.GONE) {
                onSearchRequested(); // hide current form
            }
            mActiveSearchPanel = 1;
            onSearchRequested();
        }
    });

    View currentPositionButton = findViewById(R.id.current_position);
    currentPositionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location == null) {
                Toast.makeText(MapActivity.this, R.string.map_error_nolocation, Toast.LENGTH_LONG).show();
            } else {
                Log.d(TAG, location.toString());
                panTo(location.getLongitude(), location.getLatitude());
            }
        }
    });

    View campusLayersButton = findViewById(R.id.campuslayers);
    campusLayersButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mCampusLayers == null || mCampusLayers.isEmpty())
                return;

            AlertDialog.Builder builder = new AlertDialog.Builder(MapActivity.this);
            builder.setTitle(R.string.map_floors);
            builder.setSingleChoiceItems(mCampusLayers.getListItems(),
                    mCampusLayers.getListSingleSelectionIndex(), new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int item) {
                            dialog.dismiss();
                            showCampusLayer(item);
                            mCampusLayers.deselectAll();
                            mCampusLayers.select(item);
                            Analytics.onEvent(Analytics.EVENT_MAP_LAYERSWITCH_CAMPUS, "layer",
                                    mCampusLayers.get(item).name);
                        }
                    });
            builder.setNeutralButton(R.string.close, new AlertDialogOnClickDismissHandler());
            builder.create().show();
        }
    });

    View poiLayersButton = findViewById(R.id.poilayers);
    poiLayersButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mPoiLayers == null || mPoiLayers.isEmpty())
                return;

            AlertDialog.Builder builder = new AlertDialog.Builder(MapActivity.this);
            builder.setTitle(R.string.map_pois);
            builder.setMultiChoiceItems(mPoiLayers.getListItems(), mPoiLayers.getListMultiSelection(),
                    new DialogInterface.OnMultiChoiceClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                            dialog.dismiss();
                            if (isChecked) {
                                showPoiLayer(which);
                                Analytics.onEvent(Analytics.EVENT_MAP_LAYERSWITCH_POI, "layer",
                                        mPoiLayers.get(which).name);
                            } else {
                                hidePoiLayer(which);
                            }
                            mPoiLayers.toggle(which);

                        }
                    });
            builder.setNeutralButton(R.string.close, new AlertDialogOnClickDismissHandler());
            builder.create().show();
        }
    });

    AutoCompleteTextView searchInput1 = (AutoCompleteTextView) findViewById(R.id.searchpanel_input);
    AutoCompleteTextView searchInput2 = (AutoCompleteTextView) findViewById(R.id.searchpanel_input_from);
    AutoCompleteTextView searchInput3 = (AutoCompleteTextView) findViewById(R.id.searchpanel_input_to);
    mSearchTexts = new AutoCompleteTextView[] { searchInput1, searchInput2, searchInput3 };
    View.OnFocusChangeListener searchInputFocusListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus)
                mSearchText = (AutoCompleteTextView) v;
        }
    };
    TextView.OnEditorActionListener searchInputActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId != EditorInfo.IME_ACTION_SEARCH)
                return false;

            if (mActiveSearchPanel == 0)
                searchRoom(v.getText().toString());
            else
                searchRoute(mSearchTexts[1].getText().toString(), mSearchTexts[2].getText().toString(),
                        mSearchMode);

            mSearchPanels[mActiveSearchPanel].setVisibility(View.GONE);

            // hide keyboard
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

            return true;
        }
    };
    AdapterView.OnItemClickListener searchDropdownSelectionListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            mSearchText.onEditorAction(mSearchText.getImeOptions());
        }
    };
    TextWatcher searchInputWatcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            autocompleteRoomNameCancel();
            autocompleteRoomName(s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };
    for (AutoCompleteTextView si : mSearchTexts) {
        si.setOnFocusChangeListener(searchInputFocusListener);
        si.setOnEditorActionListener(searchInputActionListener);
        si.addTextChangedListener(searchInputWatcher);
        si.setOnItemClickListener(searchDropdownSelectionListener);
    }

    View searchPanel1 = findViewById(R.id.searchpanel);
    View searchPanel2 = findViewById(R.id.searchpanel2);
    mSearchPanels = new View[] { searchPanel1, searchPanel2 };

    findViewById(R.id.searchpanel_toggle_disability).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ImageButton ib = (ImageButton) v;
            mSearchMode = ib.getDrawable().getLevel() == SEARCHMODE_DEFAULT ? SEARCHMODE_ACCESSIBLE_WHEELCHAIR
                    : SEARCHMODE_DEFAULT;
            ib.setImageLevel(mSearchMode);
        }
    });

    // process search requests
    Uri data = getIntent().getData();
    if (data != null) {
        String url = data.toString();
        String room = url.substring(url.indexOf("?") + 1);
        mPendingSearch = true;
        mPendingSearchQuery = room;
    }

    loadMap();
}

From source file:at.alladin.rmbt.controlServer.ServerResource.java

License:Apache License

public static Gson getGson(boolean prettyPrint) {
    GsonBuilder gb = new GsonBuilder().registerTypeAdapter(DateTime.class, new MyDateTimeAdapter());
    if (prettyPrint)
        gb = gb.setPrettyPrinting();/*from  w  w  w  .  j  av  a  2  s. c  o  m*/
    return gb.create();
}

From source file:at.alladin.rmbt.statisticServer.opendata.OpenTestStatisticsResource.java

License:Apache License

/**
 * Get JSON array containing conducted tests at different time intervals
 * //from  w w w .j av  a  2 s .com
 * @param qp
 * @return
 * @throws SQLException
 */
private String getStatistics(QueryParser qp) throws SQLException {
    // build the sql query
    StringBuilder selectStatement = new StringBuilder();
    selectStatement.append("SELECT CASE ");
    for (int i = 0; i < intervalsMins.length; i++) {
        selectStatement.append(String.format(
                "WHEN (time > (current_timestamp - interval '%d minutes')) THEN '%d' ", intervalsMins[i], i));
    }
    selectStatement.append(" END as ident ");

    // concatenate sql with the CASE statement
    String query = "SELECT ident, count(ident) as cnt FROM (" + selectStatement.toString() + "FROM test t "
            + "LEFT JOIN network_type nt ON nt.uid=t.network_type"
            + " LEFT JOIN device_map adm ON adm.codename=t.model"
            + " LEFT JOIN test_server ts ON ts.uid=t.server_id"
            + " LEFT JOIN provider prov ON provider_id = prov.uid "
            + " LEFT JOIN provider mprov ON mobile_provider_id = mprov.uid" + " WHERE" + " t.deleted = false"
            + " AND status = 'FINISHED' " + qp.getWhereClause("AND")
            + "AND time > (current_timestamp - interval '" + intervalsMins[intervalsMins.length - 1]
            + " minutes'" + ")" + ") a GROUP BY ident ORDER BY ident ASC;";

    PreparedStatement stmt = conn.prepareStatement(query);
    qp.fillInWhereClause(stmt, 1);
    ResultSet rs = stmt.executeQuery();

    HashMap<Integer, Long> map = new HashMap<>();
    for (int i = 0; i < intervalsMins.length; i++) {
        map.put(intervalsMins[i], 0l);
    }

    long tests = 0;
    while (rs.next()) {
        int interval = intervalsMins[rs.getInt("ident")];
        tests += rs.getLong("cnt");
        map.put(interval, tests);
    }

    //now, change keys to different time measurements depending on #mins for better readability
    HashMap<String, Long> retMap = new HashMap<>();
    for (Integer interval : map.keySet()) {
        long t = map.get(interval);

        //use different time measurements depending on #mins
        if (interval % (60 * 24) == 0 && (interval / (60 * 24)) > 1) {
            retMap.put((interval / (60 * 24)) + "d", t);
        } else if ((interval % 60) == 0 && (interval / 60) > 1) {
            retMap.put((interval / 60) + "h", t);
        } else {
            retMap.put(interval + "min", t);
        }
    }

    return new GsonBuilder().create().toJson(retMap);
}

From source file:at.alladin.rmbt.util.model.option.ServerOption.java

License:Apache License

public static Gson getGson() {
    Gson gson = new GsonBuilder().registerTypeAdapter(ServerOption.class, new ServerOptionParentDeserializer())
            .excludeFieldsWithoutExposeAnnotation().create();
    return gson;//from  ww  w  .  j  ava2  s  . co m
}

From source file:at.illecker.hama.hybrid.examples.util.benchmark.BenchmarkLogger.java

License:Apache License

public String getJson() {
    String jsonStr = "";
    Gson gson = new GsonBuilder().create();
    for (Scenario s : scenarios) {
        jsonStr += gson.toJson(s);// ww w .  j  a v  a  2s . c o m
    }
    return jsonStr;
}

From source file:at.illecker.storm.commons.util.io.JsonUtils.java

License:Apache License

public static List<Map<String, Object>> readJsonStream(InputStream jsonInputStream) {
    BufferedReader br = null;/*from   ww w. j a v a2 s  .  com*/
    try {
        br = new BufferedReader(new InputStreamReader(jsonInputStream));
        GsonBuilder builder = new GsonBuilder();
        List<Map<String, Object>> elements = (List<Map<String, Object>>) builder.create().fromJson(br,
                Object.class);
        LOG.info("Loaded " + " elements: " + elements.size());
        return elements;
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException ignore) {
            }
        }
    }
}