Android Open Source - android.app.niuz.io News Service






From Project

Back to project page android.app.niuz.io.

License

The source code is released under:

GNU General Public License

If you think the Android project android.app.niuz.io listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package io.niuz.services;
/* w w w.j  av a 2s.co m*/
import io.niuz.model.News;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

public class NewsService extends BaseService {  
  private static List<News> newsList = new ArrayList<News>(20);
  
  private final static String SERVER_LINK_INIT_USER_NEWS_TO_READ = SERVER_URL + "initUserNewsToRead/";
  private final static String SERVER_LINK_GET_NEWS = SERVER_URL + "getNewsToRead/";
  private final static String SERVER_AFTER_USER_READ_NEWS = SERVER_URL + "afterUserReadNews";
  private final static String SERVER_ON_USER_OPEN_NEWS = SERVER_URL + "onUserOpenNews";
  
  public static boolean isNewsTooOld(News object) {
    try {
      TimeZone tz = new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC");
      
      // First new's created time (GMT)
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
      df.setTimeZone(tz);
      Long created = df.parse(object.getCreatedAtStr()).getTime();
      
      // Current time in GMT time
      Calendar c = Calendar.getInstance();
      c.setTimeZone(tz);
      Long now = c.getTime().getTime();
      
      // Difference in minutes
      Long difference = (now - created) / 1000 / 60;
      return difference >= News.REFRESHED_EVERY_MINUTES;

    } catch (ParseException pe) {
      return true;
    }
  }
  
  public static void syncOnUserOpenNews(News newsObject, Context context) throws Exception {
    PhoneService.initPhoneNumber(context.getApplicationContext());
    
    // Initializing object data
    JSONObject objectToSend = new JSONObject();
    objectToSend.put("phoneNumber", PhoneService.getPhoneNumber());
    objectToSend.put("newsId", newsObject.getId());
    
    // Initializing http client
    String url = SERVER_ON_USER_OPEN_NEWS;
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new StringEntity(objectToSend.toString()));
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(httpPost);
    
    // Parsing response, throwing exception if required
    StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() == HttpStatus.SC_OK){
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          response.getEntity().writeTo(out);
          out.close();
          
    } else {
      response.getEntity().getContent().close();
      throw new Exception("Bad http status!");
    }
  }
  
  public static void syncInitAfterUserReadNews(News newsObject, Long timeSpent, Context context) throws Exception {
    PhoneService.initPhoneNumber(context.getApplicationContext());
    
    // Initializing object data
    JSONObject objectToSend = new JSONObject();
    objectToSend.put("phoneNumber", PhoneService.getPhoneNumber());
    objectToSend.put("newsId", newsObject.getId());
    objectToSend.put("timeSpent", timeSpent);
    
    // Initializing http client
    String url = SERVER_AFTER_USER_READ_NEWS;
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new StringEntity(objectToSend.toString()));
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(httpPost);
    
    // Parsing response, throwing exception if required
    StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() == HttpStatus.SC_OK){
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          response.getEntity().writeTo(out);
          out.close();
          
    } else {
      response.getEntity().getContent().close();
      throw new Exception("Bad http status!");
    }
  }
  
  private static void jsonArrayToNewsList(JSONArray news) throws JSONException {
    for (int i=0 ; i<news.length() ; i++) {
      JSONObject newsObject = news.getJSONObject(i);
      newsList.add(new News(
        newsObject.getLong("id"),
        newsObject.getString("title"),
        newsObject.getString("link"),
        newsObject.getString("createdAt"),
        newsObject.getString("updatedAt"),
        newsObject.getLong("NewsCompanyId"),
        newsObject.getLong("SubcategoryId"),
        newsObject.getLong("subcategoryWeight"),
        newsObject.getString("subcategoryName"),
        newsObject.getString("newsCompanyName")
      ));
    }
  }
  
  public static void initNewsList(Context context) throws ClientProtocolException, IOException, JSONException {
    // Clearing the current list
    newsList.clear();
    
    // Retrieving new items
    PhoneService.initPhoneNumber(context.getApplicationContext());
    String url = SERVER_LINK_GET_NEWS + PhoneService.getPhoneNumber();
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(new HttpGet(url));
    
    StatusLine statusLine = response.getStatusLine();
    
    if (statusLine.getStatusCode() == HttpStatus.SC_OK){
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          response.getEntity().writeTo(out);
          out.close();
          
          // Initializing companies
          JSONArray news = new JSONObject(out.toString()).getJSONArray("news");
          jsonArrayToNewsList(news);
          
      } else{
          response.getEntity().getContent().close();
          throw new IOException(statusLine.getReasonPhrase());
      }
  }
  
  public static void initUserNewsToRead() throws JSONException, Exception {
    // Posting request
    String url = SERVER_LINK_INIT_USER_NEWS_TO_READ + PhoneService.getPhoneNumber();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(httpPost);
    
    // Parsing response, throwing exception if required
    StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() == HttpStatus.SC_OK){
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          response.getEntity().writeTo(out);
          out.close();
          
          if (!new JSONObject(out.toString()).getBoolean("success")) {
            throw new Exception("Something went wrong during API execution!");
          }
          
    } else {
      response.getEntity().getContent().close();
      throw new Exception("Bad http status!");
    }
  }

  public static List<News> getNewsList() {
    return newsList;
  }
}




Java Source Code List

io.niuz.CategoriesSelectionActivity.java
io.niuz.CompanyInformationLoadingActivity.java
io.niuz.MainActivity.java
io.niuz.NewsCompaniesSelectionActivity.java
io.niuz.NewsHeadersActivity.java
io.niuz.NewsReaderActivity.java
io.niuz.PreMainActivity.java
io.niuz.model.APIRetrievalStatus.java
io.niuz.model.CategoryInformation.java
io.niuz.model.CompanyInformation.java
io.niuz.model.InitUserStatus.java
io.niuz.model.News.java
io.niuz.services.BaseService.java
io.niuz.services.CategoriesSubcategoriesService.java
io.niuz.services.CompaniesService.java
io.niuz.services.NewsService.java
io.niuz.services.PhoneService.java
io.niuz.services.UserService.java