File Source: Trackback.java
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. The ASF licenses this file to You
4 * under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License. For additional information regarding
15 * copyright in this work, please see the NOTICE file in the top level
16 * directory of this distribution.
17 */
18
19 package org.apache.roller.weblogger.util;
20
21 import java.io.IOException;
22 import java.io.StringReader;
23 import java.net.MalformedURLException;
24 import java.net.URL;
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.regex.Matcher;
28 import java.util.regex.Pattern;
29 import org.apache.commons.httpclient.HttpClient;
30 import org.apache.commons.httpclient.HttpMethod;
31 import org.apache.commons.httpclient.HttpStatus;
32 import org.apache.commons.httpclient.methods.PostMethod;
33 import org.apache.commons.lang.StringEscapeUtils;
34 import org.apache.commons.lang.StringUtils;
35 import org.apache.commons.logging.Log;
36 import org.apache.commons.logging.LogFactory;
37 import org.apache.roller.weblogger.WebloggerException;
38 import org.apache.roller.weblogger.config.WebloggerConfig;
39 import org.apache.roller.weblogger.pojos.WeblogEntry;
40 import org.jdom.Document;
41 import org.jdom.Element;
42 import org.jdom.JDOMException;
43 import org.jdom.input.SAXBuilder;
44
45
46 /**
47 * Represents a trackback request.
48 */
49 public class Trackback {
50
/*
P/P * Method: org.apache.roller.weblogger.util.Trackback__static_init
*
* Postconditions:
* init'ed(log)
*/
51 private static final Log log = LogFactory.getLog(Trackback.class);
52
53 private final WeblogEntry entry;
54 private final String trackbackURL;
55
56
57 public Trackback(WeblogEntry tEntry, String tURL)
/*
P/P * Method: void org.apache.roller.weblogger.util.Trackback(WeblogEntry, String)
*
* Presumptions:
* org.apache.roller.weblogger.config.WebloggerConfig:getProperty(...)@62 != null
*
* Postconditions:
* this.entry == tEntry
* init'ed(this.entry)
* this.trackbackURL == tURL
* init'ed(this.trackbackURL)
*
* Test Vectors:
* org.apache.commons.lang.StringUtils:isEmpty(...)@63: {1}, {0}
*/
58 throws TrackbackNotAllowedException {
59
60 // Make sure trackback to URL is allowed
61 boolean allowTrackback = true;
62 String allowedURLs = WebloggerConfig.getProperty("trackback.allowedURLs");
63 if (!StringUtils.isEmpty(allowedURLs)) {
64 // in the case that the administrator has enabled trackbacks
65 // for only specific URLs, set it to false by default
66 allowTrackback = false;
67 String[] splitURLs = allowedURLs.split("\\|\\|");
+ 68 for (int i=0; i < splitURLs.length; i++) {
+ 69 Matcher m = Pattern.compile(splitURLs[i]).matcher(tURL);
70 if (m.matches()) {
71 allowTrackback = true;
72 break;
73 }
74 }
75 }
76
77 if(!allowTrackback) {
+ 78 throw new TrackbackNotAllowedException(tURL);
79 } else {
80 // test url
81 try {
82 new URL(tURL);
83 } catch(MalformedURLException ex) {
84 // bad url
85 throw new IllegalArgumentException("bad url: "+tURL);
86 }
87
88 entry = tEntry;
89 trackbackURL = tURL;
90 }
91
92 }
93
94
95 /**
96 * Sends trackback from entry to remote URL.
97 * See Trackback spec for details: http://www.sixapart.com/pronet/docs/trackback_spec
98 */
99 public RollerMessages send() throws WebloggerException {
100
/*
P/P * Method: RollerMessages send()
*
* Preconditions:
* this.entry != null
*
* Presumptions:
* org.apache.commons.logging.LogFactory:getLog(...)@51 != null
* org.apache.roller.weblogger.pojos.WeblogEntry:getWebsite(...)@109 != null
*
* Postconditions:
* return_value == &new RollerMessages(send#1)
* new ArrayList(RollerMessages#1) num objects == 1
* new ArrayList(RollerMessages#2) num objects == 1
* new RollerMessages(send#1) num objects == 1
* new RollerMessages(send#1).mErrors == &new ArrayList(RollerMessages#1)
* new RollerMessages(send#1).mMessages == &new ArrayList(RollerMessages#2)
*
* Test Vectors:
* org.apache.commons.httpclient.HttpClient:executeMethod(...)@129: {-231..199, 201..403, 405..232-1}, {200}, {404}
*/
101 RollerMessages messages = new RollerMessages();
102
103 log.debug("Sending trackback to url - "+trackbackURL);
104
105 // Construct data
106 String title = entry.getTitle();
107 String excerpt = StringUtils.left( Utilities.removeHTML(entry.getDisplayContent()),255 );
108 String url = entry.getPermalink();
109 String blog_name = entry.getWebsite().getName();
110
111 // build trackback post parameters as query string
112 Map params = new HashMap();
113 params.put("title", URLUtilities.encode(title));
114 params.put("excerpt", URLUtilities.encode(excerpt));
115 params.put("url", URLUtilities.encode(url));
116 params.put("blog_name", URLUtilities.encode(blog_name));
117 String queryString = URLUtilities.getQueryString(params);
118
119 log.debug("query string - "+queryString);
120
121 // prepare http request
122 HttpClient client = new HttpClient();
123 client.setConnectionTimeout(45 * 1000);
124 HttpMethod method = new PostMethod(trackbackURL);
125 method.setQueryString(queryString);
126
127 try {
128 // execute trackback
129 int statusCode = client.executeMethod(method);
130
131 // read response
132 byte[] response = method.getResponseBody();
133 String responseString = Utilities.escapeHTML(new String(response, "UTF-8"));
134
135 log.debug("result = "+statusCode+" "+method.getStatusText());
136 log.debug("response:\n"+responseString);
137
138 if(statusCode == HttpStatus.SC_OK) {
139 // trackback request succeeded, message will give details
140 try {
141 messages = parseTrackbackResponse(new String(response, "UTF-8"), messages);
142 } catch (Exception e) {
143 // Cannot parse response, indicates failure
144 messages.addError("weblogEdit.trackbackErrorParsing", responseString);
145 }
146 } else if(statusCode == HttpStatus.SC_NOT_FOUND) {
147 // 404, invalid trackback url
148 messages.addError("weblogEdit.trackbackError404");
149 } else {
150 // some other kind of error with url, like 500, 403, etc
151 // just provide a generic error message and give the http response text
152 messages.addError("weblogEdit.trackbackErrorResponse",
153 new String[] {""+statusCode, method.getStatusText()});
154 }
155
156 } catch (IOException e) {
157 // some kind of transport error sending trackback post
158 log.debug("Error sending trackback", e);
159 messages.addError("weblogEdit.trackbackErrorTransport");
160 } finally {
161 // release used connection
162 method.releaseConnection();
163 }
164
165 return messages;
166 }
167
168
169 /**
170 * Parse XML returned from trackback POST, returns error or success message
171 * in RollerMessages object.
172 */
173 private RollerMessages parseTrackbackResponse(String response, RollerMessages messages)
174 throws JDOMException, IOException {
175
/*
P/P * Method: RollerMessages parseTrackbackResponse(String, RollerMessages)
*
* Preconditions:
* messages != null
* (soft) messages.mErrors != null
* (soft) messages.mMessages != null
*
* Presumptions:
* org.jdom.Document:getRootElement(...)@179 != null
* org.jdom.input.SAXBuilder:build(...)@177 != null
*
* Postconditions:
* return_value == messages
* return_value != null
*
* Test Vectors:
* java.lang.String:equals(...)@181: {0}, {1}
*/
176 SAXBuilder builder = new SAXBuilder();
177 Document doc = builder.build(
178 new StringReader(StringEscapeUtils.unescapeHtml(response)));
179 Element root = doc.getRootElement();
180
181 if ("response".equals(root.getName())) {
182 int code = -99;
183 try {
184 code = Integer.parseInt(root.getChildText("error"));
185 } catch (NumberFormatException ignoredByDesign) {}
186
187 String message = root.getChildText("message");
188 if (code != 0) {
189 messages.addError("weblogEdit.trackbackFailure", Utilities.removeHTML(message));
190 } else {
191 messages.addMessage("weblogEdit.trackbackSuccess");
192 }
193 } else {
194 messages.addError("weblogEdit.trackbackErrorParsing", Utilities.removeHTML(response));
195 }
196
197 return messages;
198 }
199
200 }
SofCheck Inspector Build Version : 2.18479
| Trackback.java |
2009-Jan-02 14:24:46 |
| Trackback.class |
2009-Sep-04 03:12:32 |