2019-01-22 18:22:17 +01:00
|
|
|
package org.gcube.socialnetworking.token;
|
|
|
|
|
|
|
|
import java.net.MalformedURLException;
|
|
|
|
import java.net.URL;
|
2019-01-23 14:58:59 +01:00
|
|
|
import java.util.HashMap;
|
|
|
|
import java.util.Map;
|
2019-01-22 18:22:17 +01:00
|
|
|
|
|
|
|
public class URLToken extends ReplaceableToken {
|
|
|
|
|
2019-01-23 18:03:23 +01:00
|
|
|
private static String FINAL_CHARACTERS_TO_REMOVE_FROM_LINK = "[\\.\\,\\;\\)\\:]";
|
2019-01-23 17:57:50 +01:00
|
|
|
|
2019-01-23 18:01:42 +01:00
|
|
|
public URLToken(String token, String delimiter, int start, int end) {
|
|
|
|
super(token, delimiter, start, end);
|
|
|
|
}
|
|
|
|
|
2019-01-23 17:57:50 +01:00
|
|
|
public URLToken(Token token) {
|
2019-01-22 18:22:17 +01:00
|
|
|
super(token);
|
|
|
|
}
|
|
|
|
|
|
|
|
public static URL isURL(String string) {
|
|
|
|
try {
|
2019-01-24 11:02:12 +01:00
|
|
|
if(string.startsWith("(")) {
|
|
|
|
string = string.substring(1);
|
|
|
|
}
|
2019-01-23 17:57:50 +01:00
|
|
|
if(string.startsWith("www.")) {
|
|
|
|
string = "http://" + string;
|
|
|
|
}
|
2019-01-22 18:22:17 +01:00
|
|
|
return new URL(string);
|
|
|
|
} catch(MalformedURLException e) {
|
|
|
|
// not an URL
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2019-01-23 14:58:59 +01:00
|
|
|
public String getTokenReplacement() {
|
|
|
|
if(!replaced) {
|
2019-01-24 11:02:12 +01:00
|
|
|
// Testing if it is an URL preceded by (
|
|
|
|
String prefix = "";
|
|
|
|
if(tokenReplacement.startsWith("(")) {
|
|
|
|
tokenReplacement = token.substring(1);
|
|
|
|
prefix = "(";
|
|
|
|
}
|
|
|
|
|
2019-01-23 17:57:50 +01:00
|
|
|
Map<String,String> anchorAttibutes = new HashMap<>(1);
|
2019-01-23 14:58:59 +01:00
|
|
|
anchorAttibutes.put("target", "_blank");
|
2019-01-24 11:02:12 +01:00
|
|
|
String url = tokenReplacement;
|
|
|
|
String postfix = tokenReplacement.substring(tokenReplacement.length()-1);
|
|
|
|
if(postfix.matches(FINAL_CHARACTERS_TO_REMOVE_FROM_LINK)) {
|
|
|
|
url = tokenReplacement.substring(0, token.length()-1);
|
2019-01-23 17:57:50 +01:00
|
|
|
}else {
|
2019-01-24 11:02:12 +01:00
|
|
|
postfix = "";
|
2019-01-23 17:57:50 +01:00
|
|
|
}
|
2019-01-24 11:02:12 +01:00
|
|
|
tokenReplacement = prefix + ReplaceableToken.createLink(url, url, anchorAttibutes) + postfix;
|
2019-01-23 14:58:59 +01:00
|
|
|
replaced = true;
|
|
|
|
}
|
2019-01-23 17:05:15 +01:00
|
|
|
return tokenReplacement;
|
2019-01-23 14:58:59 +01:00
|
|
|
}
|
|
|
|
|
2019-01-22 18:22:17 +01:00
|
|
|
}
|