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:ca.twoducks.vor.ossindex.report.Assistant.java

License:Open Source License

/** Export the data in JSON format
 * /*from   w  w  w.j av a2s .com*/
 * @return
 */
@SuppressWarnings("unused")
private String exportJson() {
    Writer writer = new StringWriter();
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    gson.toJson(config, writer);

    return writer.toString();
}

From source file:ca.twoducks.vor.ossindex.report.Assistant.java

License:Open Source License

/** Export both the public JSON file to the specified directory.
 * /*from  www. ja  v a2 s .  c  o  m*/
 * @param dir
 */
private void exportPublicJson(File dir) throws IOException {
    // Write the public configuration file
    File publicFile = new File(dir, "vorindex.public.json");
    PrintWriter writer = new PrintWriter(new FileWriter(publicFile));
    try {
        config.touch();
        Gson gson = new GsonBuilder().setPrettyPrinting()
                .setExclusionStrategies(new PublicExclusionStrategy(exportDependencies)).create();
        gson.toJson(config, writer);
    } finally {
        writer.close();
    }
}

From source file:ca.twoducks.vor.ossindex.report.Assistant.java

License:Open Source License

/** Export both the private JSON file to the specified directory.
 * /*from ww w  .  ja  v  a2s . co  m*/
 * @param dir
 * @throws IOException
 */
private void exportPrivateJson(File dir) throws IOException {
    // Write the private configuration file
    File privateFile = new File(dir, "vorindex.private.json");
    PrintWriter writer = new PrintWriter(new FileWriter(privateFile));
    try {
        config.touch();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        gson.toJson(config, writer);
    } finally {
        writer.close();
    }
}

From source file:ca.twoducks.vor.ossindex.report.Assistant.java

License:Open Source License

/** Load a configuration from a specified JSON file.
 * /* www.  j av a 2 s .  c  om*/
 * @param file
 * @return
 * @throws IOException
 */
private Configuration load(File file) throws IOException {
    if (file.getName().endsWith(".csv")) {
        return loadCsv(file);
    } else {
        Reader reader = new FileReader(file);
        Gson gson = new GsonBuilder().create();
        try {
            return gson.fromJson(reader, Configuration.class);
        } finally {
            reader.close();
        }
    }
}

From source file:ca.ualberta.cmput301w14t08.geochan.helpers.GsonHelper.java

License:Apache License

private GsonHelper() {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Comment.class, new CommentJsonConverter());
    builder.registerTypeAdapter(ThreadComment.class, new ThreadCommentJsonConverter());
    builder.registerTypeAdapter(Bitmap.class, new BitmapJsonConverter());
    builder.registerTypeAdapter(Location.class, new LocationJsonConverter());
    onlineGson = builder.create();//from   ww  w. j av  a 2s  .co m
    builder = new GsonBuilder();
    builder.registerTypeAdapter(Comment.class, new CommentOfflineJsonConverter());
    builder.registerTypeAdapter(ThreadComment.class, new ThreadCommentOfflineJsonConverter());
    builder.registerTypeAdapter(Location.class, new LocationJsonConverter());
    offlineGson = builder.create();
    builder = new GsonBuilder();
    exposeGson = builder.excludeFieldsWithoutExposeAnnotation().create();
}

From source file:ca.ualberta.CMPUT301W15T06.ClaimListManager.java

License:Apache License

/**
 * General construction. Set a Context context as the context that user ntered using Gson Adapter.
 * /*from ww  w  . j  av a 2  s  .  c o  m*/
 * @param context  a Context object
 * @see android.content.Context
 * @see com.google.gson.Gson
 */
private ClaimListManager(Context context) {
    this.context = context;
    gson = new GsonBuilder().registerTypeAdapter(Claim.class, new GsonAdapter<Claim>())
            .registerTypeAdapter(Item.class, new GsonAdapter<Item>())
            .registerTypeAdapter(Destination.class, new GsonAdapter<Destination>())
            .registerTypeAdapter(Receipt.class, new GsonAdapter<Receipt>()).create();
}

From source file:ca.ualberta.CMPUT301W15T06.ESClient.java

License:Apache License

public ESClient() {
    gson = new GsonBuilder().registerTypeAdapter(Claim.class, new GsonAdapter<Claim>())
            .registerTypeAdapter(Item.class, new GsonAdapter<Item>())
            .registerTypeAdapter(Destination.class, new GsonAdapter<Destination>())
            .registerTypeAdapter(Receipt.class, new GsonAdapter<Receipt>()).create();
    if (AppSingleton.getInstance().isTest()) {
        USER_LIST = "http://cmput301.softwareprocess.es:8080/testing/usrlist/usrlist";

        USER = "http://cmput301.softwareprocess.es:8080/testing/usr/";
    } else {//from  w  ww.j  av a  2s . c o m
        USER_LIST = "http://cmput301.softwareprocess.es:8080/cmput301w15t06/usrlist/usrlist";

        USER = "http://cmput301.softwareprocess.es:8080/cmput301w15t06/usr/";
    }
}

