001: /*
002: * Created on 16/10/2006
003: *
004: * Swing Components - visit http://sf.net/projects/gfd
005: *
006: * Copyright (C) 2006 Igor Regis da Silva Simões
007: *
008: * This program is free software; you can redistribute it and/or
009: * modify it under the terms of the GNU General Public License
010: * as published by the Free Software Foundation; either version 2
011: * of the License, or (at your option) any later version.
012: *
013: * This program is distributed in the hope that it will be useful,
014: * but WITHOUT ANY WARRANTY; without even the implied warranty of
015: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
016: * GNU General Public License for more details.
017: *
018: * You should have received a copy of the GNU General Public License
019: * along with this program; if not, write to the Free Software
020: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
021: *
022: */
023: package br.com.gfp.dao;
024:
025: import java.awt.Component;
026: import java.io.File;
027: import java.io.IOException;
028: import java.sql.SQLException;
029: import java.util.ArrayList;
030:
031: import javax.swing.JOptionPane;
032:
033: import br.com.gfp.internationalization.ActionsMessages;
034: import br.com.gfp.ols.componentes.OLSHttpClientFactory;
035: import br.com.gfp.ols.dados.SupportRequest;
036: import br.com.gfp.util.SimpleLog;
037: import br.com.gfpshare.beans.MessageView;
038: import br.com.gfpshare.proxy.http.GeneralHttpClient;
039:
040: public class SupportRequestDAO extends RequestDAO<SupportRequest> {
041: private MessageView messages = null;
042:
043: @Override
044: public synchronized boolean adicionarNovo(SupportRequest arg)
045: throws SQLException {
046: messages = (MessageView) GFPController.getGFPController()
047: .getContexto().get(GFPController.RODAPE_MESSAGER);
048: messages = messages.showMessage(ActionsMessages.getMessages()
049: .getString("sincronizandoRequestsTitulo"),
050: ActionsMessages.getMessages().getString(
051: "adicionandoRequestNoServidor"), true);
052: messages.getMessagePanel().getProgressBar().setIndeterminate(
053: true);
054: try {
055: arg = adicionaNovoRemoto(arg);
056: arg.setLocalPost(false);
057: arg.setMyRequest(true);
058: messages.getMessagePanel().setMessage(
059: ActionsMessages.getMessages().getString(
060: "requestAdicionadoNoServidor"), true);
061: } catch (IOException e) {
062: SQLException sqle = new SQLException(
063: "Erro ao adicionar supportRequest ao servidor SF");
064: StackTraceElement[] stackTemp1 = e.getStackTrace(), stackTemp2 = sqle
065: .getStackTrace();
066: StackTraceElement[] stack = new StackTraceElement[stackTemp1.length
067: + stackTemp2.length];
068: for (int i = 0; i < stackTemp1.length; i++) {
069: stack[i] = stackTemp1[i];
070: }
071: for (int i = 0; i < stackTemp2.length; i++) {
072: stack[i] = stackTemp1[i + stackTemp1.length];
073: }
074: sqle.setStackTrace(stack);
075: throw sqle;
076: }
077: boolean retorno = super .adicionarNovo(arg);
078: try {
079: sincronizarRequest(arg);
080: } catch (IOException e) {
081: ((SimpleLog) GFPController.getGFPController().getContexto()
082: .get(GFPController.LOG))
083: .log("Erro ao sincronizar SupportRequest! " + arg);
084: ((SimpleLog) GFPController.getGFPController().getContexto()
085: .get(GFPController.LOG)).log(e
086: .getLocalizedMessage());
087: ((SimpleLog) GFPController.getGFPController().getContexto()
088: .get(GFPController.LOG)).log(e);
089: }
090: messages.finishUse(3);
091: return retorno;
092: }
093:
094: /**
095: * Adiciona um SupportRequest ao site SF Lança exceção caso não obtenha sucesso
096: */
097: private SupportRequest adicionaNovoRemoto(SupportRequest sr)
098: throws IOException {
099: GeneralHttpClient httpClient = OLSHttpClientFactory
100: .getHttpClient();
101: httpClient.initRequest(
102: "http://sourceforge.net/tracker/index.php",
103: GeneralHttpClient.HTTPCLIENT_POST_METHOD);
104: httpClient.addPostParameter("group_id", "107070");
105: httpClient.addPostParameter("atid", "646573");
106: httpClient.addPostParameter("func", "postadd");
107: if (sr.getCategoria() != null)
108: httpClient.addPostParameter("category_id", sr
109: .getCategoria());
110: if (sr.getGrupo() != null)
111: httpClient.addPostParameter("artifact_group_id", sr
112: .getGrupo());
113: if (sr.getTitulo() != null)
114: httpClient.addPostParameter("summary", sr.getTitulo());
115: if (sr.getNovoTexto() != null)
116: httpClient.addPostParameter("details", sr.getNovoTexto());
117:
118: httpClient.addPostParameter("file_description", "GFP LOG FILE");
119:
120: httpClient.fileUpload("input_file", new File(sr.getLogDoDia()));
121: httpClient.executeRequest();
122: String resposta = httpClient.getResponseBody();
123: // TODO For test only
124: // String resposta = loadDummyFile();
125: System.out.println(resposta);
126: try {
127: resposta = resposta.substring(resposta
128: .indexOf("Submitted By"), resposta.indexOf(sr
129: .getTitulo()));
130: resposta = resposta.substring(resposta
131: .indexOf("<td nowrap>")
132: + "<td nowrap>".length());
133: resposta = resposta.substring(0, resposta.indexOf("</td>"))
134: .trim();
135: System.out.println(resposta);
136: sr.setId(Integer.parseInt(resposta));
137: System.out.println(sr);
138: } catch (StringIndexOutOfBoundsException e) {
139: // TODO Exceção
140: e.printStackTrace();
141: }
142: return sr;
143: }
144:
145: // TODO Remover metodo de testes
146: public static void main(String[] args) {
147: SupportRequest r = new SupportRequest();
148: r.setTitulo("DDDDDDDDD");
149: SupportRequestDAO controller = new SupportRequestDAO();
150: try {
151: r = controller.adicionaNovoRemoto(r);
152: } catch (IOException e) {
153: // TODO Auto-generated catch block
154: e.printStackTrace();
155: }
156: System.out.println(r);
157: }
158:
159: @Override
160: protected void loadNewRequests() {
161: messages = (MessageView) GFPController.getGFPController()
162: .getContexto().get(GFPController.RODAPE_MESSAGER);
163: messages = messages.showMessage(ActionsMessages.getMessages()
164: .getString("sincronizandoRequestsTitulo"),
165: ActionsMessages.getMessages().getString(
166: "sincronizandoRequestsMessage"), true);
167: messages.getMessagePanel().getProgressBar().setIndeterminate(
168: true);
169: SupportRequest requestTmp = null;
170: try {
171: GeneralHttpClient httpClient = OLSHttpClientFactory
172: .getHttpClient();
173: httpClient
174: .initRequest(
175: "http://sourceforge.net/tracker/?func=browse&group_id=107070&atid=646573",
176: GeneralHttpClient.HTTPCLIENT_GET_METHOD);
177: httpClient.executeRequest();
178: ArrayList<SupportRequest> requests = parseNewRequests(httpClient
179: .getResponseBody());
180: for (SupportRequest request : requests)
181: // Add request to requestTemp so we can print it on log
182: adicionarNovoLocal(requestTmp = request);
183: } catch (Exception e) {
184: ((SimpleLog) GFPController.getGFPController().getContexto()
185: .get(GFPController.LOG))
186: .log("Erro ao carregar novos SupportRequests! "
187: + requestTmp);
188: ((SimpleLog) GFPController.getGFPController().getContexto()
189: .get(GFPController.LOG)).log(e
190: .getLocalizedMessage());
191: ((SimpleLog) GFPController.getGFPController().getContexto()
192: .get(GFPController.LOG)).log(e);
193: JOptionPane.showMessageDialog((Component) GFPController
194: .getGFPController().getContexto().get(
195: GFPController.FRAME_PRINCIPAL),
196: ActionsMessages.getMessages().getString(
197: "internetNeeded"));
198: return;
199: }
200: }
201:
202: /**
203: * Dado um HTML com uma lista de SupportRequests ele carrega a todos verifica se estão na base de dados local, caso
204: * algum não esteja, este será adicionado a base da dedaos local
205: *
206: * @param page
207: * @throws SQLException
208: */
209: private ArrayList<SupportRequest> parseNewRequests(String page) {
210: ArrayList<SupportRequest> retorno = new ArrayList<SupportRequest>();
211: page = page.substring(page.indexOf("Submitted By"));
212: page = page.substring(page.indexOf("<tr bgcolor=\"#dababa\">")
213: + "<tr bgcolor=\"#dababa\">".length(), page
214: .indexOf("</table>"));
215:
216: SupportRequest supportRequest = new SupportRequest();
217: while (page.indexOf("<td nowrap>") != -1) {
218: SupportRequest existeNaBase = null;
219: supportRequest = new SupportRequest();
220: page = page.substring(page.indexOf("<td nowrap>")
221: + "<td nowrap>".length(), page.length());
222: supportRequest.setId(Integer.parseInt(page.substring(0,
223: page.indexOf("</td>")).trim()));
224: try {
225: existeNaBase = getBy(supportRequest);
226: } catch (SQLException e) {
227: // Do nothing, its normal error here
228: }
229: page = page.substring(page.indexOf("-->") + 3);
230: supportRequest.setTitulo(page.substring(0, page
231: .indexOf("<!--")));
232: page = page.substring(page.indexOf("<td align=\"center\">")
233: + "<td align=\"center\">".length());
234: supportRequest.setPrioridade(page.substring(0,
235: page.indexOf("</td>")).trim());
236:
237: page = page.substring(page.indexOf("<td>")
238: + "<td>".length());
239: supportRequest.setAtribuidoPara(page.substring(page
240: .indexOf(">") + 1, page.indexOf("</a>")));
241: supportRequest.setMyRequest(false);
242: supportRequest.setLocalPost(true);
243: if (existeNaBase == null)
244: retorno.add(supportRequest);
245: }
246: return retorno;
247: }
248:
249: /**
250: * Adiciona um novo support request sem intervir no conteudo da pagina do SF.
251: *
252: * @param supportRequest
253: * @throws SQLException
254: */
255: private void adicionarNovoLocal(SupportRequest supportRequest)
256: throws SQLException {
257: if (supportRequest.getNovoTexto() == null
258: || supportRequest.getNovoTexto().equals(""))
259: supportRequest.setNovoTexto("");
260: super .adicionarNovo(supportRequest);
261: }
262:
263: @Override
264: protected void sincronizarRequestsExistentes() throws SQLException {
265: SupportRequest arg = new SupportRequest();
266: arg.setLocalPost(true);
267: executarSQL(arg, "update \"Request\" set \"LocalPost\"=true",
268: false, false);
269: ArrayList<SupportRequest> requests = getAllBy(new SupportRequest());
270: int erroCount = 0;
271: for (SupportRequest request : requests) {
272: messages.getMessagePanel().setMessage(
273: ActionsMessages.getMessages().getString(
274: "atualizandoMansagemX")
275: + " "
276: + request.getId()
277: + " "
278: + request.getTitulo(), false);
279: try {
280: sincronizarRequest(request);
281: } catch (Exception e) {
282: ((SimpleLog) GFPController.getGFPController()
283: .getContexto().get(GFPController.LOG))
284: .log("Erro ao sincronizar SupportRequests!");
285: ((SimpleLog) GFPController.getGFPController()
286: .getContexto().get(GFPController.LOG)).log(e
287: .getLocalizedMessage());
288: ((SimpleLog) GFPController.getGFPController()
289: .getContexto().get(GFPController.LOG)).log(e);
290: JOptionPane.showMessageDialog((Component) GFPController
291: .getGFPController().getContexto().get(
292: GFPController.FRAME_PRINCIPAL),
293: ActionsMessages.getMessages().getString(
294: "internetNeeded"));
295: if (erroCount == 3)
296: return;
297: erroCount++;
298: }
299: }
300: messages.getMessagePanel().setMessage(
301: ActionsMessages.getMessages().getString(
302: "fimDaSincronizacao"), false);
303: messages.getMessagePanel().getProgressBar().setIndeterminate(
304: false);
305: messages.finishUse(10);
306: }
307:
308: /**
309: * @param request
310: * @throws IOException
311: * @throws SQLException
312: */
313: private void sincronizarRequest(SupportRequest request)
314: throws IOException, SQLException {
315: GeneralHttpClient httpClient = OLSHttpClientFactory
316: .getHttpClient();
317: httpClient.initRequest(
318: "http://sourceforge.net/tracker/index.php?func=detail&aid="
319: + request.getId()
320: + "&group_id=107070&atid=646573",
321: GeneralHttpClient.HTTPCLIENT_GET_METHOD);
322: httpClient.executeRequest();
323: SupportRequest supportRequest = parseSupportRequest(httpClient
324: .getResponseBody());
325: supportRequest.setId(request.getId());
326: supportRequest.setTitulo(request.getTitulo());
327: supportRequest.setMyRequest(request.isMyRequest());
328: supportRequest.setLocalPost(false);
329: supportRequest.setNovoTexto("");
330: if (supportRequest.getStatus().trim()
331: .equalsIgnoreCase("Closed"))
332: deletar(request);
333: else if (!supportRequest.toString().equals(request.toString()))
334: super .atualizar(supportRequest);
335: }
336:
337: /**
338: * Atauliza apenas a base da dados local sem intervir com os dados da pagina do SF
339: *
340: * @param supportRequest Dado a ser atualizado
341: * @return true se sucesso
342: * @throws SQLException caso falhe
343: * @throws IOException
344: */
345: private boolean atualizarRemoto(SupportRequest sr)
346: throws SQLException, IOException {
347: messages = (MessageView) GFPController.getGFPController()
348: .getContexto().get(GFPController.RODAPE_MESSAGER);
349: messages = messages.showMessage(ActionsMessages.getMessages()
350: .getString("sincronizandoRequestsTitulo"),
351: ActionsMessages.getMessages().getString(
352: "adicionandoRequestNoServidor"), true);
353: messages.getMessagePanel().getProgressBar().setIndeterminate(
354: true);
355: // group_id=107070&atid=646573&func=postaddcomment&artifact_id=1618153&details=sdfdfdfdfdfdfdfdfd&submit=SUBMIT
356: sr.validate();
357: // Este post é para adicionar o arquivo de log
358: GeneralHttpClient httpClient = OLSHttpClientFactory
359: .getHttpClient();
360: httpClient.initRequest(
361: "http://sourceforge.net/tracker/index.php",
362: GeneralHttpClient.HTTPCLIENT_POST_METHOD);
363: httpClient.addPostParameter("group_id", "107070");
364: httpClient.addPostParameter("atid", "646573");
365: httpClient.addPostParameter("new_artifact_type_id", "646573");
366: httpClient.addPostParameter("artifact_id", sr.getId()
367: .toString());
368: httpClient.addPostParameter("func", "postmod");// postaddcomment
369: httpClient.addPostParameter("details", sr.getNovoTexto());
370:
371: httpClient.addPostParameter("file_description", "GFP LOG FILE");
372: httpClient.fileUpload("input_file", new File(sr.getLogDoDia()));
373: httpClient.executeRequest();
374: httpClient.getResponseBody();
375:
376: // Este post é para adicionar o comentario
377: httpClient = OLSHttpClientFactory.getHttpClient();
378: httpClient.initRequest(
379: "http://sourceforge.net/tracker/index.php",
380: GeneralHttpClient.HTTPCLIENT_POST_METHOD);
381: httpClient.addPostParameter("group_id", "107070");
382: httpClient.addPostParameter("atid", "646573");
383: httpClient.addPostParameter("new_artifact_type_id", "646573");
384: httpClient.addPostParameter("artifact_group_id", sr.getGrupo());
385: httpClient.addPostParameter("artifact_id", sr.getId()
386: .toString());
387: httpClient.addPostParameter("func", "postaddcomment");
388: httpClient.addPostParameter("details", sr.getNovoTexto());
389: httpClient.executeRequest();
390: httpClient.getResponseBody();
391: messages.getMessagePanel().setMessage(
392: ActionsMessages.getMessages().getString(
393: "requestAdicionadoNoServidor"), true);
394: return true;
395: }
396:
397: private boolean atualizarLocal(SupportRequest supportRequest)
398: throws SQLException, IOException {
399: if (supportRequest.getNovoTexto() == null)
400: supportRequest.setNovoTexto("");
401: sincronizarRequest(supportRequest);
402: return true;
403: }
404:
405: @Override
406: public synchronized boolean atualizar(SupportRequest atualizacao)
407: throws SQLException {
408: try {
409: if (atualizarRemoto(atualizacao))
410: return atualizarLocal(atualizacao);
411: else
412: return false;
413: } catch (IOException e) {
414: ((SimpleLog) GFPController.getGFPController().getContexto()
415: .get(GFPController.LOG))
416: .log("Erro ao atualizar SupportRequest! "
417: + atualizacao);
418: ((SimpleLog) GFPController.getGFPController().getContexto()
419: .get(GFPController.LOG)).log(e
420: .getLocalizedMessage());
421: ((SimpleLog) GFPController.getGFPController().getContexto()
422: .get(GFPController.LOG)).log(e);
423: return false;
424: }
425: }
426:
427: /**
428: * dado um HTML extrai o SupportRequest representado nele (Apenas um support request por HTML)
429: *
430: * @param responseBody HTML
431: * @return SupportRequest
432: */
433: private SupportRequest parseSupportRequest(String page) {
434: SupportRequest request = new SupportRequest();
435: page = page.substring(page.indexOf("Number of Comments:"), page
436: .indexOf("<h3>Changes:</h3>"));
437: request.setCommentsCount(Integer.valueOf(page.substring(
438: page.indexOf("<br>") + "<br>".length(),
439: page.indexOf("</td>")).trim()));
440:
441: page = page.substring(page.indexOf("google_ad_section_start"));
442: request.setCategoria(page.substring(
443: page.indexOf("-->") + "-->".length(),
444: page.indexOf("<!-- google_ad_section_end")).trim());
445:
446: page = page.substring(page.indexOf("<br>") + "<br>".length());
447: request.setGrupo(page.substring(0, page.indexOf("</td>"))
448: .trim());
449:
450: page = page.substring(page.indexOf("<br>") + "<br>".length());
451: request.setAtribuidoPara(page.substring(0,
452: page.indexOf("</td>")).trim());
453:
454: page = page.substring(page.indexOf("<br>") + "<br>".length());
455: request.setPrioridade(page.substring(0, page.indexOf("</td>"))
456: .trim());
457:
458: page = page.substring(page.indexOf("<br>") + "<br>".length());
459: request.setStatus(page.substring(0, page.indexOf("</td>"))
460: .trim());
461:
462: page = page.substring(page.indexOf("<!--") + 4);
463: String text = page.substring(page.indexOf("-->") + 3, page
464: .indexOf("<!--"));
465:
466: page = page.substring(page.indexOf("<td colspan=\"2\">")
467: + "<td colspan=\"2\">".length());
468: page = page.substring(page.indexOf("<!--") + 4);
469: text += "\n"
470: + page.substring(page.indexOf("-->") + 3, page
471: .indexOf("<!--"));
472:
473: while (page.indexOf("Date") != -1) {
474: text += "\n-----------------------------------\n";
475: page = page.substring(page.indexOf("Date:"));
476: text += page.substring(page.indexOf("Date:"), page
477: .indexOf("<!--"));
478: page = page.substring(page.indexOf("<!--") + 4);
479: text += page.substring(page.indexOf("-->") + 3, page
480: .indexOf("<!--"));
481: }
482: request.setTexto(text);
483: return request;
484: }
485: }
|