/[projects]/android/MarketStats/src/dk/thoerup/marketstats/ShowStats.java
ViewVC logotype

Diff of /android/MarketStats/src/dk/thoerup/marketstats/ShowStats.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 662 by torben, Fri Apr 23 14:13:39 2010 UTC revision 957 by torben, Mon Jul 5 09:28:40 2010 UTC
# Line 1  Line 1 
1  package dk.thoerup.marketstats;  package dk.thoerup.marketstats;
2    
3  import java.io.IOException;  import java.io.IOException;
 import java.io.PrintWriter;  
4  import java.net.InetSocketAddress;  import java.net.InetSocketAddress;
5  import java.util.ArrayList;  import java.util.ArrayList;
 import java.util.Collections;  
 import java.util.Date;  
 import java.util.Formatter;  
6  import java.util.Locale;  import java.util.Locale;
7    import java.util.concurrent.TimeUnit;
8  import java.util.logging.Logger;  import java.util.logging.Logger;
9    
10  import javax.servlet.ServletException;  import javax.servlet.ServletException;
11    import javax.servlet.annotation.WebServlet;
12  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServlet;
13  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletRequest;
14  import javax.servlet.http.HttpServletResponse;  import javax.servlet.http.HttpServletResponse;
# Line 18  import javax.servlet.http.HttpServletRes Line 16  import javax.servlet.http.HttpServletRes
16  import net.spy.memcached.MemcachedClient;  import net.spy.memcached.MemcachedClient;
17    
18  import com.gc.android.market.api.MarketSession;  import com.gc.android.market.api.MarketSession;
 import com.gc.android.market.api.MarketSession.Callback;  
 import com.gc.android.market.api.model.Market.App;  
19  import com.gc.android.market.api.model.Market.AppsRequest;  import com.gc.android.market.api.model.Market.AppsRequest;
 import com.gc.android.market.api.model.Market.AppsResponse;  
20  import com.gc.android.market.api.model.Market.CommentsRequest;  import com.gc.android.market.api.model.Market.CommentsRequest;
 import com.gc.android.market.api.model.Market.ResponseContext;  