From source file:ca.ualberta.cs.c301f12t01.serverStorage.ReportServerRetrieval.java

License:Apache License

/**
 * Method works to get reports and tasks
 * // ww w. j a  v  a  2s .  c  o m
 * @param id
 *            Server ID of the content we want to get
 * @return content from server
 */
public static Report getContentFromServer(String id) {
    // create our nvp
    List<BasicNameValuePair> nvp = new ArrayList<BasicNameValuePair>();
    nvp.add(new BasicNameValuePair("action", "get"));
    nvp.add(new BasicNameValuePair("id", id));
    // post
    Server server = new Server();
    String jsonString = server.post(nvp);

    // convert to SO
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Response.class, new ResponseDeserializer());
    Gson gson = gsonBuilder.create();

    ReportServerObj so = gson.fromJson(jsonString, ReportServerObj.class);
    return so.getContent();
}

From source file:ca.ualberta.cs.drivr.MainActivity.java

License:Apache License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    userManager.setConnectivityManager((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE));

    /**//from w ww .j  a va2s .c om
     * This calls the login activity a the beginning if there is no local user stored
     */
    if (userManager.getUser().getUsername().isEmpty()) {
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    context = getApplicationContext();
    PreferenceManager.setDefaultValues(this, R.xml.pref_driver_mode, false);

    setSupportActionBar(toolbar);

    // Create an instance of GoogleAPIClient.
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
    }

    mFragment = (SupportMapFragment) this.getSupportFragmentManager().findFragmentById(R.id.main_map);
    mFragment.getMapAsync(this);

    autocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager()
            .findFragmentById(R.id.place_autocomplete_fragment);

    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            ConcretePlace concretePlace = new ConcretePlace(place);
            Gson gson = new GsonBuilder().registerTypeAdapter(Uri.class, new UriSerializer()).create();
            if (userManager.getUserMode().equals(UserMode.RIDER)) {
                Intent intent = new Intent(MainActivity.this, NewRequestActivity.class);
                String concretePlaceJson = gson.toJson(concretePlace);
                intent.putExtra(NewRequestActivity.EXTRA_PLACE, concretePlaceJson);
                Log.i(TAG, "Place: " + place.getName() + ", :" + place.getLatLng());
                startActivity(intent);

            } else if (userManager.getUserMode().equals(UserMode.DRIVER)) {
                Intent intent = new Intent(MainActivity.this, SearchRequestActivity.class);
                String concretePlaceJson = gson.toJson(concretePlace);
                intent.putExtra(SearchRequestActivity.EXTRA_PLACE, concretePlaceJson);
                intent.putExtra(SearchRequestActivity.EXTRA_KEYWORD, "");
                Log.i(TAG, "Place: " + place.getName() + ", :" + place.getLatLng());
                startActivity(intent);
            }
        }

        @Override
        public void onError(Status status) {
            // Do nothing
        }
    });

    // Using the floating action button menu system
    final FloatingActionMenu fabMenu = (FloatingActionMenu) findViewById(R.id.main_fab_menu);
    FloatingActionButton fabSettings = (FloatingActionButton) findViewById(R.id.fabSettings);
    FloatingActionButton fabRequests = (FloatingActionButton) findViewById(R.id.main_fab_requests);
    FloatingActionButton fabProfile = (FloatingActionButton) findViewById(R.id.main_fab_profile);
    FloatingActionButton fabHistory = (FloatingActionButton) findViewById(R.id.main_fah_history);
    FloatingActionButton fabLogin = (FloatingActionButton) findViewById(R.id.main_fab_login);
    final FloatingActionButton fabDriver = (FloatingActionButton) findViewById(R.id.main_driver_mode);
    final FloatingActionButton fabRider = (FloatingActionButton) findViewById(R.id.main_rider_mode);

    // Hide the settings FAB
    fabSettings.setVisibility(View.GONE);

    /*
    Change between user and driver mode. Will probably be replaced with an option in settings.
    For now the visibility of this is set to gone because we should not have too many FABs.
    Having too many FABs may cause confusion and rendering issues on small screens.
    */
    keywordEditText = (EditText) findViewById(R.id.main_keyword_edit_text);
    FloatingActionButton fabMode = (FloatingActionButton) findViewById(R.id.main_fab_mode);
    fabMode.setVisibility(View.GONE);
    if (userManager.getUserMode().equals(UserMode.RIDER)) {
        fabRider.setVisibility(View.GONE);
        keywordEditText.setVisibility(View.GONE);
    } else {
        fabDriver.setVisibility(View.GONE);
        keywordEditText.setVisibility(View.VISIBLE);
    }

    keywordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                Intent intent = new Intent(MainActivity.this, SearchRequestActivity.class);
                intent.putExtra(SearchRequestActivity.EXTRA_PLACE, "");
                intent.putExtra(SearchRequestActivity.EXTRA_KEYWORD, keywordEditText.getText().toString());
                keywordEditText.setText("");
                keywordEditText.clearFocus();
                startActivity(intent);
            }
            return true;
        }
    });

    fabMode.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked mode fab");
            /*
            Will be able to implement code below once elasticSearch is up and running
            UserManager userManager = null; // Once elasticSearch is working will replace with finding a User
            if (userManager.getUserMode() == UserMode.DRIVER) {
            userManager.setUserMode(UserMode.RIDER);
            }
            else if (userManager.getUserMode() == UserMode.RIDER) {
            userManager.setUserMode(UserMode.DRIVER);
            //Will have to implement a method "FindNearbyRequests" to get requests whose source
            // is nearby and display it on the map
            //Intent intent = new Intent((MainActivity.this, FindNearbyRequests.class);)
            //startActivity(intent);
            }*/
        }
    });

    fabDriver.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (userManager.getUser().getVehicleDescription().isEmpty()) {
                /*
                * From: http://stackoverflow.com/a/29048271
                * Author: Syeda Zunairah
                * Accessed: November 29, 2016
                * Creates a dialog box with an edit text to get the vehicle description.
                */
                AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
                final EditText edittext = new EditText(v.getContext());
                edittext.setText("Vechicle Make");
                edittext.clearComposingText();
                alert.setTitle("Become a Driver!");
                alert.setMessage(
                        "Drivers are require to enter vehicle information!\n\nPlease enter your vehicle's make");

                alert.setView(edittext);

                alert.setPositiveButton("Save Description", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String vehicleDescription = edittext.getText().toString();
                        if (!vehicleDescription.isEmpty()) {
                            userManager.getUser().setVehicleDescription(vehicleDescription);
                            userManager.notifyObservers();
                            userManager.setUserMode(UserMode.DRIVER);
                            ElasticSearch elasticSearch = new ElasticSearch(
                                    userManager.getConnectivityManager());
                            elasticSearch.updateUser(userManager.getUser());
                            keywordEditText.setVisibility(View.VISIBLE);
                            fabDriver.setVisibility(View.GONE);
                            fabRider.setVisibility(View.VISIBLE);
                            fabMenu.close(true);
                        }
                        dialog.dismiss();
                    }
                });

                alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                    }
                });

                AlertDialog newAlert = alert.create();
                newAlert.show();
            }
            if (!userManager.getUser().getVehicleDescription().isEmpty()) {
                userManager.setUserMode(UserMode.DRIVER);
                keywordEditText.setVisibility(View.VISIBLE);
                fabDriver.setVisibility(View.GONE);
                fabRider.setVisibility(View.VISIBLE);
                fabMenu.close(true);
            }
        }
    });

    fabRider.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            userManager.setUserMode(UserMode.RIDER);
            keywordEditText.setVisibility(View.GONE);
            fabRider.setVisibility(View.GONE);
            fabDriver.setVisibility(View.VISIBLE);
            fabMenu.close(true);
        }
    });

    fabLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });

    fabSettings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked settings fab");
            Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });

    fabProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked profile fab");
            Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });
    fabHistory.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked history fab");
            Intent intent = new Intent(MainActivity.this, RequestHistoryActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });

    fabRequests.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked requests fab");
            Intent intent = new Intent(MainActivity.this, RequestsListActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });
    setNotificationAlarm(context);
}

