social-util-library/src/main/java/org/gcube/socialnetworking/token/URLToken.java

61 lines
1.5 KiB
Java
Raw Normal View History

package org.gcube.socialnetworking.token;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class URLToken extends ReplaceableToken {
private static String FINAL_CHARACTERS_TO_REMOVE_FROM_LINK = "[\\.\\,\\;\\)\\:]";
public URLToken(String token, String delimiter, int start, int end) {
super(token, delimiter, start, end);
}
public URLToken(Token token) {
super(token);
}
public static URL isURL(String string) {
try {
if(string.startsWith("(")) {
string = string.substring(1);
}
if(string.startsWith("www.")) {
string = "http://" + string;
}
return new URL(string);
} catch(MalformedURLException e) {
// not an URL
return null;
}
}
public String getTokenReplacement() {
if(!replaced) {
// Testing if it is an URL preceded by (
String prefix = "";
if(tokenReplacement.startsWith("(")) {
tokenReplacement = token.substring(1);
prefix = "(";
}
Map<String,String> anchorAttibutes = new HashMap<>(1);
anchorAttibutes.put("target", "_blank");
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);
}else {
postfix = "";
}
tokenReplacement = prefix + ReplaceableToken.createLink(url, url, anchorAttibutes) + postfix;
replaced = true;
}
return tokenReplacement;
}
}