View Javadoc

1   /** ------------------------------------
2    * SweetDEV RIA library
3    * Copyright [2006 - 2010] [Ideo Technologies]
4    * ------------------------------------
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   * 		http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   *
18   *
19   * For more information, please contact us at:
20   *         Ideo Technologies S.A
21   *        124 rue de Verdun
22   *        92800 Puteaux - France
23   *
24   *      France & Europe Phone : +33 1.46.25.09.60
25   *
26   *
27   *        web : http://www.ideotechnologies.com
28   *        email : SweetDEV-RIA@ideotechnologies.com
29   *
30   *
31   * @version ${pom.version}
32   * @author Ideo Technologies
33   */
34  package com.ideo.sweetdevria.taglib.reader.provider;
35  
36  import java.io.InputStreamReader;
37  import java.io.Serializable;
38  import java.net.HttpURLConnection;
39  import java.net.URL;
40  import java.util.ArrayList;
41  import java.util.HashMap;
42  import java.util.Iterator;
43  import java.util.List;
44  import java.util.Map;
45  
46  import org.apache.commons.logging.Log;
47  import org.apache.commons.logging.LogFactory;
48  
49  import com.ideo.sweetdevria.taglib.reader.model.AbstractDataReaderModel;
50  import com.ideo.sweetdevria.taglib.reader.model.ReaderCategoryModel;
51  import com.ideo.sweetdevria.taglib.reader.model.ReaderItemModel;
52  import com.sun.syndication.feed.synd.SyndEntry;
53  import com.sun.syndication.feed.synd.SyndFeed;
54  import com.sun.syndication.io.SyndFeedInput;
55  
56  public class ReaderDataProvider implements Serializable {
57  
58  	private static final Log LOG = LogFactory.getLog(ReaderDataProvider.class);
59  
60  	private static final long serialVersionUID = 3813519359771011395L;
61  
62  	private List data;
63  
64  	private String rssUrl;
65  
66  	private Map idMap;
67  
68  	private int maxDepth = -1;
69  
70  	public ReaderDataProvider(List data) {
71  		idMap = new HashMap();
72  		this.data = data;
73  		Iterator it = data.iterator();
74  		while (it.hasNext()) {
75  			AbstractDataReaderModel node = (AbstractDataReaderModel) it.next();
76  			registerNode(node);
77  		}
78  	}
79  
80  	public ReaderDataProvider(String readerId, String rssFeed,
81  			Integer articlesFetched) {
82  
83  		idMap = new HashMap();
84  		rssUrl = rssFeed;
85  		SyndFeedInput sfi = null;
86  		List entries = new ArrayList();
87  
88  		try {
89  			sfi = new SyndFeedInput();
90  		} catch (NoClassDefFoundError e) {
91  			LOG.error("Can't create SyndFeedInput : " + e.getMessage(), e);
92  		}
93  
94  		if (sfi != null) {
95  			try {
96  				URL uri = new URL(rssUrl);
97  
98  				HttpURLConnection con = (HttpURLConnection) uri
99  						.openConnection();
100 
101 				/**
102 				 * Les variables http.proxyHost, http.proxyPort,
103 				 * http.proxyUserId, http.proxyUserPwd doivent etre definies
104 				 * dans la JVM (System.setProperty) si vous souahitez utiliser
105 				 * un proxy afin d'acceder a une url web
106 				 */
107 				String userId = System.getProperty("http.proxyUserId");
108 				String userPwd = System.getProperty("http.proxyUserPwd");
109 
110 				if (userId != null && userPwd != null) {
111 					sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
112 					String encodedUserPwd = encoder
113 							.encode((userId + ":" + userPwd).getBytes());
114 					con.setRequestProperty("Proxy-Authorization", "Basic "
115 							+ encodedUserPwd);
116 				}
117 
118 				// DEBUT SWTRIA-998
119 				String contentType = con.getContentType();
120 				String encoding = null;
121 				InputStreamReader inStream = null;
122 
123 				try {
124 					if (contentType != null) {
125 
126 						if (con.getContentType().lastIndexOf('=') > -1) {
127 							encoding = contentType.substring(con
128 									.getContentType().lastIndexOf('=') + 1, con
129 									.getContentType().length());
130 							inStream = new InputStreamReader(con
131 									.getInputStream(), encoding);
132 						} else {
133 							inStream = new InputStreamReader(con
134 									.getInputStream());
135 						}
136 					} else {
137 						inStream = new InputStreamReader(con.getInputStream());
138 					}
139 
140 					SyndFeed feed = sfi.build(inStream);
141 					// FIN SWTRIA-998
142 					entries = feed.getEntries();
143 				} finally {
144 					if (inStream == null) {
145 						inStream.close();
146 					}
147 				}
148 			} catch (Exception e) {
149 				LOG.error(e.getMessage(), e);
150 			}
151 		}
152 
153 		data = new ArrayList();
154 
155 		Iterator it = entries.iterator();
156 		int cpt = 1;
157 		while (it.hasNext() && cpt <= articlesFetched.intValue()) {
158 			SyndEntry entry = (SyndEntry) it.next();
159 
160 			AbstractDataReaderModel node = new ReaderItemModel(readerId + "_"
161 					+ String.valueOf(cpt++), washHtmlString(entry.getTitle()),
162 					washHtmlString(entry.getDescription().getValue()));
163 
164 			data.add(node);
165 			registerNode(node);
166 		}
167 	}
168 
169 	private String washHtmlString(String code) {
170 		String result = code;
171 
172 		result = result.replaceAll("\n", "<br/>");
173 		result = result.replaceAll("\"", "'");
174 
175 		return result;
176 	}
177 
178 	public void registerNode(AbstractDataReaderModel node) {
179 		idMap.put(node.getId(), node);
180 
181 		if (node instanceof ReaderCategoryModel) {
182 			Iterator it = ((ReaderCategoryModel) node).getChildrenIterator();
183 			while (it != null && it.hasNext()) {
184 				AbstractDataReaderModel child = (AbstractDataReaderModel) it
185 						.next();
186 
187 				registerNode(child);
188 			}
189 		}
190 	}
191 
192 	public AbstractDataReaderModel getNodeById(String id) {
193 		return (AbstractDataReaderModel) idMap.get(id);
194 	}
195 
196 	public List getData() {
197 		return data;
198 	}
199 
200 	public void setData(List data) {
201 		this.data = data;
202 	}
203 
204 	public int getSize() {
205 		return data.size();
206 	}
207 
208 	public void setMaxDepth(int maxDepth) {
209 		this.maxDepth = maxDepth;
210 	}
211 
212 	public String getJSONString(int from, int to) {
213 		// System.out.println(from+":"+to);
214 		if (from > getSize())
215 			return "[]";
216 
217 		String result = "[";
218 
219 		for (int i = from; i < to && i < getSize(); i++) {
220 			if (i != from) {
221 				result += ",";
222 			}
223 			result += ((AbstractDataReaderModel) (data.get(i)))
224 					.getJSONString(maxDepth);
225 		}
226 
227 		return result + "]";
228 	}
229 
230 	public String getNodeContentJSONString(String id) {
231 		AbstractDataReaderModel node = getNodeById(id);
232 
233 		String result = "";
234 
235 		if (node instanceof ReaderCategoryModel) {
236 			result = "[";
237 
238 			Iterator it = ((ReaderCategoryModel) node).getChildrenIterator();
239 			while (it != null && it.hasNext()) {
240 				result += ((AbstractDataReaderModel) it.next())
241 						.getJSONString(0)
242 						+ (it.hasNext() ? "," : "");
243 			}
244 
245 			return result + "]";
246 		} else {
247 			result = "{\"result\":\"" + ((ReaderItemModel) node).getContent()
248 					+ "\"}";
249 		}
250 
251 		return "";
252 	}
253 
254 }