From source file:ca.ualberta.cs.drivr.MainActivity.java

License:Apache License

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;/*from   ww  w .  ja v a 2 s.c o m*/
    final MapController mapController = new MapController(mMap, context);

    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        mMap.setMyLocationEnabled(true);
    }

    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {

            if (userManager.getUserMode() == UserMode.RIDER) {
                mapController.addPendingRequest(latLng, MainActivity.this);
            } else {
                ConcretePlace place = mapController.markerGeocodePlace(latLng);
                Gson gson = new GsonBuilder().registerTypeAdapter(Uri.class, new UriSerializer()).create();

                Intent intent = new Intent(MainActivity.this, SearchRequestActivity.class);
                String concretePlaceJson = gson.toJson(place);
                intent.putExtra(SearchRequestActivity.EXTRA_PLACE, concretePlaceJson);
                intent.putExtra(SearchRequestActivity.EXTRA_KEYWORD, "");
                Log.i(TAG, "Place: " + place.getName() + ", :" + place.getLatLng());
                startActivity(intent);

            }
        }
    });

    mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
        @Override
        public void onMarkerDragStart(Marker marker) {
        }

        @Override
        public void onMarkerDrag(Marker marker) {
            mMap.animateCamera(CameraUpdateFactory.newLatLng(marker.getPosition()));
        }

        @Override
        public void onMarkerDragEnd(Marker marker) {
        }
    });
}