/*******************************************************************************
* Copyright 2013 butor.com
*
* 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.butor.web.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.net.ConnectException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.servlet.http.HttpServletRequest;
import org.butor.json.JsonRequest;
import org.butor.json.service.Context;
import org.butor.json.service.ResponseHandler;
import org.butor.utils.ApplicationException;
import org.butor.utils.CommonMessageID;
import org.butor.utils.Message;
import org.butor.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.api.client.util.Strings;
import com.google.common.base.Throwables;
public abstract class BaseAjaxComponent implements AjaxComponent {
protected Logger _logger = LoggerFactory.getLogger(getClass());
private ConcurrentMap<String, Method> _servicesMap =
new ConcurrentHashMap<String, Method>();
private Object targetCmp = null;
public BaseAjaxComponent(Object targetCmp) {
this.targetCmp = targetCmp;
Method[] methods = this.targetCmp.getClass().getDeclaredMethods();
if (methods.length == 0) {
return;
}
for (Method m : methods) {
Class<?> rt = m.getReturnType();
Class<?>[] pts = m.getParameterTypes();
if (pts.length > 0 && pts[0].isAssignableFrom(Context.class) && rt.equals(void.class)) {
String key = buildKey(m.getName(), pts.length);
if (_servicesMap.containsKey(key)) {
_logger.warn(String.format("method %s with %d args has been mapped already. Ignoring similar one!"));
continue;
}
_logger.info("Adding service {} with {} args",m.getName(),pts.length);
_servicesMap.put(key, m);
}
}
}
protected String buildKey(String methodName_, int nbArgs_) {
return String.format("%s.%d", methodName_, nbArgs_);
}
protected void handleException(final ResponseHandler<?> handler, String serviceName, Throwable e) {
if (e instanceof ApplicationException) {
ApplicationException appEx = (ApplicationException)e;
_logger.warn(String.format("Failed to invoke service e=%s, cmp=%s",
serviceName, targetCmp.getClass().getName()), appEx);
for (Message message : appEx.getMessages()) {
handler.addMessage(message);
}
} else if (Throwables.getRootCause(e) instanceof ConnectException) {
_logger.error(String.format("Failed to connect service=%s, cmp=%s",
serviceName, targetCmp.getClass().getName()), e);
handler.addMessage(CommonMessageID.SERVICE_NOT_AVAILABLE.getMessage());
} else {
_logger.error(String.format("Failed to invoke service=%s, cmp=%s",
serviceName, targetCmp.getClass().getName()), e);
handler.addMessage(CommonMessageID.SERVICE_FAILURE.getMessage());
}
}
protected JsonRequest findJsonRequest(final HttpServletRequest req_) throws IOException {
JsonRequest jr = null;
InputStream is = null;
String qs;
if (req_.getMethod().equalsIgnoreCase("post")) {
is = req_.getInputStream();
StringWriter sw = new StringWriter();
while (true) {
int bb = is.read();
if (bb == -1)
break;
sw.write(bb);
}
qs = sw.toString();
} else {
qs = req_.getQueryString();
}
Map<String,String> argsMap = new HashMap<String, String>();
String[] toks = qs.split("&");
for (String tok : toks) {
tok = URLDecoder.decode(tok, "utf-8");
String[] pair = tok.split("=");
argsMap.put(pair[0], pair.length > 1 ? pair[1] : null);
}
jr = new JsonRequest();
String userId = null;
if (req_.getUserPrincipal() != null)
userId = req_.getUserPrincipal().getName();
jr.setUserId(userId);
String sessionId = argsMap.get("sessionId");
if (Strings.isNullOrEmpty(sessionId)) {
sessionId = req_.getSession().getId();
}
jr.setSessionId(sessionId);
jr.setReqId(argsMap.get("reqId"));
jr.setService(argsMap.get("service"));
jr.setLang(argsMap.get("lang"));
String val = argsMap.get("streaming");
jr.setStreaming(StringUtil.isEmpty(val) ? false : val.equalsIgnoreCase("yes") || val.equalsIgnoreCase("true"));
jr.setServiceArgsJson(URLDecoder.decode(argsMap.get("args"), "UTF-8"));
return jr;
}
protected Method findService(String serviceName, int nbArgs) {
String key = buildKey(serviceName, nbArgs +1);//+1 for context as arg[0]
Method m = _servicesMap.get(key);
return m;
}
protected Object getTargetCmp() {
return targetCmp;
}
}