21    
22    
23    @WebServlet(urlPatterns={"/ShowStats"})
24  public class ShowStats extends HttpServlet {  public class ShowStats extends HttpServlet {
25          private static final long serialVersionUID = 1L;          private static final long serialVersionUID = 1L;
26    
27          final int TIMEOUT = 30*60;          static final int MAXCOMMENTS = 30;
28            static final int APP_TIMEOUT = 30*60;
29            static final int COMMENT_TIMEOUT = APP_TIMEOUT * 4;
30            
31          static final Logger log = Logger.getLogger(ShowStats.class.getName());          static final Logger log = Logger.getLogger(ShowStats.class.getName());
32    
33          String login;          String login;
34          String password;          String password;
35            
36            MemcachedClient memcache = null;
37    
38    
39          @Override          @Override
# Line 42  public class ShowStats extends HttpServl Line 42  public class ShowStats extends HttpServl
42    
43                  login = getServletContext().getInitParameter("login");                  login = getServletContext().getInitParameter("login");
44                  password = getServletContext().getInitParameter("password");                  password = getServletContext().getInitParameter("password");
45                    
46                    try {
47                            memcache = new MemcachedClient(new InetSocketAddress("localhost", 11211));
48                    } catch (IOException e) {
49                            throw new ServletException(e);
50                    }
51          }          }
52    
53          protected String doLookup(String appId) throws IOException {          @Override
54                  MemcachedClient c = new MemcachedClient(new InetSocketAddress("localhost", 11211));          public void destroy() {
55                    super.destroy();
56                    
57                    memcache.shutdown(3, TimeUnit.SECONDS);
58                    memcache = null;
59            }
60    
61            protected AppBean lookupApp(String query) throws IOException {
62                    
63    
64                  String key = "marketstats:" + appId;                  String key = "marketstats:" + query.replace(' ', '_');
65                  String response = (String) c.get(key);                  //String response = (String) memcache.get(key);
66                    AppBean response = (AppBean) memcache.get(key);
67    
68                  if (response == null) {                  if (response == null) {
69                          response = doLookupWorker(appId);                          response = lookupAppWorker(query);
70                          c.set(key, TIMEOUT, response);                          if (response != null) {
71                          response += "<!-- new lookup -->";                                  memcache.set(key, APP_TIMEOUT, response);
72                  } else {                          }
73                          response += "<!-- from memcached -->";                  }
                 }  
74                  return response;                  return response;
75          }          }
76    
77            protected AppBean lookupAppWorker(String query) {
         protected String doLookupWorker(String appId) {  
                 final StringBuilder sb = new StringBuilder();  
   
78    
79                  MarketSession session = new MarketSession();                  MarketSession session = new MarketSession();
80                  session.login(login,password);                  session.login(login,password);
81    
82    
83                  AppsRequest appsRequest = AppsRequest.newBuilder()                  AppsRequest appsRequest = AppsRequest.newBuilder()
84                  .setAppId(appId)                  .setQuery(query)
85                  .setStartIndex(0).setEntriesCount(10)                  .setStartIndex(0)
86                    .setEntriesCount(1)
87                  .setWithExtendedInfo(true)                  .setWithExtendedInfo(true)
88                  .build();                  .build();
89                    
90                    AppsCallback appsCb = new AppsCallback();
91                    session.append(appsRequest, appsCb);
92                    session.flush();
93                    
94                    return appsCb.getResult();
95            }      
96            
97            CommentsRequest buildCommentRequest(String appId, int start, int count) {
98                  CommentsRequest commentsRequest = CommentsRequest.newBuilder()                  CommentsRequest commentsRequest = CommentsRequest.newBuilder()
99                  .setAppId(appId)                  .setAppId(appId)
100                  .setStartIndex(0)                  .setStartIndex(start)
101                  .setEntriesCount(10)                  .setEntriesCount(count)
102                  .build();                  .build();
103                    
104                    return commentsRequest;
105            }
106            
107                  Callback<AppsResponse> appsCb = new Callback<AppsResponse>() {          private ArrayList<CommentBean> loadComments(String appId) {
108                          @Override                  
                         public void onResult(ResponseContext context, AppsResponse response) {  
                                 //System.out.println("Response : " + response);  
                                 //sb.append("Response: " + response + "\n");  
   
                                 Formatter form = new Formatter(sb);  
                                 App app = response.getApp(0);  
                                 sb.append( "<h2>" + app.getTitle() + "</h2>");  
                                 sb.append("Ver: " + app.getVersion() + " (" + app.getVersionCode() + ")\n"  );  
                                 sb.append("Ratingcount: " + app.getRatingsCount() + "\n");  
   
                                 sb.append("Rating: "  );  
                                 double rating = Double.parseDouble( app.getRating() );  
                                 form.format("%.4f", rating);  
                                 sb.append("\n");  
   
                                 sb.append("Downloads: " + app.getExtendedInfo().getDownloadsCountText() + " (" + app.getExtendedInfo().getDownloadsCount() + ")\n" );  
   
                                 sb.append("\n");  
   
                         }  
                 };  
   
109                  ArrayList<CommentBean> commentBeans = new ArrayList<CommentBean>();                  ArrayList<CommentBean> commentBeans = new ArrayList<CommentBean>();
110                    MarketSession session = new MarketSession();
111                    session.login(login,password);
112                    
113                  CommentCallback commentsCb = new CommentCallback();                  CommentCallback commentsCb = new CommentCallback();
114                  commentsCb.setList( commentBeans );                  commentsCb.setList( commentBeans );
115    
116                  commentsCb.setLocale("en");                  session.setLocale( Locale.ROOT );
117                  session.setLocale( Locale.ENGLISH );                  
118                    
119                  session.append(appsRequest, appsCb);                  
120                  session.append(commentsRequest, commentsCb);                  int start = 0;
121                  session.flush();                  do {
122                            int count = 10;
123                  commentsCb.setLocale( "da" );                          if (start > 0)                          
124                  session.setLocale( new Locale("da") );                                  count = Math.min(10, commentsCb.getEntryCount() );
125                  session.append(commentsRequest, commentsCb);                          
126                  session.flush();                          //log.warning("count=" + count + " start=" + start + " entryCount=" + commentsCb.getEntryCount() );
127                            CommentsRequest commentsRequest = buildCommentRequest(appId,start,count);                      
128                  Collections.sort(commentBeans);                          session.append(commentsRequest, commentsCb);
129                            start +=10;
130                  sb.append("-----------------------------------------------------------------\n");                          
131                  for (CommentBean c : commentBeans) {                          CommentsRequest commentsRequest2 = buildCommentRequest(appId,start,count);                      
132                          sb.append("User: " + c.author + " ("  + c.locale + ")\n");                          session.append(commentsRequest2, commentsCb);
133                          sb.append("Rating: " + c.rating + "\n");                          session.flush();
134                          sb.append("Time: " + new Date(c.time).toString() + "\n");                          
135                          sb.append( c.text + "\n");                          start +=10;
136                          sb.append("\n");                          
137                            if (start >= MAXCOMMENTS)
138                  }                                  break; //emergency brake
139                            
140                    } while ( start < commentsCb.getEntryCount() );
141                    
142                    return commentBeans;
143            }
144    
145                  return sb.toString();          
146            
147            @SuppressWarnings("unchecked")
148            public ArrayList<CommentBean> getComments(AppBean app) {                
149                    String key = "marketstats:comments:" + app.getId();
150                    ArrayList<CommentBean>  comments =  (ArrayList<CommentBean>) memcache.get(key);
151    
152                    if (comments == null) {
153                            comments = loadComments(app.getId());
154                            memcache.set(key, COMMENT_TIMEOUT, comments);
155                    }
156                    return comments;
157          }          }
158    
159          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
160                  String appId = request.getParameter("appId");                  String query = request.getParameter("query");
161                    
162                  response.setContentType("text/html");                  AppBean app = lookupApp(query);
163                  PrintWriter out = response.getWriter();                  if (app != null) {
164                  out.print( "<html><body><pre>" + doLookup(appId) + "</pre></body></html>" );                          request.setAttribute("app", app);
165                    
166                            ArrayList<CommentBean> comments = getComments(app);
167                            request.setAttribute("comments", comments);
168                    
169                            getServletContext().getRequestDispatcher("/statsview.jsp").forward(request, response);
170                    } else {
171                            response.getWriter().print("No app found with query=" + query);
172                    }
173          }          }
174    
175  }  }

Legend:
Removed from v.662  
changed lines
  Added in v.957

  ViewVC Help
Powered by ViewVC 1.1.20