📄 defaultuploadpolicy.java
字号:
* @see wjhk.jupload2.policies.UploadPolicy#addHeader(java.lang.String)
*/
public void addHeader(String header) {
this.headers.add(header);
}
/**
* @see wjhk.jupload2.policies.UploadPolicy#beforeUpload()
*/
public void beforeUpload() {
// Default: no special action.
}
/**
* The default behaviour (see {@link DefaultUploadPolicy}) is to check that
* the stringUploadSuccess applet parameter is present in the response from
* the server. The return is tested, in the order below: <DIR> <LI>False, if
* the stringUploadError is found. An error message is then displayed. <LI>
* True, if the stringUploadSuccess is null or empty (no test at all). <LI>
* True, if the stringUploadSuccess string is present in the
* serverOutputBody. <LI>True, If previous condition is not filled, but the
* HTTP header "HTTP(.*)200OK$" is present: the test is currently non
* blocking, because I can not test all possible HTTP configurations.<BR>
* <LI>False if the previous conditions are not fullfilled. </DIR>
*
* <BR>
* This method also looks for the stringUploadWarning regular expression.
* Each time it is matched, the found message is displayed to the user.
*
* @param status The HTTP response code
* @param msg The status message from the first line of the response (e.g.
* "200 OK").
* @param body The body of the HTTP answer.
* @return True or False, indicating if the upload is a success or not.
* @see UploadPolicy#checkUploadSuccess(int, String, String)
*/
public boolean checkUploadSuccess(int status, String msg, String body)
throws JUploadException {
boolean bReturn = false;
if (getDebugLevel() > 100) {
// Let's have a little time to check the upload messages written on
// the progress bar.
try {
Thread.sleep(300);
} catch (InterruptedException e) {
}
}
this.lastResponseBody = body;
this.lastResponseMessage = msg;
displayDebug("HTTP status: " + msg, 30);
// HTTP-100 correction, thanks to Marc Reidy
if ((status != 200) && (status != 100))
throw new JUploadExceptionUploadFailed("Received HTTP status "
+ msg);
// Let's analyze the body returned, line by line. The end of line
// character may be CR, LF, or CRLF. We navigate through the body, and
// replace any end of line character by a uniform CRLF.
Matcher matcherError, matcherWarning;
String line;
Pattern p = Pattern.compile("[\\r\\n]", Pattern.MULTILINE);
String[] lines = p.split(body);
StringBuffer sbBodyWithUniformCRLF = new StringBuffer(body.length());
for (int i = 0; i < lines.length; i += 1) {
line = lines[i];
sbBodyWithUniformCRLF.append(line).append("\r\n");
if (line == null || line.equals("")) {
// An empty line. Let's go the next line.
continue;
}
// Check if this is a success
// The success string should be in the http body
if (getStringUploadSuccess() != null
&& !getStringUploadSuccess().equals("")) {
if (this.patternSuccess.matcher(line).matches()) {
// We go on. There may be some WARNING message, hereafter.
bReturn = true;
}
}
// Check if this is an error
if (getStringUploadError() != null
&& !getStringUploadError().equals("")) {
matcherError = this.patternError.matcher(line);
if (matcherError.matches()) {
String errmsg = "An error occurs during upload (but the applet couldn't find the error message)";
if (matcherError.groupCount() > 0) {
if (!matcherError.group(1).equals("")) {
// Let's do a (very simple) formatting: one line to
// 100 characters
errmsg = matcherError.group(1);
int maxLineLength = 80;
StringBuffer sbErrMsg = new StringBuffer();
for (int j = 0, remaining = errmsg.length(); remaining > 0; remaining -= maxLineLength, j += 1) {
if (remaining <= maxLineLength) {
// It's the last loop.
sbErrMsg.append(errmsg.substring(j
* maxLineLength));
} else {
sbErrMsg.append(errmsg.substring(j
* maxLineLength, (j + 1)
* maxLineLength));
}
sbErrMsg.append("\n");
}
errmsg = sbErrMsg.toString();
}
}
this.lastResponseMessage = errmsg;
throw new JUploadExceptionUploadFailed(errmsg);
}
}// getStringUploadError
// Check if this is an warning
if (getStringUploadWarning() != null
&& !getStringUploadWarning().equals("")) {
matcherWarning = this.patternWarning.matcher(line);
if (matcherWarning.matches()) {
String warnmsg = "A warning occurs during upload (but the applet couldn't find the warning message)";
if (matcherWarning.groupCount() > 0) {
if (!matcherWarning.group(1).equals("")) {
warnmsg = matcherWarning.group(1);
}
}
this.lastResponseMessage = warnmsg;
displayWarn(warnmsg);
alertStr(warnmsg);
}
}// getStringUploadWarning
}// while(st.hasMoreTokens())
if (bReturn) {
return true;
}
// We found no stringUploadSuccess nor stringUploadError
if (getStringUploadSuccess() == null
|| getStringUploadSuccess().equals("")) {
// No chance to check the correctness of this upload. -> Assume Ok
return true;
}
// stringUploadSuccess was defined but we did not find it.
// This is most certainly an error as http-status 200 does *not* refer
// to the correctness of the content. It merely means that the protocol
// handling was ok. -> throw an exception
throw new JUploadExceptionUploadFailed(getClass().getName()
+ ".checkUploadSuccess(): The string \""
+ this.stringUploadSuccess
+ "\" was not found in the response body");
} // checkUploadSuccess
/**
* Generate a js String, that can be written in a javascript expression.
* It's up to the caller to put the starting and ending quotes. The double
* quotes are replaced by simple quotes (to let simple quotes unchanged, as
* it may be used in common language). Thus, start and end of JS string
* should be with double quotes, when using the return of this function.
*
* @param s
* @return The transformed string, that can be written in the output, into a
* javascript string. It doesn't contain the starting and ending
* double quotes.
*/
private String jsString(String s) {
String dollarReplacement = Matcher.quoteReplacement("\\$");
String singleQuoteReplacement = Matcher.quoteReplacement("\\'");
String linefeedReplacement = Matcher.quoteReplacement("\\n");
if (s == null || s.equals("")) {
displayDebug("jsString (nothing to do, s is an empty string)", 100);
return "";
} else {
displayDebug("jsString:", 100);
displayDebug(" original string:" + s, 100);
s = s.replaceAll("\\$", dollarReplacement);
displayDebug(" after dollar changed:" + s, 100);
s = s.replaceAll("\"", "'");
displayDebug(" after double quote changed:" + s, 100);
s = s.replaceAll("'", singleQuoteReplacement);
displayDebug(" after single quote changed:" + s, 100);
s = s.replaceAll("\n", linefeedReplacement);
displayDebug(" after LF changed:" + s, 100);
s = s.replaceAll("\r", "");
displayDebug(" after CR changed:" + s, 100);
return s;
}
}
/**
* @see wjhk.jupload2.policies.UploadPolicy#afterUpload(Exception, String)
*/
public void afterUpload(Exception e, String serverOutput)
throws JUploadException {
// If there was no error, and afterUploadURL is defined, let's try to go
// to this URL.
String url = getAfterUploadURL();
if (url != null) {
try {
if (url.toLowerCase().startsWith("javascript:")) {
// A JavaScript expression was specified. Execute it.
String expr = url.substring(11);
// Replacement of %msg%. Will do something only if the %msg%
// string exists in expr.
expr = expr
.replaceAll(
"%msg%",
Matcher
.quoteReplacement(jsString(getLastResponseMessage())));
// Replacement of %body%. Will do something only if the
// %body% string exists in expr.
expr = expr.replaceAll("%body%", Matcher
.quoteReplacement(jsString(getLastResponseBody())));
// Replacement of %success%. Will do something only if the
// %success% string exists in expr.
expr = expr.replaceAll("%success%", Matcher
.quoteReplacement((null == e) ? "true" : "false"));
displayDebug("Calling javascript expression: " + expr, 80);
JSObject.getWindow(getApplet()).eval(expr);
} else if (null == e) {
// This is not a javascript URL: we change the current page
// only if no error occured.
String target = getAfterUploadTarget();
if (getDebugLevel() >= 100) {
alertStr("No switch to getAfterUploadURL, because debug level is "
+ getDebugLevel() + " (>=100)");
} else {
// Let's change the current URL to edit names and
// comments, for the selected album. Ok, let's go and
// add names and comments to the newly updated pictures.
getApplet().getAppletContext().showDocument(
new URL(url),
(null == target) ? "_self" : target);
}
}
} catch (Exception ee) {
// Oops, no navigator. We are probably in debug mode, within
// eclipse for instance.
displayErr(ee);
}
}
}
/** @see UploadPolicy#alertStr(String) */
public void alertStr(String str) {
JOptionPane.showMessageDialog(null, str, "Alert",
JOptionPane.WARNING_MESSAGE);
}
/** @see UploadPolicy#alert(String) */
public void alert(String key) {
alertStr(getString(key));
}
/**
* The DefaultUpload accepts all file types: we just return an instance of
* FileData, without any test.
*
* @see UploadPolicy#createFileData(File, File)
*/
public FileData createFileData(File file, File root)
throws JUploadExceptionStopAddingFiles {
if (!fileFilterAccept(file)) {
String msg = file.getName() + " : "
+ getString("errForbiddenExtension");
displayWarn(msg);
if (JOptionPane.showConfirmDialog(null, msg, "alert",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.CANCEL_OPTION) {
// The user want to stop to add files to the list. For instance,
// when he/she added a whole directory, and it contains a lot of
// files that don't match the allowed file extension.
throw new JUploadExceptionStopAddingFiles("Stopped by the user");
}
return null;
} else if (!file.canRead()) {
displayInfo("Can't read file " + file.getName()
+ ". No DefaultFileData creation.");
return null;
} else {
return new DefaultFileData(file, root, this);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -