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.ualberta.cmput301w14t08.geochan.managers.FavouritesIOManager.java

License:Apache License

/**
 * Deserializes the favourited Comments.
 * @return An ArrayList of the favourited comments as ThreadComments.
 *//*  www .  java2s. c  o m*/
public ArrayList<ThreadComment> deSerializeFavComments() {
    ArrayList<ThreadComment> list = new ArrayList<ThreadComment>();
    try {
        FileInputStream f = context.openFileInput(FILENAME1);
        BufferedReader r = new BufferedReader(new InputStreamReader(f));
        String json = "";
        String temp = "";
        temp = r.readLine();
        while (temp != null) {
            json = json + temp;
            temp = r.readLine();
        }
        r.close();
        f.close();
        Type type = new TypeToken<ArrayList<ThreadComment>>() {
        }.getType();
        list = gson.fromJson(json, type);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return list;
}

From source file:ca.ualberta.cmput301w14t08.geochan.managers.FavouritesIOManager.java

License:Apache License

/**
 * Deserialize ArrayList of favourited ThreadComments from JSON
 * /*from   w w w.j  av  a  2 s  . co m*/
 * @return ArrayList of favourited ThreadComments.
 */
public ArrayList<ThreadComment> deSerializeThreads() {
    ArrayList<ThreadComment> list = new ArrayList<ThreadComment>();
    try {
        FileInputStream f = context.openFileInput(FILENAME2);
        BufferedReader r = new BufferedReader(new InputStreamReader(f));
        String json = "";
        String temp = "";
        temp = r.readLine();
        while (temp != null) {
            json = json + temp;
            temp = r.readLine();
        }
        r.close();
        f.close();
        Type type = new TypeToken<ArrayList<ThreadComment>>() {
        }.getType();
        list = gson.fromJson(json, type);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return list;
}

From source file:ca.ualberta.cmput301w14t08.geochan.managers.GeoLocationLogIOManager.java

License:Apache License

/**
 * Deserializes and returns the GeoLocations stored in our app.
 * @return An ArrayList of the stored GeoLocations.
 *///from w w w  .  ja  va2  s  .  com
public ArrayList<GeoLocation> deserializeLog() {
    ArrayList<GeoLocation> list = new ArrayList<GeoLocation>();
    try {
        FileInputStream f = context.openFileInput(FILENAME);
        BufferedReader r = new BufferedReader(new InputStreamReader(f));
        String json = "";
        String temp = "";
        temp = r.readLine();
        while (temp != null) {
            json = json + temp;
            temp = r.readLine();
        }
        r.close();
        f.close();
        Type type = new TypeToken<ArrayList<GeoLocation>>() {
        }.getType();
        list = gson.fromJson(json, type);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return list;
}

From source file:ca.ualberta.cmput301w14t08.geochan.runnables.GetCommentsRunnable.java

License:Apache License

/**
 * Forms a query and sends a multi-Get request to ES, then processes the
 * retrieved data into a CommentList object and saves it into an array.
 * Then, puts the comment object in the right place in the corresponding
 * commentList to be later reconstructed into a correct hierarchy of
 * comments./*ww w. ja  v  a2s.  com*/
 */
@Override
public void run() {
    task.setGetCommentsThread(Thread.currentThread());
    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
    HttpURLConnection connection = null;
    try {
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        task.handleGetCommentsState(STATE_GET_COMMENTS_RUNNING);
        CommentList commentList = task.getCommentListCache();
        ArrayList<String> idList = new ArrayList<String>();
        commentList.getIdsFromList(commentList, idList);
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        String json = ElasticSearchQueries.commentsScript(idList);

        String server = ElasticSearchClient.URL + "/" + ElasticSearchClient.URL_INDEX + "/"
                + ElasticSearchClient.TYPE_COMMENT + "/_mget";
        URL url = new URL(server);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");

        DataOutputStream writeStream = new DataOutputStream(connection.getOutputStream());
        writeStream.writeBytes(json);
        writeStream.flush();
        writeStream.close();

        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        StringBuffer response = new StringBuffer();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        String responseJson = response.toString();
        Gson gson = GsonHelper.getOnlineGson();
        Type elasticSearchDocsType = new TypeToken<ElasticSearchDocs<Comment>>() {
        }.getType();

        ElasticSearchDocs<Comment> esResponse = gson.fromJson(responseJson, elasticSearchDocsType);
        ArrayList<Comment> list = new ArrayList<Comment>();

        for (ElasticSearchResponse<Comment> r : esResponse.getDocs()) {
            Comment object = r.getSource();
            list.add(object);
        }

        for (Comment comment : list) {
            commentList.findCommentListById(commentList, comment.getId()).setComment(comment);
        }

        ThreadComment threadComment = ThreadList.getThreads().get(task.getThreadIndex());
        Comment bodyComment = threadComment.getBodyComment();
        threadComment.setBodyComment(commentList.reconsructFromCommentList(commentList, bodyComment));
        CacheManager.getInstance().serializeThreadCommentById(threadComment);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (connection == null || (connection.getResponseCode() != 200)) {
                task.handleGetCommentsState(STATE_GET_COMMENTS_FAILED);
            } else {
                task.handleGetCommentsState(STATE_GET_COMMENTS_COMPLETE);
            }
        } catch (IOException e) {
            task.handleGetCommentsState(STATE_GET_COMMENTS_FAILED);
        }
        connection.disconnect();
        Thread.interrupted();
    }

}

From source file:ca.ualberta.cmput301w14t08.geochan.runnables.GetImageRunnable.java

License:Apache License

/**
 * Forms a query and sends a get request to ES,
 * then processes retrieved data as a bitmap and
 * sends it to the task's cache.//from  w  w w . jav a 2  s  .  c om
 */
@Override
public void run() {
    task.setGetImageThread(Thread.currentThread());
    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
    task.handleGetImageState(STATE_GET_IMAGE_RUNNING);
    JestResult result = null;
    try {
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        Get get = new Get.Builder(ElasticSearchClient.URL_INDEX, task.getId()).type(type).build();
        result = ElasticSearchClient.getInstance().getClient().execute(get);

        Type type = new TypeToken<ElasticSearchResponse<Bitmap>>() {
        }.getType();
        Gson gson = GsonHelper.getOnlineGson();
        ElasticSearchResponse<Bitmap> esResponse = gson.fromJson(result.getJsonString(), type);

        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        task.setImageCache(esResponse.getSource());
        task.handleGetImageState(STATE_GET_IMAGE_COMPLETE);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (result == null || !result.isSucceeded()) {
            task.handleGetImageState(STATE_GET_IMAGE_FAILED);
        }
        // task.setGetImageThread(null);
        Thread.interrupted();
    }

}

From source file:ca.ualberta.cmput301w14t08.geochan.runnables.GetThreadCommentsRunnable.java

License:Apache License

/**
 * Forms a query and sends a Get request to ES, then processes
 * retrieved data as an array of ThreadComment objects.
 *//*from  w ww . j av a 2  s  . c  o m*/
@Override
public void run() {
    task.setGetThreadCommentsThread(Thread.currentThread());
    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
    task.handleGetThreadCommentsState(STATE_GET_THREADS_RUNNING);
    JestResult result = null;
    try {
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        String query = ElasticSearchQueries.SEARCH_MATCH_ALL;
        Search search = new Search.Builder(query).addIndex(ElasticSearchClient.URL_INDEX).addType(type).build();
        result = ElasticSearchClient.getInstance().getClient().execute(search);
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        Type elasticSearchSearchResponseType = new TypeToken<ElasticSearchSearchResponse<ThreadComment>>() {
        }.getType();
        Gson gson = GsonHelper.getOnlineGson();
        ElasticSearchSearchResponse<ThreadComment> esResponse = gson.fromJson(result.getJsonString(),
                elasticSearchSearchResponseType);
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        ArrayList<ThreadComment> list = new ArrayList<ThreadComment>();
        for (ElasticSearchResponse<ThreadComment> r : esResponse.getHits()) {
            ThreadComment object = r.getSource();
            list.add(object);
        }
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        ThreadList.setThreads(list);
        task.handleGetThreadCommentsState(STATE_GET_THREADS_COMPLETE);
    } catch (Exception e) {
        //
    } finally {
        if (result == null || !result.isSucceeded()) {
            task.handleGetThreadCommentsState(STATE_GET_THREADS_FAILED);
        }
        // task.setGetCommentListThread(null);
        Thread.interrupted();
    }
}

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

License:Apache License

/**
 * This method will load the ClamList and return it for further
 * use or display. It also checks exceptions to prevent crush.
 * /*from  w  w  w  .  j  a  v  a 2 s.  co  m*/
 * @param name  a String that is the full name of the user.
 * @exception FileNotFoundException
 * @exception IOException
 * @throws RuntimeException
 * @see com.google.gson.Gson
  * @see java.io.FileInputStream
 * @see java.io.FileNotFoundException
 * @see java.io.FileOutputStream
 * @see java.io.IOException
 * @see java.io.InputStreamReader
 * @see java.io.OutputStreamWriter
 * @return the user that is currenly using the application
 */
public User load(String name) {

    User user = null;
    try {
        FileInputStream fis = context.openFileInput(USER_FILE + name);
        Type dataType = new TypeToken<User>() {
        }.getType();
        InputStreamReader isr = new InputStreamReader(fis);
        user = gson.fromJson(isr, dataType);
        fis.close();
    } catch (FileNotFoundException e) {

    } catch (IOException e) {
        throw new RuntimeException("IOException");
    }

    if (user == null) {
        user = new User(name);
        UserList userList = AppSingleton.getInstance().getUserList();
        if (!userList.getUserList().contains(name)) {
            userList.getUserList().add(name);
            saveUserList(user);
        }
    }
    return user;
}

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

License:Apache License

/**
 * Load the list of user from online to local. Throw error exceptions if necessary.
 * //from  w w w.  jav a  2  s .c o m
 * @return the list of users who are using the application
 * @see FileNotFoundException
 * @see IOException
 */
public UserList loadUserList() {
    UserList userList = null;
    try {
        FileInputStream fis = context.openFileInput("usrList");
        Type dataType = new TypeToken<UserList>() {
        }.getType();
        InputStreamReader isr = new InputStreamReader(fis);
        userList = gson.fromJson(isr, dataType);
        fis.close();
    } catch (FileNotFoundException e) {

    } catch (IOException e) {
        throw new RuntimeException("IOException");
    }

    return userList;

}

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

License:Apache License

/**
 * Consumes the Get operation of the service
 * @return sr.getSource/*from   ww w. ja  va 2 s .  co  m*/
 */
public User getUser(String string) {
    Hit<User> sr = null;
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(USER + string);

    HttpResponse response = null;

    try {
        response = httpClient.execute(httpGet);
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e);

    } catch (IOException e) {
        return null;
    }

    Type HitType = new TypeToken<Hit<User>>() {
    }.getType();

    try {
        sr = gson.fromJson(new InputStreamReader(response.getEntity().getContent()), HitType);
    } catch (JsonIOException e) {
        throw new RuntimeException(e);
    } catch (JsonSyntaxException e) {
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return sr.getSource();
}

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

License:Apache License

public UserList getUserList() {
    // TODO Auto-generated method stub
    Hit<UserList> sr = null;/*www  .ja va2  s.  com*/
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(USER_LIST);

    HttpResponse response = null;
    try {
        response = httpClient.execute(httpGet);
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e.getMessage());
    } catch (IOException e) {
        return null;
    }

    Type HitType = new TypeToken<Hit<UserList>>() {
    }.getType();

    try {
        sr = gson.fromJson(new InputStreamReader(response.getEntity().getContent()), HitType);
    } catch (JsonIOException e) {
        throw new RuntimeException(e);
    } catch (JsonSyntaxException e) {
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return sr.getSource();
}