Java tutorial
/* * Copyright 2012 Kazumune Katagiri. (http://d.hatena.ne.jp/nemuzuka) * * 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 jp.co.nemuzuka.core.controller; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Date; import java.util.TimeZone; import java.util.logging.Logger; import jp.co.nemuzuka.core.annotation.ActionForm; import jp.co.nemuzuka.core.annotation.NoSessionCheck; import jp.co.nemuzuka.core.annotation.ProjectAdmin; import jp.co.nemuzuka.core.annotation.ProjectMember; import jp.co.nemuzuka.core.annotation.SystemManager; import jp.co.nemuzuka.core.entity.GlobalTransaction; import jp.co.nemuzuka.core.entity.TransactionEntity; import jp.co.nemuzuka.core.entity.UserInfo; import jp.co.nemuzuka.core.entity.UserTimeZone; import jp.co.nemuzuka.core.entity.mock.UserServiceImpl; import jp.co.nemuzuka.service.MemberService; import jp.co.nemuzuka.service.ProjectService; import jp.co.nemuzuka.service.impl.MemberServiceImpl; import jp.co.nemuzuka.service.impl.ProjectServiceImpl; import jp.co.nemuzuka.utils.ConvertUtils; import jp.co.nemuzuka.utils.CurrentDateUtils; import jp.co.nemuzuka.utils.DateTimeUtils; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; import org.slim3.controller.Controller; import org.slim3.util.BeanUtil; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; /** * Contoroller?. * @author kazumune */ public abstract class AbsController extends Controller { /** logger. */ protected final Logger logger = Logger.getLogger(getClass().getName()); /** UserInfo?. */ protected static final String USER_INFO_KEY = "userInfo"; /** token?. */ //Session????????????? protected static final String TOKEN_KEY = "jp.co.nemuzuka.token"; /** . */ protected UserService userService; //?URL /** ????????. */ protected static final String ERR_URL_NO_REGIST = "/error/noregist/"; /** . */ protected static final String ERR_URL_SYSERROR = "/error/syserror/"; /** Session. */ protected static final String ERR_SESSION_TIMEOUT = "/error/timeout/"; /** ????true. */ public static final boolean trialMode = Boolean .valueOf(System.getProperty("jp.co.nemuzuka.trial.mode", "false")); /** ??????SessionKey. */ protected static final String USE_TRIAL_USER = "jp.co.nemuzuka.trial"; /** * ?. * ThreadLocal??????????? * @see org.slim3.controller.Controller#tearDown() */ @Override protected void tearDown() { TransactionEntity entity = GlobalTransaction.transaction.get(); if (entity != null) { entity.rollback(); GlobalTransaction.transaction.remove(); } }; /** * UserInfo?. * Session?????UserInfo???? * @return UserInfo */ protected UserInfo getUserInfo() { return sessionScope(USER_INFO_KEY); } /** * . * ??logout?URL??? * Session??trial???????????????? * ????ThreadLocal???? */ protected void setUserService() { userService = UserServiceFactory.getUserService(); if (StringUtils.isNotEmpty((String) sessionScope(USE_TRIAL_USER))) { userService = new UserServiceImpl(userService); } //ThreadLocal? MemberService service = MemberServiceImpl.getInstance(); User curentUser = userService.getCurrentUser(); if (curentUser != null) { String timeZone = service.getTimeZone(userService.getCurrentUser().getEmail()); if (StringUtils.isEmpty(timeZone)) { timeZone = jp.co.nemuzuka.common.TimeZone.GMT_P_9.getCode(); } UserTimeZone.timeZone.set(TimeZone.getTimeZone(timeZone).getID()); } requestScope("logoutURL", "/logout"); } /** * Method?. * ???? * ??????????? * @param clazz Class * @param methodName ?? * @param paramClass ? * @return * @throws NoSuchMethodException ?????????????? */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected Method getDeclaredMethod(Class clazz, String methodName, Class[] paramClass) throws NoSuchMethodException { Method target = null; try { target = clazz.getDeclaredMethod(methodName, paramClass); } catch (NoSuchMethodException e) { Class superClazz = clazz.getSuperclass(); if (superClazz == null) { throw e; } return getDeclaredMethod(superClazz, methodName, paramClass); } return target; } /** * ??. * ??????? * @param clazz * @param methodName ?? * @return ???? */ @SuppressWarnings({ "rawtypes" }) protected Object invoke(Class clazz, String methodName) { //validate??? Method method = null; try { method = getDeclaredMethod(clazz, methodName, (Class[]) null); } catch (Exception e) { throw new RuntimeException(e); } //validate?? Object obj = null; try { method.setAccessible(true); obj = method.invoke(this, (Object[]) null); } catch (Exception e) { throw new RuntimeException(e); } return obj; } /** * ActionForm. * @ActionForm?????????? * ?????? * @param clazz */ @SuppressWarnings("rawtypes") protected void setActionForm(Class clazz) { //@ActionForm????????????? Field[] fields = clazz.getDeclaredFields(); for (Field target : fields) { Annotation[] annos = target.getAnnotations(); for (Annotation targetAnno : annos) { if (targetAnno instanceof ActionForm) { //? Object obj = null; try { target.setAccessible(true); obj = target.getType().newInstance(); BeanUtil.copy(request, obj); target.set(this, obj); } catch (Exception e) { throw new RuntimeException(e); } } } } } /** * Token. * Session?Token??? * @return Token */ protected String setToken() { String token = RandomStringUtils.randomAlphanumeric(32); sessionScope(TOKEN_KEY, token); return token; } /** * ?. * ThreadLocal????? */ protected void setTransaction() { TransactionEntity transactionEntity = new TransactionEntity(); GlobalTransaction.transaction.set(transactionEntity); } /** * Commit. * Commit??ThreadLocal???? */ protected void executeCommit() { TransactionEntity entity = GlobalTransaction.transaction.get(); entity.commit(); GlobalTransaction.transaction.remove(); } /** * ProjectAdmin?. * ??@ProjectAdmin??????????????? * ??????false???? * @param clazz * @return ??? or ???????true/??????false */ @SuppressWarnings("rawtypes") protected boolean executeProjectAdminCheck(Class clazz) { //execute?ProjectAdmin????? Method target = null; try { target = getDeclaredMethod(clazz, "execute", (Class[]) null); } catch (Exception e) { throw new RuntimeException(e); } ProjectAdmin projectAdmin = target.getAnnotation(ProjectAdmin.class); if (projectAdmin != null) { //UserInfo???????????? return getUserInfo().projectManager; } return true; } /** * ProjectMember?. * ??@ProjectMember??????????????? * ??????false???? * @param clazz * @return ??? or ???????true/??????false */ @SuppressWarnings("rawtypes") protected boolean executeProjectMemberCheck(Class clazz) { //execute?ProjectMember????? Method target = null; try { target = getDeclaredMethod(clazz, "execute", (Class[]) null); } catch (Exception e) { throw new RuntimeException(e); } ProjectMember projectMember = target.getAnnotation(ProjectMember.class); if (projectMember != null) { //UserInfo???????????? return getUserInfo().projectMember; } return true; } /** * SystemManager?. * ??@SystemManager??????????????? * ??????false???? * @param clazz * @return ??? or ???????true/??????false */ @SuppressWarnings("rawtypes") protected boolean executeSystemManagerCheck(Class clazz) { //execute?SystemManager????? Method target = null; try { target = getDeclaredMethod(clazz, "execute", (Class[]) null); } catch (Exception e) { throw new RuntimeException(e); } SystemManager systemManager = target.getAnnotation(SystemManager.class); if (systemManager != null) { //UserInfo???????????? return getUserInfo().systemManager; } return true; } /** * Session?. * Session??????? * @param clazz * @return Session?? or NoSessionCheck??????true/Session?????false */ @SuppressWarnings("rawtypes") protected boolean executeSessionCheck(Class clazz) { Method target = null; try { target = getDeclaredMethod(clazz, "execute", (Class[]) null); } catch (Exception e) { throw new RuntimeException(e); } NoSessionCheck noSessionCheck = target.getAnnotation(NoSessionCheck.class); if (noSessionCheck != null) { //execute?NoSessionCheck????????OK?? return true; } UserInfo userInfo = getUserInfo(); if (userInfo == null) { return false; } return true; } /** * UserInfo. * ???? * @param userInfo UserInfo */ protected void refreshUserInfo(UserInfo userInfo) { ProjectService service = ProjectServiceImpl.getInstance(); ProjectService.TargetProjectResult result = service .getUserProjectList(userService.getCurrentUser().getEmail(), userService.isUserAdmin()); userInfo.projectList = result.projectList; userInfo.systemManager = result.admin; //???()??? Date date = CurrentDateUtils.getInstance().getCurrentDateTime(); int min = ConvertUtils.toInteger(System.getProperty("jp.co.nemuzuka.session.refresh.min", "15")); date = DateTimeUtils.addMinutes(date, min); userInfo.refreshStartTime = date; //??TODO?Ticket? userInfo.dashboardLimitCnt = ConvertUtils .toInteger(System.getProperty("jp.co.nemuzuka.dashboard.list.limit", "5")); } /** * ?. * ?????????? * @param email ? * @return?????true */ protected boolean isExistsUser(String email) { removeSessionScope(USE_TRIAL_USER); MemberService service = MemberServiceImpl.getInstance(); Key key = service.getKey(email); if (key == null) { //????Key? if (trialMode) { key = service.getKey(UserServiceImpl.DUMMY_EMAIL); userService = new UserServiceImpl(userService); sessionScope(USE_TRIAL_USER, "1"); } } if (key == null) { //??? return false; } return true; } /** * Token?. * ?Session?Token???????? * @return ????true */ protected boolean isTokenCheck() { String reqToken = asString(TOKEN_KEY); String sessionToken = sessionScope(TOKEN_KEY); removeSessionScope(TOKEN_KEY); if (ObjectUtils.equals(reqToken, sessionToken) == false) { return false; } return true; } }