/*
* Copyright 2009 NCHOVY
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.krakenapps.servlet.text;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TextHttpServlet extends HttpServlet {
final Logger logger = LoggerFactory.getLogger(TextHttpServlet.class.getName());
private static final long serialVersionUID = 1L;
private TextHttpServiceApi manager;
public TextHttpServlet(TextHttpServiceApi manager) {
this.manager = manager;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain;charset=UTF-8");
logger.debug("text servlet pathinfo: " + req.getPathInfo());
String[] tokens = req.getPathInfo().split("/");
if (tokens.length != 3)
return;
String filterId = tokens[1];
String methodName = tokens[2];
try {
String text = (String) manager.invokeTextMethod(filterId, methodName, req);
if (text == null) {
logger.warn("text servlet null returned.");
}
resp.getWriter().print(text);
resp.getWriter().close();
} catch (NoSuchMethodException e) {
try {
Map<String, Object> params = buildParameterMap(req);
String text = (String) manager.invokeTextMethod(filterId, methodName, params);
if (text == null) {
logger.warn("text servlet null returned.");
}
resp.getWriter().print(text);
resp.getWriter().close();
} catch (Exception e1) {
e1.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private Map<String, Object> buildParameterMap(HttpServletRequest req) {
Map<String, Object> paramMap = new HashMap<String, Object>();
Enumeration it = req.getParameterNames();
while (it.hasMoreElements()) {
String name = (String) it.nextElement();
Object value = req.getParameter(name);
paramMap.put(name, value);
}
return paramMap;
}
}