Example usage for com.google.gson.reflect TypeToken TypeToken

List of usage examples for com.google.gson.reflect TypeToken TypeToken

Introduction

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

Prototype

@SuppressWarnings("unchecked")
protected TypeToken() 

Source Link

Document

Constructs a new type literal.

Usage

From source file:ca.cs.ualberta.localpost.controller.ElasticSearchOperations.java

License:Open Source License

/**
 * //  w w w.  j  a v a 2  s  .  c o  m
 * @param uuid Pulls Model from ES using UUID
 * @return   Arraylist of Root(Top Leve) Comment models
 * @throws ClientProtocolException   Internet Exception
 * @throws IOException   Handles IO exceptions
 */
public ArrayList<CommentModel> getAllRootComments(String uuid) throws ClientProtocolException, IOException {
    ArrayList<CommentModel> returnArray = new ArrayList<CommentModel>();
    HttpGet search = new HttpGet(urlRoot + "_search");
    HttpResponse response = httpclient.execute(search);

    String status = response.getStatusLine().toString();
    //System.out.println(status);

    String json = getEntityContent(response);

    Type searchType = new TypeToken<ElasticSearchSearchResponse<RootCommentModel>>() {
    }.getType();
    ElasticSearchSearchResponse<RootCommentModel> esResponse = gson.fromJson(json, searchType);

    for (ElasticSearchResponse<RootCommentModel> r : esResponse.getHits()) {
        RootCommentModel model = r.getSource();
        if (uuid == null) {
            //deleteComment(model.getPostId(),2);
            returnArray.add(model);
        }
        if (model.getPostId().toString().equals(uuid)) {
            returnArray.clear();
            returnArray.add(model);
            return returnArray;
        }
    }
    return returnArray;
}

From source file:ca.cs.ualberta.localpost.view.MapsView.java

License:Open Source License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.maps_view);//w  w w .java2s.  co m

    // If map is not already setUp, then set it up
    setUpMapIfNeeded();

    // Load current user
    try {
        user = Serialize.loaduser(getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Receive intent
    Intent extrasData = getIntent();
    INTENT_PURPOSE = extrasData.getStringExtra(MAP_VIEW_TYPE);

    // The following checks conditions to determine how to display the map
    // depending on where the intent was sent from and with what purpose
    //
    // Thread View
    if (INTENT_PURPOSE.equals(THREAD_VIEW)) {
        // Retrieve the comment model passed through intent
        INTENT_OBJECT = extrasData.getStringExtra(THREAD_COMMENT_MODEL);

        // Convert GSON string to ArrayList Type
        arrayComments = gson.fromJson(INTENT_OBJECT, new TypeToken<ArrayList<String>>() {
        }.getType());

        markerThreadView(arrayComments);
    }
    // Evaluates true when submitting a comment
    else if (INTENT_PURPOSE.equals(SUBMIT_VIEW) || INTENT_PURPOSE.equals(EDIT_USER_LOCATION_VIEW)) {
        // Set address to the users default location
        address = user.getAddress();

        // Set coordinates to the users default location
        latLng = new LatLng(address.getLatitude(), address.getLongitude());

        commentMarker();
    }
    // Evaluates true when editing a comment
    else if (INTENT_PURPOSE.equals(EDIT_COMMENT_VIEW)) {
        // Retrieve the comment model passed through intent
        INTENT_OBJECT = extrasData.getStringExtra(EDIT_COMMENT_MODEL);

        // Convert the gson string to a Root Comment Model
        commentModel = gson.fromJson(INTENT_OBJECT, RootCommentModel.class);

        // Open the map at the location where the comment was made
        latLng = new LatLng(commentModel.getAddress().getLatitude(), commentModel.getAddress().getLongitude());
        address = commentModel.getAddress();
        commentMarker();
    }

    // Getting reference to btn_find of the layout maps_view
    Button btn_find = (Button) findViewById(R.id.btn_find);

    // Defining button click event listener for the find button
    OnClickListener findClickListener = new FindButton();

    // Setting button click event listener for the find button
    btn_find.setOnClickListener(findClickListener);
}

From source file:ca.cs.ualberta.localpost.view.ThreadView.java

License:Open Source License

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    ConnectivityCheck conn = new ConnectivityCheck(this);
    ElasticSearchOperations es = new ElasticSearchOperations();
    switch (item.getItemId()) {

    case R.id.readLater:
        Toast.makeText(getApplicationContext(), "Added to Read Later", Toast.LENGTH_SHORT).show();
        if (conn.isConnectingToInternet()) {
            es.execute(1, topLevel.getPostId(), topLevel, null);
            Serialize.SaveComment(topLevel, this, "readlater");
            Serialize.update(topLevel, this, "readlater.json");
            return true;
        } else {//from w w  w .j a  va  2 s  . c o m
            Toast.makeText(this, "You require connectivity to cache a thread for later read",
                    Toast.LENGTH_SHORT).show();
            return true;
        }
    case R.id.plotThread:
        if (conn.isConnectingToInternet()) {
            Intent intentMapThread = new Intent(getApplicationContext(), MapsView.class);
            intentMapThread.putExtra(MAP_VIEW_TYPE, THREAD_VIEW);
            String passArrayComment = gson.toJson(mapThreadView, new TypeToken<ArrayList<String>>() {
            }.getType());
            intentMapThread.putExtra(THREAD_COMMENT_MODEL, passArrayComment);
            startActivity(intentMapThread);
            return true;
        } else {
            Toast.makeText(getApplicationContext(), "Yo you require connectivity to view a map thread",
                    Toast.LENGTH_SHORT).show();
            return true;
        }
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:ca.drusk.investment_tracker.data_retrieval.HistoricalDataServlet.java

License:Open Source License

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)/* w  w  w.j  a v  a2 s .  co  m*/
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String queriedSymbol = request.getParameter("symbol");
    assert queriedSymbol != null : "query symbol was null!";

    response.setContentType("application/json");

    try {
        List<YahooDataBean> beans = dataFetcher.fetchDataForSymbol(queriedSymbol);
        Type type = new TypeToken<List<YahooDataBean>>() {
        }.getType();
        PrintWriter out = response.getWriter();
        out.write(gson.toJson(beans, type));

    } catch (ParseException e) {
        e.printStackTrace();
        // TODO return an error code
    }
}

From source file:ca.etsmtl.applets.etsmobile.ETSMobileApp.java

License:Apache License

public ArrayList<Session> getSessionsFromPrefs() {
    ArrayList<Session> list;

    final Type type = new TypeToken<List<Session>>() {
    }.getType();/*  www  . ja  v  a2  s  .  c  o m*/

    final String string = prefs.getString(ETSMOBILE_CALENDRIER_SESSIONS, "[]");

    Log.d("ETSMobileApp::CalendrierJSONtoPOJO", string);

    list = new Gson().fromJson(string, type);
    if (list == null) {
        list = new ArrayList<Session>();
    }
    Log.d("ETSMobileApp::CalendrierJSONtoPOJO", "" + list.size());
    return list;
}

From source file:ca.nabdullaualberta.buzzergame.FileManager.java

License:Apache License

protected ArrayList<Long> loadFromFile(SinglePlayer player) {

    ArrayList<Long> reactionTimes = new ArrayList<Long>();
    try {// ww  w . j  a  v  a 2s  .  c o m
        FileInputStream fis = context.openFileInput(FILENAME);
        BufferedReader in = new BufferedReader(new InputStreamReader(fis));
        Gson gson = new Gson();
        Type listType = new TypeToken<ArrayList<Long>>() {
        }.getType();
        reactionTimes = gson.fromJson(in, listType);
        fis.close();
    } catch (FileNotFoundException e) {
        reactionTimes = new ArrayList<Long>();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return reactionTimes;
}

From source file:ca.nabdullaualberta.buzzergame.FileManager.java

License:Apache License

protected ArrayList<MultiPlayer> loadFromFile(MultiPlayer player) {
    ArrayList<MultiPlayer> players = new ArrayList<>();
    try {//from w w w  . j av a 2 s.co m
        FileInputStream fis = context.openFileInput(FILENAME);
        BufferedReader in = new BufferedReader(new InputStreamReader(fis));
        Gson gson = new Gson();
        Type listType = new TypeToken<ArrayList<MultiPlayer>>() {
        }.getType();
        players = gson.fromJson(in, listType);
        fis.close();
    } catch (FileNotFoundException e) {
        players = new ArrayList<MultiPlayer>();
        if (player.getNumPlayers() == 2) {
            players.add(0, new MultiPlayer("Player 2"));
            players.add(0, new MultiPlayer("Player 1"));
        } else if (player.getNumPlayers() == 3) {
            players.add(0, new MultiPlayer("Player 3"));
            players.add(0, new MultiPlayer("Player 2"));
            players.add(0, new MultiPlayer("Player 1"));
        } else if (player.getNumPlayers() == 4) {
            players.add(0, new MultiPlayer("Player 4"));
            players.add(0, new MultiPlayer("Player 3"));
            players.add(0, new MultiPlayer("Player 2"));
            players.add(0, new MultiPlayer("Player 1"));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return players;
}

From source file:ca.rossanderson.rhanders_reflex.StatsModel.java

License:Open Source License

private ArrayList<Long> readReactionTimesFromFile(Context cxt) {
    ArrayList<Long> times = null;
    Gson gson = new Gson();
    try {/*from www.  ja v  a  2 s  .co m*/
        FileInputStream fis = new FileInputStream(getReactionTimesPath(cxt));
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

        Type type = new TypeToken<ArrayList<Long>>() {
        }.getType();
        times = gson.fromJson(reader, type);
        fis.close();
    } catch (FileNotFoundException e) {
        Log.e("Stats", String.format("File not found at '{}'", getReactionTimesPath(cxt)));
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (times == null) {
        times = new ArrayList<Long>();
    }
    return times;
}

From source file:ca.rossanderson.rhanders_reflex.StatsModel.java

License:Open Source License

private HashMap<Integer, HashMap<Integer, Integer>> readGameShowBuzzesFromFile(Context cxt) {
    HashMap<Integer, HashMap<Integer, Integer>> buzzes = null;
    Gson gson = new Gson();
    try {/*from   w  ww  . jav  a 2  s  .co m*/
        FileInputStream fis = new FileInputStream(getGameShowPath(cxt));
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

        Type type = new TypeToken<HashMap<Integer, HashMap<Integer, Integer>>>() {
        }.getType();
        buzzes = gson.fromJson(reader, type);
        fis.close();
    } catch (FileNotFoundException e) {
        Log.e("Stats", String.format("File not found at '{}'", getGameShowPath(cxt)));
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (buzzes == null) {
        buzzes = new HashMap<Integer, HashMap<Integer, Integer>>();
    }
    // Fill with zeros: <[2-4], <[1-4], 0>>
    for (int players = 2; players <= 4; players++) {
        for (int playerNum = 1; playerNum <= players; playerNum++) {
            if (buzzes.get(players) == null) {
                buzzes.put(players, new HashMap<Integer, Integer>());
            }
            if (buzzes.get(players).get(playerNum) == null) {
                buzzes.get(players).put(playerNum, 0);
            }
        }
    }
    return buzzes;
}

From source file:ca.ualberta.app.controller.CacheController.java

License:Apache License

/**
 * Load the question ID's from the file with given name.
 * /*  w ww . ja v a  2 s  .c  o  m*/
 * @param context
 *            The context.
 * @param FILENAME
 *            The name of the local file.
 * 
 * @return the ID of the question(s).
 */
public ArrayList<Long> loadIdFromFile(Context context, String FILENAME) {
    ArrayList<Long> questionId = null;
    try {
        FileInputStream fis = context.openFileInput(FILENAME);
        BufferedReader in = new BufferedReader(new InputStreamReader(fis));
        Gson gson = new Gson();
        // Following line from
        // https://sites.google.com/site/gson/gson-user-guide 2014-09-23
        Type listType = new TypeToken<ArrayList<Long>>() {
        }.getType();
        questionId = gson.fromJson(in, listType);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (questionId == null)
        return questionId = new ArrayList<Long>();
    return questionId;
}