Created
April 8, 2015 17:27
-
-
Save SergioLarios/93cfc5861ba4dc9bd67a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.test; | |
import com.liferay.portal.kernel.util.StringPool; | |
import com.liferay.portal.kernel.util.Validator; | |
import com.liferay.portal.kernel.util.WebKeys; | |
import java.io.IOException; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
import javax.servlet.Filter; | |
import javax.servlet.FilterChain; | |
import javax.servlet.FilterConfig; | |
import javax.servlet.ServletException; | |
import javax.servlet.ServletRequest; | |
import javax.servlet.ServletResponse; | |
public class TranslatorFilter implements Filter { | |
private static final Pattern PRE1 = Pattern.compile("/cont-.*[0-9]$"); | |
private static final Pattern PRE2 = Pattern.compile("/of-.*[0-9]$"); | |
private static final Pattern PRE3 = Pattern.compile("/oferta-.*[0-9]$"); | |
private static final String REPALCE = "/-/content/"; | |
private static final String DETAIL = "/detalle"; | |
@Override | |
public void doFilter(ServletRequest req, ServletResponse res, | |
FilterChain chain) throws IOException, ServletException { | |
String uri = (String) req.getAttribute(WebKeys.INVOKER_FILTER_URI); | |
Matcher m1 = PRE1.matcher(uri); | |
Matcher m2 = PRE2.matcher(uri); | |
Matcher m3 = PRE3.matcher(uri); | |
if (m1.find(0) || m2.find(0) || m3.find(0)) { | |
String preUrl = StringPool.BLANK; | |
int delBlocks = 2; | |
if (m3.find(0)) { preUrl = DETAIL; } | |
if (m1.find(0)) { delBlocks = 1; } | |
try { | |
// New uri translation | |
String[] paths = uri.split(StringPool.SLASH); | |
String newUri = StringPool.BLANK; | |
for (int i = 0; i < paths.length - delBlocks; i++) { | |
if (!Validator.isBlank(paths[i])) { | |
newUri = newUri + StringPool.SLASH + paths[i]; | |
} | |
} | |
// Extracting article id | |
String articleString = paths[paths.length - 1]; | |
articleString = articleString.substring( | |
articleString.indexOf(StringPool.MINUS) + 1, articleString.length()); | |
Integer articleId = Integer.valueOf(articleString); | |
// New uri redirection | |
newUri = newUri + preUrl + REPALCE + articleId; | |
System.out.println("Pre --> " + uri); | |
System.out.println("Post --> " + newUri); | |
req.getRequestDispatcher(newUri).forward(req, res); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
chain.doFilter(req, res); | |
} | |
} | |
else { | |
chain.doFilter(req, res); | |
} | |
} | |
@Override | |
public void init(FilterConfig arg0) throws ServletException {} | |
@Override | |
public void destroy() {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment