proj_name
stringclasses
154 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
49
masked_class
stringlengths
68
178k
func_body
stringlengths
46
9.61k
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/common/filter/AuthFilter.java
AuthFilter
doFilter
class AuthFilter implements Filter { private static final Logger log = LoggerFactory.getLogger(AuthFilter.class); public void init(FilterConfig config) throws ServletException { } public void destroy() { } /** * doFilter determines if user is an administrator or redirect to login page * * @param req task request * @param resp task response * @param chain filter chain * @throws ServletException */ public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException {<FILL_FUNCTION_BODY>} }
HttpServletRequest servletRequest = (HttpServletRequest) req; HttpServletResponse servletResponse = (HttpServletResponse) resp; boolean isAdmin = false; try { //read auth token String authToken = AuthUtil.getAuthToken(servletRequest.getSession()); //check if exists if (authToken != null && !authToken.trim().equals("")) { //check if valid admin auth token String userType = AuthDB.isAuthorized(AuthUtil.getUserId(servletRequest.getSession()), authToken); if (userType != null) { String uri = servletRequest.getRequestURI(); if (Auth.MANAGER.equals(userType)) { isAdmin = true; } else if (!uri.contains("/manage/") && Auth.ADMINISTRATOR.equals(userType)) { isAdmin = true; } AuthUtil.setUserType(servletRequest.getSession(), userType); //check to see if user has timed out String timeStr = AuthUtil.getTimeout(servletRequest.getSession()); if (timeStr != null && !timeStr.trim().equals("")) { SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyHHmmss"); Date sessionTimeout = sdf.parse(timeStr); Date currentTime = new Date(); //if current time > timeout then redirect to login page if (sessionTimeout == null || currentTime.after(sessionTimeout)) { isAdmin = false; } else { AuthUtil.setTimeout(servletRequest.getSession()); } } else { isAdmin = false; } } } //if not admin redirect to login page if (!isAdmin) { AuthUtil.deleteAllSession(servletRequest.getSession()); servletResponse.sendRedirect(servletRequest.getContextPath() + "/"); } else { chain.doFilter(req, resp); } } catch (SQLException | ParseException | IOException | GeneralSecurityException ex) { AuthUtil.deleteAllSession(servletRequest.getSession()); log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); }
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/common/util/AppConfig.java
AppConfig
decryptProperty
class AppConfig { private static final Logger log = LoggerFactory.getLogger(AppConfig.class); private static PropertiesConfiguration prop; public static final String CONFIG_DIR = StringUtils.isNotEmpty(System.getProperty("CONFIG_DIR")) ? System.getProperty("CONFIG_DIR").trim() : AppConfig.class.getClassLoader().getResource(".").getPath(); static { try { //move configuration to specified dir if (StringUtils.isNotEmpty(System.getProperty("CONFIG_DIR"))) { File configFile = new File(CONFIG_DIR + "BastillionConfig.properties"); if (!configFile.exists()) { File oldConfig = new File(AppConfig.class.getClassLoader().getResource(".").getPath() + "BastillionConfig.properties"); FileUtils.moveFile(oldConfig, configFile); } configFile = new File(CONFIG_DIR + "jaas.conf"); if (!configFile.exists()) { File oldConfig = new File(AppConfig.class.getClassLoader().getResource(".").getPath() + "jaas.conf"); FileUtils.moveFile(oldConfig, configFile); } } prop = new PropertiesConfiguration(CONFIG_DIR + "BastillionConfig.properties"); } catch (IOException | ConfigurationException ex) { log.error(ex.toString(), ex); } } private AppConfig() { } /** * gets the property from config * * @param name property name * @return configuration property */ public static String getProperty(String name) { String property = null; if (StringUtils.isNotEmpty(name)) { if (StringUtils.isNotEmpty(System.getenv(name))) { property = System.getenv(name); } else if (StringUtils.isNotEmpty(System.getenv(name.toUpperCase()))) { property = System.getenv(name.toUpperCase()); } else { property = prop.getString(name); } } return property; } /** * gets the property from config * * @param name property name * @param defaultValue default value if property is empty * @return configuration property */ public static String getProperty(String name, String defaultValue) { String value = getProperty(name); if (StringUtils.isEmpty(value)) { value = defaultValue; } return value; } /** * gets the property from config and replaces placeholders * * @param name property name * @param replacementMap name value pairs of place holders to replace * @return configuration property */ public static String getProperty(String name, Map<String, String> replacementMap) { String value = getProperty(name); if (StringUtils.isNotEmpty(value)) { //iterate through map to replace text Set<String> keySet = replacementMap.keySet(); for (String key : keySet) { //replace values in string String rVal = replacementMap.get(key); value = value.replace("${" + key + "}", rVal); } } return value; } /** * removes property from the config * * @param name property name */ public static void removeProperty(String name) throws ConfigurationException { //remove property prop.clearProperty(name); prop.save(); } /** * updates the property in the config * * @param name property name * @param value property value */ public static void updateProperty(String name, String value) throws ConfigurationException { //remove property if (StringUtils.isNotEmpty(value)) { prop.setProperty(name, value); prop.save(); } } /** * checks if property is encrypted * * @param name property name * @return true if property is encrypted */ public static boolean isPropertyEncrypted(String name) { String property = prop.getString(name); if (StringUtils.isNotEmpty(property)) { return property.matches("^" + EncryptionUtil.CRYPT_ALGORITHM + "\\{.*\\}$"); } else { return false; } } /** * decrypts and returns the property from config * * @param name property name * @return configuration property */ public static String decryptProperty(String name) throws GeneralSecurityException {<FILL_FUNCTION_BODY>} /** * encrypts and updates the property in the config * * @param name property name * @param value property value */ public static void encryptProperty(String name, String value) throws ConfigurationException, GeneralSecurityException { //remove property if (StringUtils.isNotEmpty(value)) { prop.setProperty(name, EncryptionUtil.CRYPT_ALGORITHM + "{" + EncryptionUtil.encrypt(value) + "}"); prop.save(); } } }
String retVal = prop.getString(name); if (StringUtils.isNotEmpty(retVal)) { retVal = retVal.replaceAll("^" + EncryptionUtil.CRYPT_ALGORITHM + "\\{", "").replaceAll("\\}$", ""); retVal = EncryptionUtil.decrypt(retVal); } return retVal;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/common/util/AuthUtil.java
AuthUtil
getAuthToken
class AuthUtil { public static final String SESSION_ID = "sessionId"; public static final String USER_ID = "userId"; public static final String USERNAME = "username"; public static final String AUTH_TOKEN = "authToken"; public static final String TIMEOUT = "timeout"; private AuthUtil() { } /** * query session for OTP shared secret * * @param session http session * @return shared secret */ public static String getOTPSecret(HttpSession session) throws GeneralSecurityException { String secret = (String) session.getAttribute("otp_secret"); secret = EncryptionUtil.decrypt(secret); return secret; } /** * set authentication type * * @param session http session * @param authType authentication type */ public static void setAuthType(HttpSession session, String authType) { if (authType != null) { session.setAttribute("authType", authType); } } /** * query authentication type * * @param session http session * @return authentication type */ public static String getAuthType(HttpSession session) { String authType = (String) session.getAttribute("authType"); return authType; } /** * set user type * * @param session http session * @param userType user type */ public static void setUserType(HttpSession session, String userType) { if (userType != null) { session.setAttribute("userType", userType); } } /** * query user type * * @param session http session * @return user type */ public static String getUserType(HttpSession session) { String userType = (String) session.getAttribute("userType"); return userType; } /** * set session id * * @param session http session * @param sessionId session id */ public static void setSessionId(HttpSession session, Long sessionId) throws GeneralSecurityException { if (sessionId != null) { session.setAttribute(SESSION_ID, EncryptionUtil.encrypt(sessionId.toString())); } } /** * query session id * * @param session http session * @return session id */ public static Long getSessionId(HttpSession session) throws GeneralSecurityException { Long sessionId = null; String sessionIdStr = EncryptionUtil.decrypt((String) session.getAttribute(SESSION_ID)); if (sessionIdStr != null && !sessionIdStr.trim().equals("")) { sessionId = Long.parseLong(sessionIdStr); } return sessionId; } /** * query session for user id * * @param session http session * @return user id */ public static Long getUserId(HttpSession session) throws GeneralSecurityException { Long userId = null; String userIdStr = EncryptionUtil.decrypt((String) session.getAttribute(USER_ID)); if (userIdStr != null && !userIdStr.trim().equals("")) { userId = Long.parseLong(userIdStr); } return userId; } /** * query session for the username * * @param session http session * @return username */ public static String getUsername(HttpSession session) { return (String) session.getAttribute(USERNAME); } /** * query session for authentication token * * @param session http session * @return authentication token */ public static String getAuthToken(HttpSession session) throws GeneralSecurityException {<FILL_FUNCTION_BODY>} /** * query session for timeout * * @param session http session * @return timeout string */ public static String getTimeout(HttpSession session) { String timeout = (String) session.getAttribute(TIMEOUT); return timeout; } /** * set session OTP shared secret * * @param session http session * @param secret shared secret */ public static void setOTPSecret(HttpSession session, String secret) throws GeneralSecurityException { if (secret != null && !secret.trim().equals("")) { session.setAttribute("otp_secret", EncryptionUtil.encrypt(secret)); } } /** * set session user id * * @param session http session * @param userId user id */ public static void setUserId(HttpSession session, Long userId) throws GeneralSecurityException { if (userId != null) { session.setAttribute(USER_ID, EncryptionUtil.encrypt(userId.toString())); } } /** * set session username * * @param session http session * @param username username */ public static void setUsername(HttpSession session, String username) { if (username != null) { session.setAttribute(USERNAME, username); } } /** * set session authentication token * * @param session http session * @param authToken authentication token */ public static void setAuthToken(HttpSession session, String authToken) throws GeneralSecurityException { if (authToken != null && !authToken.trim().equals("")) { session.setAttribute(AUTH_TOKEN, EncryptionUtil.encrypt(authToken)); } } /** * set session timeout * * @param session http session */ public static void setTimeout(HttpSession session) { //set session timeout SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyHHmmss"); Calendar timeout = Calendar.getInstance(); timeout.add(Calendar.MINUTE, Integer.parseInt(AppConfig.getProperty("sessionTimeout", "15"))); session.setAttribute(TIMEOUT, sdf.format(timeout.getTime())); } /** * delete all session information * * @param session */ public static void deleteAllSession(HttpSession session) { session.setAttribute(TIMEOUT, null); session.setAttribute(AUTH_TOKEN, null); session.setAttribute(USER_ID, null); session.setAttribute(SESSION_ID, null); session.invalidate(); } /** * return client ip from servlet request * * @param servletRequest http servlet request * @return client ip */ public static String getClientIPAddress(HttpServletRequest servletRequest) { String clientIP = null; if (StringUtils.isNotEmpty(AppConfig.getProperty("clientIPHeader"))) { clientIP = servletRequest.getHeader(AppConfig.getProperty("clientIPHeader")); } if (StringUtils.isEmpty(clientIP)) { clientIP = servletRequest.getRemoteAddr(); } return clientIP; } }
String authToken = (String) session.getAttribute(AUTH_TOKEN); authToken = EncryptionUtil.decrypt(authToken); return authToken;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/control/LoginKtrl.java
LoginKtrl
loginSubmit
class LoginKtrl extends BaseKontroller { private static final Logger log = LoggerFactory.getLogger(LoginKtrl.class); //check if otp is enabled @Model(name = "otpEnabled") static final Boolean otpEnabled = ("required".equals(AppConfig.getProperty("oneTimePassword")) || "optional".equals(AppConfig.getProperty("oneTimePassword"))); private static final Logger loginAuditLogger = LoggerFactory.getLogger("io.bastillion.manage.control.LoginAudit"); private final String AUTH_ERROR = "Authentication Failed : Login credentials are invalid"; private final String AUTH_ERROR_NO_PROFILE = "Authentication Failed : There are no profiles assigned to this account"; private final String AUTH_ERROR_EXPIRED_ACCOUNT = "Authentication Failed : Account has expired"; @Model(name = "auth") Auth auth; public LoginKtrl(HttpServletRequest request, HttpServletResponse response) { super(request, response); } @Kontrol(path = "/login", method = MethodType.GET) public String login() { return "/login.html"; } @Kontrol(path = "/loginSubmit", method = MethodType.POST) public String loginSubmit() throws ServletException {<FILL_FUNCTION_BODY>} @Kontrol(path = "/logout", method = MethodType.GET) public String logout() { AuthUtil.deleteAllSession(getRequest().getSession()); return "redirect:/"; } /** * Validates fields for auth submit */ @Validate(input = "/login.html") public void validateLoginSubmit() { if (auth.getUsername() == null || auth.getUsername().trim().equals("")) { addFieldError("auth.username", "Required"); } if (auth.getPassword() == null || auth.getPassword().trim().equals("")) { addFieldError("auth.password", "Required"); } } }
String retVal = "redirect:/admin/menu.html"; String authToken = null; try { authToken = AuthDB.login(auth); //get client IP String clientIP = AuthUtil.getClientIPAddress(getRequest()); if (authToken != null) { User user = AuthDB.getUserByAuthToken(authToken); if (user != null) { String sharedSecret = null; if (otpEnabled) { sharedSecret = AuthDB.getSharedSecret(user.getId()); if (StringUtils.isNotEmpty(sharedSecret) && (auth.getOtpToken() == null || !OTPUtil.verifyToken(sharedSecret, auth.getOtpToken()))) { loginAuditLogger.info(auth.getUsername() + " (" + clientIP + ") - " + AUTH_ERROR); addError(AUTH_ERROR); return "/login.html"; } } //check to see if admin has any assigned profiles if (!User.MANAGER.equals(user.getUserType()) && (user.getProfileList() == null || user.getProfileList().size() <= 0)) { loginAuditLogger.info(auth.getUsername() + " (" + clientIP + ") - " + AUTH_ERROR_NO_PROFILE); addError(AUTH_ERROR_NO_PROFILE); return "/login.html"; } //check to see if account has expired if (user.isExpired()) { loginAuditLogger.info(auth.getUsername() + " (" + clientIP + ") - " + AUTH_ERROR_EXPIRED_ACCOUNT); addError(AUTH_ERROR_EXPIRED_ACCOUNT); return "/login.html"; } AuthUtil.setAuthToken(getRequest().getSession(), authToken); AuthUtil.setUserId(getRequest().getSession(), user.getId()); AuthUtil.setAuthType(getRequest().getSession(), user.getAuthType()); AuthUtil.setTimeout(getRequest().getSession()); AuthUtil.setUsername(getRequest().getSession(), user.getUsername()); AuthDB.updateLastLogin(user); //for first time login redirect to set OTP if (otpEnabled && StringUtils.isEmpty(sharedSecret)) { retVal = "redirect:/admin/viewOTP.ktrl"; } else if ("changeme".equals(auth.getPassword()) && Auth.AUTH_BASIC.equals(user.getAuthType())) { retVal = "redirect:/admin/userSettings.ktrl"; } loginAuditLogger.info(auth.getUsername() + " (" + clientIP + ") - Authentication Success"); } } else { loginAuditLogger.info(auth.getUsername() + " (" + clientIP + ") - " + AUTH_ERROR); addError(AUTH_ERROR); retVal = "/login.html"; } } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return retVal;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/control/OTPKtrl.java
OTPKtrl
qrImage
class OTPKtrl extends BaseKontroller { private static final Logger log = LoggerFactory.getLogger(OTPKtrl.class); public static final boolean requireOTP = "required".equals(AppConfig.getProperty("oneTimePassword")); //QR image size private static final int QR_IMAGE_WIDTH = 325; private static final int QR_IMAGE_HEIGHT = 325; @Model(name = "qrImage") String qrImage; @Model(name = "sharedSecret") String sharedSecret; public OTPKtrl(HttpServletRequest request, HttpServletResponse response) { super(request, response); } @Kontrol(path = "/admin/viewOTP", method = MethodType.GET) public String viewOTP() throws ServletException { sharedSecret = OTPUtil.generateSecret(); try { AuthUtil.setOTPSecret(getRequest().getSession(), sharedSecret); } catch (GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } qrImage = new Date().getTime() + ".png"; return "/admin/two-factor_otp.html"; } @Kontrol(path = "/admin/otpSubmit", method = MethodType.POST) public String otpSubmit() throws ServletException { try { AuthDB.updateSharedSecret(sharedSecret, AuthUtil.getAuthToken(getRequest().getSession())); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } if (requireOTP) { AuthUtil.deleteAllSession(getRequest().getSession()); } return "redirect:/logout.ktrl"; } @Kontrol(path = "/admin/qrImage", method = MethodType.GET) public String qrImage() throws ServletException {<FILL_FUNCTION_BODY>} }
String username; String secret; try { username = UserDB.getUser(AuthUtil.getUserId(getRequest().getSession())).getUsername(); secret = AuthUtil.getOTPSecret(getRequest().getSession()); AuthUtil.setOTPSecret(getRequest().getSession(), null); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } try { String qrCodeText = "otpauth://totp/Bastillion%20%28" + URLEncoder.encode(getRequest().getHeader("host").replaceAll("\\:.*$", ""), "utf-8") + "%29:" + username + "?secret=" + secret; QRCodeWriter qrWriter = new QRCodeWriter(); Hashtable<EncodeHintType, String> hints = new Hashtable<>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix matrix = qrWriter.encode(qrCodeText, BarcodeFormat.QR_CODE, QR_IMAGE_WIDTH, QR_IMAGE_HEIGHT, hints); getResponse().setContentType("image/png"); BufferedImage image = new BufferedImage(QR_IMAGE_WIDTH, QR_IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, QR_IMAGE_WIDTH, QR_IMAGE_HEIGHT); graphics.setColor(Color.BLACK); for (int x = 0; x < QR_IMAGE_WIDTH; x++) { for (int y = 0; y < QR_IMAGE_HEIGHT; y++) { if (matrix.get(x, y)) { graphics.fillRect(x, y, 1, 1); } } } ImageIO.write(image, "png", getResponse().getOutputStream()); getResponse().getOutputStream().flush(); getResponse().getOutputStream().close(); } catch (IOException | WriterException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return null;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/control/ProfileKtrl.java
ProfileKtrl
saveProfile
class ProfileKtrl extends BaseKontroller { private static final Logger log = LoggerFactory.getLogger(ProfileKtrl.class); @Model(name = "sortedSet") SortedSet sortedSet = new SortedSet(); @Model(name = "profile") Profile profile = new Profile(); public ProfileKtrl(HttpServletRequest request, HttpServletResponse response) { super(request, response); } @Kontrol(path = "/manage/viewProfiles", method = MethodType.GET) public String viewSystems() throws ServletException { try { sortedSet = ProfileDB.getProfileSet(sortedSet); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return "/manage/view_profiles.html"; } @Kontrol(path = "/manage/saveProfile", method = MethodType.POST) public String saveProfile() throws ServletException {<FILL_FUNCTION_BODY>} @Kontrol(path = "/manage/deleteProfile", method = MethodType.GET) public String deleteProfile() throws ServletException { if (profile.getId() != null) { try { ProfileDB.deleteProfile(profile.getId()); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } } return "redirect:/manage/viewProfiles.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField(); } /** * validate save profile */ @Validate(input = "/manage/view_profiles.html") public void validateSaveProfile() throws ServletException { if (profile == null || profile.getNm() == null || profile.getNm().trim().equals("")) { addFieldError("profile.nm", "Required"); } if (!this.getFieldErrors().isEmpty()) { try { sortedSet = ProfileDB.getProfileSet(sortedSet); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } } } }
try { if (profile.getId() != null) { ProfileDB.updateProfile(profile); } else { ProfileDB.insertProfile(profile); } } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return "redirect:/manage/viewProfiles.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField();
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/control/ProfileSystemsKtrl.java
ProfileSystemsKtrl
viewProfileSystems
class ProfileSystemsKtrl extends BaseKontroller { private static final Logger log = LoggerFactory.getLogger(ProfileSystemsKtrl.class); @Model(name = "profile") Profile profile; @Model(name = "sortedSet") SortedSet sortedSet = new SortedSet(); @Model(name = "systemSelectId") List<Long> systemSelectId = new ArrayList<>(); public ProfileSystemsKtrl(HttpServletRequest request, HttpServletResponse response) { super(request, response); } @Kontrol(path = "/manage/viewProfileSystems", method = MethodType.GET) public String viewProfileSystems() throws ServletException {<FILL_FUNCTION_BODY>} @Kontrol(path = "/manage/assignSystemsToProfile", method = MethodType.POST) public String assignSystemsToProfile() throws ServletException { if (systemSelectId != null) { try { ProfileSystemsDB.setSystemsForProfile(profile.getId(), systemSelectId); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } } RefreshAuthKeyUtil.refreshProfileSystems(profile.getId()); return "redirect:/manage/viewProfiles.ktrl"; } }
if (profile != null && profile.getId() != null) { try { profile = ProfileDB.getProfile(profile.getId()); sortedSet = SystemDB.getSystemSet(sortedSet, profile.getId()); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } } return "/manage/view_profile_systems.html";
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/control/ProfileUsersKtrl.java
ProfileUsersKtrl
assignSystemsToProfile
class ProfileUsersKtrl extends BaseKontroller { private static final Logger log = LoggerFactory.getLogger(ProfileUsersKtrl.class); @Model(name = "profile") Profile profile; @Model(name = "sortedSet") SortedSet sortedSet = new SortedSet(); @Model(name = "userSelectId") List<Long> userSelectId = new ArrayList<>(); public ProfileUsersKtrl(HttpServletRequest request, HttpServletResponse response) { super(request, response); } @Kontrol(path = "/manage/viewProfileUsers", method = MethodType.GET) public String viewProfileUsers() throws ServletException { if (profile != null && profile.getId() != null) { try { profile = ProfileDB.getProfile(profile.getId()); sortedSet = UserDB.getAdminUserSet(sortedSet, profile.getId()); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } } return "/manage/view_profile_users.html"; } @Kontrol(path = "/manage/assignUsersToProfile", method = MethodType.POST) public String assignSystemsToProfile() throws ServletException {<FILL_FUNCTION_BODY>} }
if (userSelectId != null) { try { UserProfileDB.setUsersForProfile(profile.getId(), userSelectId); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } } RefreshAuthKeyUtil.refreshProfileSystems(profile.getId()); return "redirect:/manage/viewProfiles.ktrl";
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/control/ScriptKtrl.java
ScriptKtrl
validateSaveScript
class ScriptKtrl extends BaseKontroller { private static final Logger log = LoggerFactory.getLogger(ScriptKtrl.class); @Model(name = "sortedSet") SortedSet sortedSet = new SortedSet(); @Model(name = "script") Script script = new Script(); public ScriptKtrl(HttpServletRequest request, HttpServletResponse response) { super(request, response); } @Kontrol(path = "/admin/viewScripts", method = MethodType.GET) public String viewScripts() throws ServletException { try { Long userId = AuthUtil.getUserId(getRequest().getSession()); sortedSet = ScriptDB.getScriptSet(sortedSet, userId); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return "/admin/view_scripts.html"; } @Kontrol(path = "/admin/saveScript", method = MethodType.POST) public String saveScript() throws ServletException { try { Long userId = AuthUtil.getUserId(getRequest().getSession()); if (script.getId() != null) { ScriptDB.updateScript(script, userId); } else { ScriptDB.insertScript(script, userId); } } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return "redirect:/admin/viewScripts.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField(); } @Kontrol(path = "/admin/deleteScript", method = MethodType.GET) public String deleteScript() throws ServletException { if (script.getId() != null) { try { Long userId = AuthUtil.getUserId(getRequest().getSession()); ScriptDB.deleteScript(script.getId(), userId); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } } return "redirect:/admin/viewScripts.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField(); } /** * Validates all fields for adding a user */ @Validate(input = "/admin/view_scripts.html") public void validateSaveScript() throws ServletException {<FILL_FUNCTION_BODY>} }
if (script == null || script.getDisplayNm() == null || script.getDisplayNm().trim().equals("")) { addFieldError("script.displayNm", "Required"); } if (script == null || script.getScript() == null || script.getScript().trim().equals("") || (new Script()).getScript().trim().equals(script.getScript().trim())) { addFieldError("script.script", "Required"); } if (!this.getFieldErrors().isEmpty()) { try { Long userId = AuthUtil.getUserId(getRequest().getSession()); sortedSet = ScriptDB.getScriptSet(sortedSet, userId); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } }
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/control/SessionAuditKtrl.java
SessionAuditKtrl
getJSONTermOutputForSession
class SessionAuditKtrl extends BaseKontroller { private static final Logger log = LoggerFactory.getLogger(SessionAuditKtrl.class); @Model(name = "sortedSet") SortedSet sortedSet = new SortedSet(); @Model(name = "sessionId") Long sessionId; @Model(name = "instanceId") Integer instanceId; @Model(name = "sessionAudit") SessionAudit sessionAudit; @Model(name = "systemList") List<HostSystem> systemList; @Model(name = "userList") List<User> userList; public SessionAuditKtrl(HttpServletRequest request, HttpServletResponse response) { super(request, response); } @Kontrol(path = "/manage/viewSessions", method = MethodType.GET) public String viewSessions() throws ServletException { if (sortedSet.getOrderByField() == null || sortedSet.getOrderByField().trim().equals("")) { sortedSet.setOrderByField(SessionAuditDB.SORT_BY_SESSION_TM); sortedSet.setOrderByDirection("desc"); } try { systemList = SystemDB.getSystemSet(new SortedSet(SystemDB.SORT_BY_NAME)).getItemList(); userList = UserDB.getUserSet(new SortedSet(SessionAuditDB.SORT_BY_USERNAME)).getItemList(); sortedSet = SessionAuditDB.getSessions(sortedSet); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return "/manage/view_sessions.html"; } @Kontrol(path = "/manage/getTermsForSession", method = MethodType.GET) public String getTermsForSession() throws ServletException { try { sessionAudit = SessionAuditDB.getSessionsTerminals(sessionId); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return "/manage/view_terms.html"; } @Kontrol(path = "/manage/getJSONTermOutputForSession", method = MethodType.GET) public String getJSONTermOutputForSession() throws ServletException {<FILL_FUNCTION_BODY>} }
try { String json = new Gson().toJson(SessionAuditDB.getTerminalLogsForSession(sessionId, instanceId)); getResponse().getOutputStream().write(json.getBytes()); } catch (SQLException | GeneralSecurityException | IOException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return null;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/control/SystemKtrl.java
SystemKtrl
validateSaveSystem
class SystemKtrl extends BaseKontroller { private static final Logger log = LoggerFactory.getLogger(SystemKtrl.class); public static final String REQUIRED = "Required"; @Model(name = "sortedSet") SortedSet sortedSet = new SortedSet(); @Model(name = "hostSystem") HostSystem hostSystem = new HostSystem(); @Model(name = "script") Script script = null; @Model(name = "password") String password; @Model(name = "passphrase") String passphrase; @Model(name = "profileList") List<Profile> profileList = new ArrayList<>(); public SystemKtrl(HttpServletRequest request, HttpServletResponse response) { super(request, response); } @Kontrol(path = "/admin/viewSystems", method = MethodType.GET) public String viewAdminSystems() throws ServletException { try { Long userId = AuthUtil.getUserId(getRequest().getSession()); if (Auth.MANAGER.equals(AuthUtil.getUserType(getRequest().getSession()))) { sortedSet = SystemDB.getSystemSet(sortedSet); profileList = ProfileDB.getAllProfiles(); } else { sortedSet = SystemDB.getUserSystemSet(sortedSet, userId); profileList = UserProfileDB.getProfilesByUser(userId); } if (script != null && script.getId() != null) { script = ScriptDB.getScript(script.getId(), userId); } } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return "/admin/view_systems.html"; } @Kontrol(path = "/manage/viewSystems", method = MethodType.GET) public String viewManageSystems() throws ServletException { try { sortedSet = SystemDB.getSystemSet(sortedSet); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return "/manage/view_systems.html"; } @Kontrol(path = "/manage/saveSystem", method = MethodType.POST) public String saveSystem() throws ServletException { String retVal = "redirect:/manage/viewSystems.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField(); hostSystem = SSHUtil.authAndAddPubKey(hostSystem, passphrase, password); try { if (hostSystem.getId() != null) { SystemDB.updateSystem(hostSystem); } else { hostSystem.setId(SystemDB.insertSystem(hostSystem)); } sortedSet = SystemDB.getSystemSet(sortedSet); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } if (!HostSystem.SUCCESS_STATUS.equals(hostSystem.getStatusCd())) { retVal = "/manage/view_systems.html"; } return retVal; } @Kontrol(path = "/manage/deleteSystem", method = MethodType.GET) public String deleteSystem() throws ServletException { if (hostSystem.getId() != null) { try { SystemDB.deleteSystem(hostSystem.getId()); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } } return "redirect:/manage/viewSystems.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField(); } /** * Validates all fields for adding a host system */ @Validate(input = "/manage/view_systems.html") public void validateSaveSystem() throws ServletException {<FILL_FUNCTION_BODY>} }
if (hostSystem == null || hostSystem.getDisplayNm() == null || hostSystem.getDisplayNm().trim().equals("")) { addFieldError("hostSystem.displayNm", REQUIRED); } if (hostSystem == null || hostSystem.getUser() == null || hostSystem.getUser().trim().equals("")) { addFieldError("hostSystem.user", REQUIRED); } if (hostSystem == null || hostSystem.getHost() == null || hostSystem.getHost().trim().equals("")) { addFieldError("hostSystem.host", REQUIRED); } if (hostSystem == null || hostSystem.getPort() == null) { addFieldError("hostSystem.port", REQUIRED); } else if (!(hostSystem.getPort() > 0)) { addFieldError("hostSystem.port", "Invalid"); } if (hostSystem == null || hostSystem.getAuthorizedKeys() == null || hostSystem.getAuthorizedKeys().trim().equals("") || hostSystem.getAuthorizedKeys().trim().equals("~")) { addFieldError("hostSystem.authorizedKeys", REQUIRED); } if (!this.getFieldErrors().isEmpty()) { try { sortedSet = SystemDB.getSystemSet(sortedSet); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } }
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/control/UploadAndPushKtrl.java
UploadAndPushKtrl
push
class UploadAndPushKtrl extends BaseKontroller { private static final Logger log = LoggerFactory.getLogger(UploadAndPushKtrl.class); public static final String UPLOAD_PATH = DBUtils.class.getClassLoader().getResource(".").getPath() + "../upload"; @Model(name = "upload") File upload; @Model(name = "uploadFileName") String uploadFileName; @Model(name = "idList") List<Long> idList = new ArrayList<>(); @Model(name = "pushDir") String pushDir = "~"; @Model(name = "hostSystemList") List<HostSystem> hostSystemList; @Model(name = "pendingSystemStatus") HostSystem pendingSystemStatus; @Model(name = "currentSystemStatus") HostSystem currentSystemStatus; public UploadAndPushKtrl(HttpServletRequest request, HttpServletResponse response) { super(request, response); } @Kontrol(path = "/admin/setUpload", method = MethodType.GET) public String setUpload() throws Exception { Long userId = AuthUtil.getUserId(getRequest().getSession()); SystemStatusDB.setInitialSystemStatus(idList, userId, AuthUtil.getUserType(getRequest().getSession())); return "/admin/upload.html"; } @Kontrol(path = "/admin/uploadSubmit", method = MethodType.POST) public String uploadSubmit() { String retVal = "/admin/upload_result.html"; try { Long userId = AuthUtil.getUserId(getRequest().getSession()); List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(getRequest()); for (FileItem item : multiparts) { if (!item.isFormField()) { uploadFileName = new File(item.getName()).getName(); File path = new File(UPLOAD_PATH); if (!path.exists()) { path.mkdirs(); } upload = new File(UPLOAD_PATH + File.separator + uploadFileName); item.write(upload); } else { pushDir = item.getString(); } } pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId); hostSystemList = SystemStatusDB.getAllSystemStatus(userId); } catch (Exception ex) { log.error(ex.toString(), ex); retVal = "/admin/upload.html"; } //reset csrf token back since it's already set on page load getRequest().getSession().setAttribute(SecurityFilter._CSRF, getRequest().getParameter(SecurityFilter._CSRF)); return retVal; } @Kontrol(path = "/admin/push", method = MethodType.POST) public String push() throws ServletException {<FILL_FUNCTION_BODY>} }
try { Long userId = AuthUtil.getUserId(getRequest().getSession()); Long sessionId = AuthUtil.getSessionId(getRequest().getSession()); //get next pending system pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId); if (pendingSystemStatus != null) { //get session for system SchSession session = null; for (Integer instanceId : SecureShellKtrl.getUserSchSessionMap().get(sessionId).getSchSessionMap().keySet()) { //if host system id matches pending system then upload if (pendingSystemStatus.getId().equals(SecureShellKtrl.getUserSchSessionMap().get(sessionId).getSchSessionMap().get(instanceId).getHostSystem().getId())) { session = SecureShellKtrl.getUserSchSessionMap().get(sessionId).getSchSessionMap().get(instanceId); } } if (session != null) { //push upload to system currentSystemStatus = SSHUtil.pushUpload(pendingSystemStatus, session.getSession(), UPLOAD_PATH + "/" + uploadFileName, pushDir + "/" + uploadFileName); //update system status SystemStatusDB.updateSystemStatus(currentSystemStatus, userId); pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId); } } //if push has finished to all servers then delete uploaded file if (pendingSystemStatus == null) { File delFile = new File(UPLOAD_PATH, uploadFileName); FileUtils.deleteQuietly(delFile); //delete all expired files in upload path File delDir = new File(UPLOAD_PATH); if (delDir.isDirectory()) { //set expire time to delete all files older than 48 hrs Calendar expireTime = Calendar.getInstance(); expireTime.add(Calendar.HOUR, -48); Iterator<File> filesToDelete = FileUtils.iterateFiles(delDir, new AgeFileFilter(expireTime.getTime()), TrueFileFilter.TRUE); while (filesToDelete.hasNext()) { delFile = filesToDelete.next(); delFile.delete(); } } } hostSystemList = SystemStatusDB.getAllSystemStatus(userId); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } //reset csrf token back since it's already set on page load getRequest().getSession().setAttribute(SecurityFilter._CSRF, getRequest().getParameter(SecurityFilter._CSRF)); return "/admin/upload_result.html";
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/control/UserSettingsKtrl.java
UserSettingsKtrl
passwordSubmit
class UserSettingsKtrl extends BaseKontroller { private static final Logger log = LoggerFactory.getLogger(UserSettingsKtrl.class); public static final String REQUIRED = "Required"; @Model(name = "themeMap") static Map<String, String> themeMap1 = new LinkedHashMap<>(Map.ofEntries( entry("Tango", "#2e3436,#cc0000,#4e9a06,#c4a000,#3465a4,#75507b,#06989a,#d3d7cf,#555753,#ef2929,#8ae234,#fce94f,#729fcf,#ad7fa8,#34e2e2,#eeeeec"), entry("XTerm", "#000000,#cd0000,#00cd00,#cdcd00,#0000ee,#cd00cd,#00cdcd,#e5e5e5,#7f7f7f,#ff0000,#00ff00,#ffff00,#5c5cff,#ff00ff,#00ffff,#ffffff") )); @Model(name = "planeMap") static Map<String, String> planeMap1 = new LinkedHashMap<>(Map.ofEntries( entry("Black on light yellow", "#FFFFDD,#000000"), entry("Black on white", "#FFFFFF,#000000"), entry("Gray on black", "#000000,#AAAAAA"), entry("Green on black", "#000000,#00FF00"), entry("White on black", "#000000,#FFFFFF") )); @Model(name = "publicKey") static String publicKey; @Model(name = "auth") Auth auth; @Model(name = "userSettings") UserSettings userSettings; static { try { publicKey = PrivateKeyDB.getApplicationKey().getPublicKey(); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); } } public UserSettingsKtrl(HttpServletRequest request, HttpServletResponse response) { super(request, response); } @Kontrol(path = "/admin/userSettings", method = MethodType.GET) public String userSettings() throws ServletException { try { userSettings = UserThemeDB.getTheme(AuthUtil.getUserId(getRequest().getSession())); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return "/admin/user_settings.html"; } @Kontrol(path = "/admin/passwordSubmit", method = MethodType.POST) public String passwordSubmit() throws ServletException {<FILL_FUNCTION_BODY>} @Kontrol(path = "/admin/themeSubmit", method = MethodType.POST) public String themeSubmit() throws ServletException { userSettings.setTheme(userSettings.getTheme()); userSettings.setPlane(userSettings.getPlane()); try { UserThemeDB.saveTheme(AuthUtil.getUserId(getRequest().getSession()), userSettings); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return "redirect:/admin/menu.html"; } /** * Validates fields for password submit */ @Validate(input = "/admin/user_settings.html") public void validatePasswordSubmit() { if (auth.getPassword() == null || auth.getPassword().trim().equals("")) { addFieldError("auth.password", REQUIRED); } if (auth.getPasswordConfirm() == null || auth.getPasswordConfirm().trim().equals("")) { addFieldError("auth.passwordConfirm", REQUIRED); } if (auth.getPrevPassword() == null || auth.getPrevPassword().trim().equals("")) { addFieldError("auth.prevPassword", REQUIRED); } } }
String retVal = "/admin/user_settings.html"; if (!auth.getPassword().equals(auth.getPasswordConfirm())) { addError("Passwords do not match"); } else if (!PasswordUtil.isValid(auth.getPassword())) { addError(PasswordUtil.PASSWORD_REQ_ERROR_MSG); } else { try { auth.setAuthToken(AuthUtil.getAuthToken(getRequest().getSession())); if (AuthDB.updatePassword(auth)) { retVal = "redirect:/admin/menu.html"; } else { addError("Current password is invalid"); } } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } } return retVal;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/control/UsersKtrl.java
UsersKtrl
validateSaveUser
class UsersKtrl extends BaseKontroller { private static final Logger log = LoggerFactory.getLogger(UsersKtrl.class); public static final String REQUIRED = "Required"; @Model(name = "sortedSet") SortedSet sortedSet = new SortedSet(); @Model(name = "user") User user = new User(); @Model(name = "resetSharedSecret") Boolean resetSharedSecret = false; @Model(name = "userId") Long userId; public UsersKtrl(HttpServletRequest request, HttpServletResponse response) { super(request, response); } @Kontrol(path = "/manage/viewUsers", method = MethodType.GET) public String viewUsers() throws ServletException { try { userId = AuthUtil.getUserId(getRequest().getSession()); sortedSet = UserDB.getUserSet(sortedSet); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return "/manage/view_users.html"; } @Kontrol(path = "/manage/saveUser", method = MethodType.POST) public String saveUser() throws ServletException { String retVal = "redirect:/manage/viewUsers.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField(); try { if (user.getId() != null) { if (user.getPassword() == null || user.getPassword().trim().equals("")) { UserDB.updateUserNoCredentials(user); } else { UserDB.updateUserCredentials(user); } //check if reset is set if (resetSharedSecret) { UserDB.resetSharedSecret(user.getId()); } } else { UserDB.insertUser(user); } } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return retVal; } @Kontrol(path = "/manage/deleteUser", method = MethodType.GET) public String deleteUser() throws ServletException { try { if (user.getId() != null && !user.getId().equals(AuthUtil.getUserId(getRequest().getSession()))) { UserDB.deleteUser(user.getId()); PublicKeyDB.deleteUserPublicKeys(user.getId()); RefreshAuthKeyUtil.refreshAllSystems(); } } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return "redirect:/manage/viewUsers.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField(); } @Kontrol(path = "/manage/unlockUser", method = MethodType.GET) public String unlockUser() throws ServletException { try { if (user.getId() != null && !user.getId().equals(AuthUtil.getUserId(getRequest().getSession()))) { UserDB.unlockAccount(user.getId()); } } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); } return "redirect:/manage/viewUsers.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField(); } /** * Validates all fields for adding a user */ @Validate(input = "/manage/view_users.html") public void validateSaveUser() throws ServletException {<FILL_FUNCTION_BODY>} }
if (user == null || user.getUsername() == null || user.getUsername().trim().equals("")) { addFieldError("user.username", REQUIRED); } if (user == null || user.getLastNm() == null || user.getLastNm().trim().equals("")) { addFieldError("user.lastNm", REQUIRED); } if (user == null || user.getFirstNm() == null || user.getFirstNm().trim().equals("")) { addFieldError("user.firstNm", REQUIRED); } if (user != null && user.getPassword() != null && !user.getPassword().trim().equals("")) { if (!user.getPassword().equals(user.getPasswordConfirm())) { addError("Passwords do not match"); } else if (!PasswordUtil.isValid(user.getPassword())) { addError(PasswordUtil.PASSWORD_REQ_ERROR_MSG); } } if (user != null && user.getId() == null && !Auth.AUTH_EXTERNAL.equals(user.getAuthType()) && (user.getPassword() == null || user.getPassword().trim().equals(""))) { addError("Password is required"); } try { if (user != null && !UserDB.isUnique(user.getId(), user.getUsername())) { addError("Username has been taken"); } if (!this.getFieldErrors().isEmpty() || !this.getErrors().isEmpty()) { userId = AuthUtil.getUserId(getRequest().getSession()); sortedSet = UserDB.getUserSet(sortedSet); } } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new ServletException(ex.toString(), ex); }
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/db/PrivateKeyDB.java
PrivateKeyDB
getApplicationKey
class PrivateKeyDB { private PrivateKeyDB() { } /** * returns public private key for application * * @return app key values */ public static ApplicationKey getApplicationKey() throws SQLException, GeneralSecurityException {<FILL_FUNCTION_BODY>} }
ApplicationKey appKey = null; Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("select * from application_key"); ResultSet rs = stmt.executeQuery(); while (rs.next()) { appKey = new ApplicationKey(); appKey.setId(rs.getLong("id")); appKey.setPassphrase(EncryptionUtil.decrypt(rs.getString("passphrase"))); appKey.setPrivateKey(EncryptionUtil.decrypt(rs.getString("private_key"))); appKey.setPublicKey(rs.getString("public_key")); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); DBUtils.closeConn(con); return appKey;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/db/ProfileDB.java
ProfileDB
getProfileSet
class ProfileDB { public static final String FILTER_BY_SYSTEM = "system"; public static final String FILTER_BY_USER = "username"; public static final String SORT_BY_PROFILE_NM = "nm"; private ProfileDB() { } /** * method to do order by based on the sorted set object for profiles * * @return list of profiles */ public static SortedSet getProfileSet(SortedSet sortedSet) throws SQLException, GeneralSecurityException {<FILL_FUNCTION_BODY>} /** * returns all profile information * * @return list of profiles */ public static List<Profile> getAllProfiles() throws SQLException, GeneralSecurityException { ArrayList<Profile> profileList = new ArrayList<>(); Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("select * from profiles order by nm asc"); ResultSet rs = stmt.executeQuery(); while (rs.next()) { Profile profile = new Profile(); profile.setId(rs.getLong("id")); profile.setNm(rs.getString("nm")); profile.setDesc(rs.getString("desc")); profileList.add(profile); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); DBUtils.closeConn(con); return profileList; } /** * returns profile based on id * * @param profileId profile id * @return profile */ public static Profile getProfile(Long profileId) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); Profile profile = getProfile(con, profileId); DBUtils.closeConn(con); return profile; } /** * returns profile based on id * * @param con db connection object * @param profileId profile id * @return profile */ public static Profile getProfile(Connection con, Long profileId) throws SQLException { Profile profile = null; PreparedStatement stmt = con.prepareStatement("select * from profiles where id=?"); stmt.setLong(1, profileId); ResultSet rs = stmt.executeQuery(); while (rs.next()) { profile = new Profile(); profile.setId(rs.getLong("id")); profile.setNm(rs.getString("nm")); profile.setDesc(rs.getString("desc")); profile.setHostSystemList(ProfileSystemsDB.getSystemsByProfile(con, profileId)); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); return profile; } /** * inserts new profile * * @param profile profile object */ public static void insertProfile(Profile profile) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("insert into profiles (nm, desc) values (?,?)"); stmt.setString(1, profile.getNm()); stmt.setString(2, profile.getDesc()); stmt.execute(); DBUtils.closeStmt(stmt); DBUtils.closeConn(con); } /** * updates profile * * @param profile profile object */ public static void updateProfile(Profile profile) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("update profiles set nm=?, desc=? where id=?"); stmt.setString(1, profile.getNm()); stmt.setString(2, profile.getDesc()); stmt.setLong(3, profile.getId()); stmt.execute(); DBUtils.closeStmt(stmt); DBUtils.closeConn(con); } /** * deletes profile * * @param profileId profile id */ public static void deleteProfile(Long profileId) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("delete from profiles where id=?"); stmt.setLong(1, profileId); stmt.execute(); DBUtils.closeStmt(stmt); DBUtils.closeConn(con); } }
ArrayList<Profile> profileList = new ArrayList<>(); String orderBy = ""; if (sortedSet.getOrderByField() != null && !sortedSet.getOrderByField().trim().equals("")) { orderBy = " order by " + sortedSet.getOrderByField() + " " + sortedSet.getOrderByDirection(); } String sql = "select distinct p.* from profiles p "; if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_SYSTEM))) { sql = sql + ", system_map m, system s where m.profile_id = p.id and m.system_id = s.id" + " and (lower(s.display_nm) like ? or lower(s.host) like ?)"; } else if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_USER))) { sql = sql + ", user_map m, users u where m.profile_id = p.id and m.user_id = u.id" + " and (lower(u.first_nm) like ? or lower(u.last_nm) like ?" + " or lower(u.email) like ? or lower(u.username) like ?)"; } sql = sql + orderBy; Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement(sql); if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_SYSTEM))) { stmt.setString(1, "%" + sortedSet.getFilterMap().get(FILTER_BY_SYSTEM).toLowerCase() + "%"); stmt.setString(2, "%" + sortedSet.getFilterMap().get(FILTER_BY_SYSTEM).toLowerCase() + "%"); } else if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_USER))) { stmt.setString(1, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%"); stmt.setString(2, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%"); stmt.setString(3, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%"); stmt.setString(4, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%"); } ResultSet rs = stmt.executeQuery(); while (rs.next()) { Profile profile = new Profile(); profile.setId(rs.getLong("id")); profile.setNm(rs.getString("nm")); profile.setDesc(rs.getString("desc")); profileList.add(profile); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); DBUtils.closeConn(con); sortedSet.setItemList(profileList); return sortedSet;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/db/ProfileSystemsDB.java
ProfileSystemsDB
getSystemIdsByProfile
class ProfileSystemsDB { private ProfileSystemsDB() { } /** * sets host systems for profile * * @param profileId profile id * @param systemIdList list of host system ids */ public static void setSystemsForProfile(Long profileId, List<Long> systemIdList) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("delete from system_map where profile_id=?"); stmt.setLong(1, profileId); stmt.execute(); DBUtils.closeStmt(stmt); for (Long systemId : systemIdList) { stmt = con.prepareStatement("insert into system_map (profile_id, system_id) values (?,?)"); stmt.setLong(1, profileId); stmt.setLong(2, systemId); stmt.execute(); DBUtils.closeStmt(stmt); } DBUtils.closeConn(con); } /** * returns a list of systems for a given profile * * @param con DB connection * @param profileId profile id * @return list of host systems */ public static List<HostSystem> getSystemsByProfile(Connection con, Long profileId) throws SQLException { List<HostSystem> hostSystemList = new ArrayList<>(); PreparedStatement stmt = con.prepareStatement("select * from system s, system_map m where s.id=m.system_id and m.profile_id=? order by display_nm asc"); stmt.setLong(1, profileId); ResultSet rs = stmt.executeQuery(); while (rs.next()) { HostSystem hostSystem = new HostSystem(); hostSystem.setId(rs.getLong("id")); hostSystem.setDisplayNm(rs.getString("display_nm")); hostSystem.setUser(rs.getString("username")); hostSystem.setHost(rs.getString("host")); hostSystem.setPort(rs.getInt("port")); hostSystem.setAuthorizedKeys(rs.getString("authorized_keys")); hostSystemList.add(hostSystem); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); return hostSystemList; } /** * returns a list of systems for a given profile * * @param profileId profile id * @return list of host systems */ public static List<HostSystem> getSystemsByProfile(Long profileId) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); List<HostSystem> hostSystemList = getSystemsByProfile(con, profileId); DBUtils.closeConn(con); return hostSystemList; } /** * returns a list of system ids for a given profile * * @param con DB con * @param profileId profile id * @return list of host systems */ public static List<Long> getSystemIdsByProfile(Connection con, Long profileId) throws SQLException {<FILL_FUNCTION_BODY>} /** * returns a list of system ids for a given profile * * @param profileId profile id * @return list of host systems */ public static List<Long> getSystemIdsByProfile(Long profileId) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); List<Long> systemIdList = getSystemIdsByProfile(con, profileId); DBUtils.closeConn(con); return systemIdList; } /** * returns a list of system ids for a given profile * * @param con DB con * @param profileId profile id * @param userId user id * @return list of host systems */ public static List<Long> getSystemIdsByProfile(Connection con, Long profileId, Long userId) throws SQLException { List<Long> systemIdList = new ArrayList<>(); PreparedStatement stmt = con.prepareStatement("select sm.system_id from system_map sm, user_map um where um.profile_id=sm.profile_id and sm.profile_id=? and um.user_id=?"); stmt.setLong(1, profileId); stmt.setLong(2, userId); ResultSet rs = stmt.executeQuery(); while (rs.next()) { systemIdList.add(rs.getLong("system_id")); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); return systemIdList; } /** * returns a list of system ids for a given profile * * @param profileId profile id * @param userId user id * @return list of host systems */ public static List<Long> getSystemIdsByProfile(Long profileId, Long userId) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); List<Long> systemIdList = getSystemIdsByProfile(con, profileId, userId); DBUtils.closeConn(con); return systemIdList; } }
List<Long> systemIdList = new ArrayList<>(); PreparedStatement stmt = con.prepareStatement("select * from system s, system_map m where s.id=m.system_id and m.profile_id=? order by display_nm asc"); stmt.setLong(1, profileId); ResultSet rs = stmt.executeQuery(); while (rs.next()) { systemIdList.add(rs.getLong("id")); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); return systemIdList;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/db/ScriptDB.java
ScriptDB
getScript
class ScriptDB { public static final String DISPLAY_NM = "display_nm"; public static final String SORT_BY_DISPLAY_NM = DISPLAY_NM; private ScriptDB() { } /** * returns scripts based on sort order defined * * @param sortedSet object that defines sort order * @param userId user id * @return sorted script list */ public static SortedSet getScriptSet(SortedSet sortedSet, Long userId) throws SQLException, GeneralSecurityException { ArrayList<Script> scriptList = new ArrayList<>(); String orderBy = ""; if (sortedSet.getOrderByField() != null && !sortedSet.getOrderByField().trim().equals("")) { orderBy = "order by " + sortedSet.getOrderByField() + " " + sortedSet.getOrderByDirection(); } String sql = "select * from scripts where user_id=? " + orderBy; Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement(sql); stmt.setLong(1, userId); ResultSet rs = stmt.executeQuery(); while (rs.next()) { Script script = new Script(); script.setId(rs.getLong("id")); script.setDisplayNm(rs.getString(DISPLAY_NM)); script.setScript(rs.getString("script")); scriptList.add(script); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); DBUtils.closeConn(con); sortedSet.setItemList(scriptList); return sortedSet; } /** * returns script base on id * * @param scriptId script id * @param userId user id * @return script object */ public static Script getScript(Long scriptId, Long userId) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); Script script = getScript(con, scriptId, userId); DBUtils.closeConn(con); return script; } /** * returns script base on id * * @param con DB connection * @param scriptId script id * @param userId user id * @return script object */ public static Script getScript(Connection con, Long scriptId, Long userId) throws SQLException {<FILL_FUNCTION_BODY>} /** * inserts new script * * @param script script object * @param userId user id */ public static void insertScript(Script script, Long userId) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("insert into scripts (display_nm, script, user_id) values (?,?,?)"); stmt.setString(1, script.getDisplayNm()); stmt.setString(2, script.getScript()); stmt.setLong(3, userId); stmt.execute(); DBUtils.closeStmt(stmt); DBUtils.closeConn(con); } /** * updates existing script * * @param script script object * @param userId user id */ public static void updateScript(Script script, Long userId) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("update scripts set display_nm=?, script=? where id=? and user_id=?"); stmt.setString(1, script.getDisplayNm()); stmt.setString(2, script.getScript()); stmt.setLong(3, script.getId()); stmt.setLong(4, userId); stmt.execute(); DBUtils.closeStmt(stmt); DBUtils.closeConn(con); } /** * deletes script * * @param scriptId script id * @param userId user id */ public static void deleteScript(Long scriptId, Long userId) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("delete from scripts where id=? and user_id=?"); stmt.setLong(1, scriptId); stmt.setLong(2, userId); stmt.execute(); DBUtils.closeStmt(stmt); DBUtils.closeConn(con); } }
Script script = null; PreparedStatement stmt = con.prepareStatement("select * from scripts where id=? and user_id=?"); stmt.setLong(1, scriptId); stmt.setLong(2, userId); ResultSet rs = stmt.executeQuery(); while (rs.next()) { script = new Script(); script.setId(rs.getLong("id")); script.setDisplayNm(rs.getString(DISPLAY_NM)); script.setScript(rs.getString("script")); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); return script;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/db/SystemStatusDB.java
SystemStatusDB
getNextPendingSystem
class SystemStatusDB { public static final String STATUS_CD = "status_cd"; private SystemStatusDB() { } /** * set the initial status for selected systems * * @param systemSelectIds systems ids to set initial status * @param userId user id * @param userType user type */ public static void setInitialSystemStatus(List<Long> systemSelectIds, Long userId, String userType) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); //checks perms if to see if in assigned profiles if (!Auth.MANAGER.equals(userType)) { systemSelectIds = SystemDB.checkSystemPerms(con, systemSelectIds, userId); } //deletes all old systems deleteAllSystemStatus(con, userId); for (Long hostSystemId : systemSelectIds) { HostSystem hostSystem = new HostSystem(); hostSystem.setId(hostSystemId); hostSystem.setStatusCd(HostSystem.INITIAL_STATUS); //insert new status insertSystemStatus(con, hostSystem, userId); } DBUtils.closeConn(con); } /** * deletes all records from status table for user * * @param con DB connection object * @param userId user id */ private static void deleteAllSystemStatus(Connection con, Long userId) throws SQLException { PreparedStatement stmt = con.prepareStatement("delete from status where user_id=?"); stmt.setLong(1, userId); stmt.execute(); DBUtils.closeStmt(stmt); } /** * inserts into the status table to keep track of key placement status * * @param con DB connection object * @param hostSystem systems for authorized_keys replacement * @param userId user id */ private static void insertSystemStatus(Connection con, HostSystem hostSystem, Long userId) throws SQLException { PreparedStatement stmt = con.prepareStatement("insert into status (id, status_cd, user_id) values (?,?,?)"); stmt.setLong(1, hostSystem.getId()); stmt.setString(2, hostSystem.getStatusCd()); stmt.setLong(3, userId); stmt.execute(); DBUtils.closeStmt(stmt); } /** * updates the status table to keep track of key placement status * * @param hostSystem systems for authorized_keys replacement * @param userId user id */ public static void updateSystemStatus(HostSystem hostSystem, Long userId) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); updateSystemStatus(con, hostSystem, userId); DBUtils.closeConn(con); } /** * updates the status table to keep track of key placement status * * @param con DB connection * @param hostSystem systems for authorized_keys replacement * @param userId user id */ public static void updateSystemStatus(Connection con, HostSystem hostSystem, Long userId) throws SQLException { PreparedStatement stmt = con.prepareStatement("update status set status_cd=? where id=? and user_id=?"); stmt.setString(1, hostSystem.getStatusCd()); stmt.setLong(2, hostSystem.getId()); stmt.setLong(3, userId); stmt.execute(); DBUtils.closeStmt(stmt); } /** * returns all key placement statuses * * @param userId user id */ public static SortedSet getSortedSetStatus(Long userId) throws SQLException, GeneralSecurityException { SortedSet sortedSet = new SortedSet(); sortedSet.setItemList(getAllSystemStatus(userId)); return sortedSet; } /** * returns all key placement statuses * * @param userId user id */ public static List<HostSystem> getAllSystemStatus(Long userId) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); List<HostSystem> hostSystemList = getAllSystemStatus(con, userId); DBUtils.closeConn(con); return hostSystemList; } /** * returns all key placement statuses * * @param con DB connection object * @param userId user id */ private static List<HostSystem> getAllSystemStatus(Connection con, Long userId) throws SQLException { List<HostSystem> hostSystemList = new ArrayList<>(); PreparedStatement stmt = con.prepareStatement("select * from status where user_id=? order by id asc"); stmt.setLong(1, userId); ResultSet rs = stmt.executeQuery(); while (rs.next()) { HostSystem hostSystem = SystemDB.getSystem(con, rs.getLong("id")); hostSystem.setStatusCd(rs.getString(STATUS_CD)); hostSystemList.add(hostSystem); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); return hostSystemList; } /** * returns key placement status of system * * @param systemId system id * @param userId user id */ public static HostSystem getSystemStatus(Long systemId, Long userId) throws SQLException, GeneralSecurityException { HostSystem hostSystem = null; Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("select * from status where id=? and user_id=?"); stmt.setLong(1, systemId); stmt.setLong(2, userId); ResultSet rs = stmt.executeQuery(); while (rs.next()) { hostSystem = SystemDB.getSystem(con, rs.getLong("id")); hostSystem.setStatusCd(rs.getString(STATUS_CD)); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); DBUtils.closeConn(con); return hostSystem; } /** * returns the first system that authorized keys has not been tried * * @param userId user id * @return hostSystem systems for authorized_keys replacement */ public static HostSystem getNextPendingSystem(Long userId) throws SQLException, GeneralSecurityException {<FILL_FUNCTION_BODY>} }
HostSystem hostSystem = null; Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("select * from status where (status_cd like ? or status_cd like ? or status_cd like ?) and user_id=? order by id asc"); stmt.setString(1, HostSystem.INITIAL_STATUS); stmt.setString(2, HostSystem.AUTH_FAIL_STATUS); stmt.setString(3, HostSystem.PUBLIC_KEY_FAIL_STATUS); stmt.setLong(4, userId); ResultSet rs = stmt.executeQuery(); if (rs.next()) { hostSystem = SystemDB.getSystem(con, rs.getLong("id")); hostSystem.setStatusCd(rs.getString(STATUS_CD)); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); DBUtils.closeConn(con); return hostSystem;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/db/UserProfileDB.java
UserProfileDB
checkIsUsersProfile
class UserProfileDB { private UserProfileDB() { } /** * sets users for profile * * @param profileId profile id * @param userIdList list of user ids */ public static void setUsersForProfile(Long profileId, List<Long> userIdList) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("delete from user_map where profile_id=?"); stmt.setLong(1, profileId); stmt.execute(); DBUtils.closeStmt(stmt); for (Long userId : userIdList) { stmt = con.prepareStatement("insert into user_map (profile_id, user_id) values (?,?)"); stmt.setLong(1, profileId); stmt.setLong(2, userId); stmt.execute(); DBUtils.closeStmt(stmt); } //delete all unassigned keys by profile PublicKeyDB.deleteUnassignedKeysByProfile(con, profileId); DBUtils.closeConn(con); } /** * return a list of profiles for user * * @param userId user id * @return profile list */ public static List<Profile> getProfilesByUser(Long userId) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); List<Profile> profileList = getProfilesByUser(con, userId); DBUtils.closeConn(con); return profileList; } /** * return a list of profiles for user * * @param userId user id * @return profile list */ public static List<Profile> getProfilesByUser(Connection con, Long userId) throws SQLException { ArrayList<Profile> profileList = new ArrayList<>(); PreparedStatement stmt = con.prepareStatement("select * from profiles g, user_map m where g.id=m.profile_id and m.user_id=? order by nm asc"); stmt.setLong(1, userId); ResultSet rs = stmt.executeQuery(); while (rs.next()) { Profile profile = new Profile(); profile.setId(rs.getLong("id")); profile.setNm(rs.getString("nm")); profile.setDesc(rs.getString("desc")); profileList.add(profile); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); return profileList; } /** * checks to determine if user belongs to profile * * @param userId user id * @param profileId profile id * @return true if user belongs to profile */ public static boolean checkIsUsersProfile(Long userId, Long profileId) throws SQLException, GeneralSecurityException {<FILL_FUNCTION_BODY>} /** * assigns profiles to given user * * @param userId user id * @param allProfilesNmList list of all profiles * @param assignedProfilesNmList list of assigned profiles */ public static void assignProfilesToUser(Connection con, Long userId, List<String> allProfilesNmList, List<String> assignedProfilesNmList) throws SQLException { for (String profileNm : allProfilesNmList) { if (StringUtils.isNotEmpty(profileNm)) { Long profileId = null; PreparedStatement stmt = con.prepareStatement("select id from profiles p where lower(p.nm) like ?"); stmt.setString(1, profileNm.toLowerCase()); ResultSet rs = stmt.executeQuery(); while (rs.next()) { profileId = rs.getLong("id"); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); if (profileId != null) { stmt = con.prepareStatement("delete from user_map where profile_id=?"); stmt.setLong(1, profileId); stmt.execute(); DBUtils.closeStmt(stmt); if (assignedProfilesNmList.contains(profileNm)) { stmt = con.prepareStatement("insert into user_map (profile_id, user_id) values (?,?)"); stmt.setLong(1, profileId); stmt.setLong(2, userId); stmt.execute(); DBUtils.closeStmt(stmt); } //delete all unassigned keys by profile PublicKeyDB.deleteUnassignedKeysByProfile(con, profileId); } } } } /** * assigns profiles to given user * * @param userId user id * @param profileNm profile name */ public static void assignProfileToUser(Connection con, Long userId, String profileNm) throws SQLException { if (StringUtils.isNotEmpty(profileNm)) { Long profileId = null; PreparedStatement stmt = con.prepareStatement("select id from profiles p where lower(p.nm) like ?"); stmt.setString(1, profileNm.toLowerCase()); ResultSet rs = stmt.executeQuery(); while (rs.next()) { profileId = rs.getLong("id"); } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); if (profileId != null) { stmt = con.prepareStatement("delete from user_map where profile_id=?"); stmt.setLong(1, profileId); stmt.execute(); DBUtils.closeStmt(stmt); stmt = con.prepareStatement("insert into user_map (profile_id, user_id) values (?,?)"); stmt.setLong(1, profileId); stmt.setLong(2, userId); stmt.execute(); DBUtils.closeStmt(stmt); //delete all unassigned keys by profile PublicKeyDB.deleteUnassignedKeysByProfile(con, profileId); } } } }
boolean isUsersProfile = false; Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("select * from user_map where profile_id=? and user_id=?"); stmt.setLong(1, profileId); stmt.setLong(2, userId); ResultSet rs = stmt.executeQuery(); while (rs.next()) { isUsersProfile = true; } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); DBUtils.closeConn(con); return isUsersProfile;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/db/UserThemeDB.java
UserThemeDB
getTheme
class UserThemeDB { private UserThemeDB() { } /** * get user theme * * @param userId object * @return user theme object */ public static UserSettings getTheme(Long userId) throws SQLException, GeneralSecurityException {<FILL_FUNCTION_BODY>} /** * saves user theme * * @param userId object */ public static void saveTheme(Long userId, UserSettings theme) throws SQLException, GeneralSecurityException { Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("delete from user_theme where user_id=?"); stmt.setLong(1, userId); stmt.execute(); DBUtils.closeStmt(stmt); if (StringUtils.isNotEmpty(theme.getPlane()) || StringUtils.isNotEmpty(theme.getTheme())) { stmt = con.prepareStatement("insert into user_theme(user_id, bg, fg, d1, d2, d3, d4, d5, d6, d7, d8, b1, b2, b3, b4, b5, b6, b7, b8) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); stmt.setLong(1, userId); stmt.setString(2, theme.getBg()); stmt.setString(3, theme.getFg()); //if contains all 16 theme colors insert if (theme.getColors() != null && theme.getColors().length == 16) { for (int i = 0; i < 16; i++) { stmt.setString(i + 4, theme.getColors()[i]); } //else set to null } else { for (int i = 0; i < 16; i++) { stmt.setString(i + 4, null); } } stmt.execute(); DBUtils.closeStmt(stmt); } DBUtils.closeConn(con); } }
UserSettings theme = null; Connection con = DBUtils.getConn(); PreparedStatement stmt = con.prepareStatement("select * from user_theme where user_id=?"); stmt.setLong(1, userId); ResultSet rs = stmt.executeQuery(); if (rs.next()) { theme = new UserSettings(); theme.setBg(rs.getString("bg")); theme.setFg(rs.getString("fg")); if (StringUtils.isNotEmpty(rs.getString("d1"))) { String[] colors = new String[16]; colors[0] = rs.getString("d1"); colors[1] = rs.getString("d2"); colors[2] = rs.getString("d3"); colors[3] = rs.getString("d4"); colors[4] = rs.getString("d5"); colors[5] = rs.getString("d6"); colors[6] = rs.getString("d7"); colors[7] = rs.getString("d8"); colors[8] = rs.getString("b1"); colors[9] = rs.getString("b2"); colors[10] = rs.getString("b3"); colors[11] = rs.getString("b4"); colors[12] = rs.getString("b5"); colors[13] = rs.getString("b6"); colors[14] = rs.getString("b7"); colors[15] = rs.getString("b8"); theme.setColors(colors); } } DBUtils.closeRs(rs); DBUtils.closeStmt(stmt); DBUtils.closeConn(con); return theme;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/model/SortedSet.java
SortedSet
getOrderByField
class SortedSet { private String orderByField = null; private String orderByDirection = "asc"; private List itemList; private Map<String, String> filterMap = new HashMap<>(); public SortedSet() { } public SortedSet(String orderByField) { this.orderByField = orderByField; } public String getOrderByField() {<FILL_FUNCTION_BODY>} public void setOrderByField(String orderByField) { this.orderByField = orderByField; } public String getOrderByDirection() { if ("asc".equalsIgnoreCase(orderByDirection)) { return "asc"; } else { return "desc"; } } public void setOrderByDirection(String orderByDirection) { this.orderByDirection = orderByDirection; } public List getItemList() { return itemList; } public void setItemList(List itemList) { this.itemList = itemList; } public Map<String, String> getFilterMap() { return filterMap; } public void setFilterMap(Map<String, String> filterMap) { this.filterMap = filterMap; } }
if (orderByField != null) { return orderByField.replaceAll("[^0-9,a-z,A-Z,\\_,\\.]", ""); } return null;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/model/UserSettings.java
UserSettings
setPlane
class UserSettings { String[] colors = null; String bg; String fg; String plane; String theme; Integer ptyWidth; Integer ptyHeight; public String[] getColors() { return colors; } public void setColors(String[] colors) { this.colors = colors; } public String getBg() { return bg; } public void setBg(String bg) { this.bg = bg; } public String getFg() { return fg; } public void setFg(String fg) { this.fg = fg; } public String getPlane() { if (StringUtils.isNotEmpty(bg) && StringUtils.isNotEmpty(fg)) { plane = bg + "," + fg; } return plane; } public void setPlane(String plane) {<FILL_FUNCTION_BODY>} public String getTheme() { if (this.colors != null && this.colors.length == 16) { theme = StringUtils.join(this.colors, ","); } return theme; } public void setTheme(String theme) { if (StringUtils.isNotEmpty(theme) && theme.split(",").length == 16) { this.setColors(theme.split(",")); } this.theme = theme; } public Integer getPtyWidth() { return ptyWidth; } public void setPtyWidth(Integer ptyWidth) { this.ptyWidth = ptyWidth; } public Integer getPtyHeight() { return ptyHeight; } public void setPtyHeight(Integer ptyHeight) { this.ptyHeight = ptyHeight; } }
if (StringUtils.isNotEmpty(plane) && plane.split(",").length == 2) { this.setBg(plane.split(",")[0]); this.setFg(plane.split(",")[1]); } this.plane = plane;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/task/SecureShellTask.java
SecureShellTask
run
class SecureShellTask implements Runnable { private static final Logger log = LoggerFactory.getLogger(SecureShellTask.class); InputStream outFromChannel; SessionOutput sessionOutput; public SecureShellTask(SessionOutput sessionOutput, InputStream outFromChannel) { this.sessionOutput = sessionOutput; this.outFromChannel = outFromChannel; } public void run() {<FILL_FUNCTION_BODY>} }
InputStreamReader isr = new InputStreamReader(outFromChannel); BufferedReader br = new BufferedReader(isr); SessionOutputUtil.addOutput(sessionOutput); char[] buff = new char[1024]; int read; try { while ((read = br.read(buff)) != -1) { SessionOutputUtil.addToOutput(sessionOutput.getSessionId(), sessionOutput.getInstanceId(), buff, 0, read); Thread.sleep(50); } SessionOutputUtil.removeOutput(sessionOutput.getSessionId(), sessionOutput.getInstanceId()); } catch (IOException | InterruptedException ex) { log.error(ex.toString(), ex); }
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/task/SentOutputTask.java
SentOutputTask
run
class SentOutputTask implements Runnable { private static final Logger log = LoggerFactory.getLogger(SentOutputTask.class); Session session; Long sessionId; User user; public SentOutputTask(Long sessionId, Session session, User user) { this.sessionId = sessionId; this.session = session; this.user = user; } public void run() {<FILL_FUNCTION_BODY>} }
Gson gson = new Gson(); while (session.isOpen()) { try { Connection con = DBUtils.getConn(); List<SessionOutput> outputList = SessionOutputUtil.getOutput(con, sessionId, user); if (!outputList.isEmpty()) { String json = gson.toJson(outputList); //send json to session this.session.getBasicRemote().sendText(json); } Thread.sleep(25); DBUtils.closeConn(con); } catch (SQLException | GeneralSecurityException | IOException | InterruptedException ex) { log.error(ex.toString(), ex); } }
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/util/DSPool.java
DSPool
registerDataSource
class DSPool { private static BasicDataSource dsPool = null; private static final String BASE_DIR = AppConfig.CONFIG_DIR; private static final String DB_DRIVER = AppConfig.getProperty("dbDriver"); private static final int MAX_ACTIVE = Integer.parseInt(AppConfig.getProperty("maxActive")); private static final boolean TEST_ON_BORROW = Boolean.parseBoolean(AppConfig.getProperty("testOnBorrow")); private static final int MIN_IDLE = Integer.parseInt(AppConfig.getProperty("minIdle")); private static final int MAX_WAIT = Integer.parseInt(AppConfig.getProperty("maxWait")); private DSPool() { } /** * fetches the data source for H2 db * * @return data source pool */ public static BasicDataSource getDataSource() throws GeneralSecurityException { if (dsPool == null) { dsPool = registerDataSource(); } return dsPool; } /** * register the data source for H2 DB * * @return pooling database object */ private static BasicDataSource registerDataSource() throws GeneralSecurityException {<FILL_FUNCTION_BODY>} }
System.setProperty("h2.baseDir", BASE_DIR); // create a database connection String user = AppConfig.getProperty("dbUser"); String password = AppConfig.decryptProperty("dbPassword"); String connectionURL = AppConfig.getProperty("dbConnectionURL"); if (connectionURL != null && connectionURL.contains("CIPHER=")) { password = "filepwd " + password; } String validationQuery = "select 1"; BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(DB_DRIVER); dataSource.setMaxTotal(MAX_ACTIVE); dataSource.setTestOnBorrow(TEST_ON_BORROW); dataSource.setMinIdle(MIN_IDLE); dataSource.setMaxWaitMillis(MAX_WAIT); dataSource.setValidationQuery(validationQuery); dataSource.setUsername(user); dataSource.setPassword(password); dataSource.setUrl(connectionURL); return dataSource;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/util/EncryptionUtil.java
EncryptionUtil
encrypt
class EncryptionUtil { private static final Logger log = LoggerFactory.getLogger(EncryptionUtil.class); //secret key private static byte[] key = new byte[0]; static { try { key = KeyStoreUtil.getSecretBytes(KeyStoreUtil.ENCRYPTION_KEY_ALIAS); } catch (GeneralSecurityException ex) { log.error(ex.toString(), ex); } } public static final String CRYPT_ALGORITHM = "AES"; public static final String HASH_ALGORITHM = "SHA-256"; private EncryptionUtil() { } /** * generate salt for hash * * @return salt */ public static String generateSalt() { byte[] salt = new byte[32]; SecureRandom secureRandom = new SecureRandom(); secureRandom.nextBytes(salt); return new String(Base64.encodeBase64(salt)); } /** * return hash value of string * * @param str unhashed string * @param salt salt for hash * @return hash value of string */ public static String hash(String str, String salt) throws NoSuchAlgorithmException { String hash = null; MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); if (StringUtils.isNotEmpty(salt)) { md.update(Base64.decodeBase64(salt.getBytes())); } md.update(str.getBytes(StandardCharsets.UTF_8)); hash = new String(Base64.encodeBase64(md.digest())); return hash; } /** * return hash value of string * * @param str unhashed string * @return hash value of string */ public static String hash(String str) throws NoSuchAlgorithmException { return hash(str, null); } /** * return encrypted value of string * * @param key secret key * @param str unencrypted string * @return encrypted string */ public static String encrypt(byte[] key, String str) throws GeneralSecurityException {<FILL_FUNCTION_BODY>} /** * return decrypted value of encrypted string * * @param key secret key * @param str encrypted string * @return decrypted string */ public static String decrypt(byte[] key, String str) throws GeneralSecurityException { String retVal = null; if (str != null && str.length() > 0) { Cipher c = Cipher.getInstance(CRYPT_ALGORITHM); c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, CRYPT_ALGORITHM)); byte[] decodedVal = Base64.decodeBase64(str.getBytes()); retVal = new String(c.doFinal(decodedVal)); } return retVal; } /** * return encrypted value of string * * @param str unencrypted string * @return encrypted string */ public static String encrypt(String str) throws GeneralSecurityException { return encrypt(key, str); } /** * return decrypted value of encrypted string * * @param str encrypted string * @return decrypted string */ public static String decrypt(String str) throws GeneralSecurityException { return decrypt(key, str); } }
String retVal = null; if (str != null && str.length() > 0) { Cipher c = Cipher.getInstance(CRYPT_ALGORITHM); c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, CRYPT_ALGORITHM)); byte[] encVal = c.doFinal(str.getBytes()); retVal = new String(Base64.encodeBase64(encVal)); } return retVal;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/util/KeyStoreUtil.java
KeyStoreUtil
initializeKeyStore
class KeyStoreUtil { private static final Logger log = LoggerFactory.getLogger(KeyStoreUtil.class); private static KeyStore keyStore = null; private static final String keyStoreFile = AppConfig.CONFIG_DIR + "/bastillion.jceks"; private static final char[] KEYSTORE_PASS = new char[]{ 'G', '~', 'r', 'x', 'Z', 'E', 'w', 'f', 'a', '[', '!', 'f', 'Z', 'd', '*', 'L', '8', 'm', 'h', 'u', '#', 'j', '9', ':', '~', ';', 'U', '>', 'O', 'i', '8', 'r', 'C', '}', 'f', 't', '%', '[', 'H', 'h', 'M', '&', 'K', ':', 'l', '5', 'c', 'H', '6', 'r', 'A', 'E', '.', 'F', 'Y', 'W', '}', '{', '*', '8', 'd', 'E', 'C', 'A', '6', 'F', 'm', 'j', 'u', 'A', 'Q', '%', '{', '/', '@', 'm', '&', '5', 'S', 'q', '4', 'Q', '+', 'Y', '|', 'X', 'W', 'z', '8', '<', 'j', 'd', 'a', '}', '`', '0', 'N', 'B', '3', 'i', 'v', '5', 'U', ' ', '2', 'd', 'd', '(', '&', 'J', '_', '9', 'o', '(', '2', 'I', '`', ';', '>', '#', '$', 'X', 'j', '&', '&', '%', '>', '#', '7', 'q', '>', ')', 'L', 'A', 'v', 'h', 'j', 'i', '8', '~', ')', 'a', '~', 'W', '/', 'l', 'H', 'L', 'R', '+', '\\', 'i', 'R', '_', '+', 'y', 's', '0', 'n', '\'', '=', '{', 'B', ':', 'l', '1', '%', '^', 'd', 'n', 'H', 'X', 'B', '$', 'f', '"', '#', ')', '{', 'L', '/', 'q', '\'', 'O', '%', 's', 'M', 'Q', ']', 'D', 'v', ';', 'L', 'C', 'd', '?', 'D', 'l', 'h', 'd', 'i', 'N', '4', 'R', '>', 'O', ';', '$', '(', '4', '-', '0', '^', 'Y', ')', '5', 'V', 'M', '7', 'S', 'a', 'c', 'D', 'C', 'w', 'A', 'o', 'n', 's', 'r', '*', 'G', '[', 'l', 'h', '$', 'U', 's', '_', 'D', 'f', 'X', '~', '.', '7', 'B', 'A', 'E', '(', '#', ']', ':', '`', ',', 'k', 'y'}; private static final int KEYLENGTH = 256; //Alias for encryption keystore public static final String ENCRYPTION_KEY_ALIAS = "KEYBOX-ENCRYPTION_KEY"; static { File f = new File(keyStoreFile); //load or create keystore try { if (f.isFile() && f.canRead()) { keyStore = KeyStore.getInstance("JCEKS"); FileInputStream keyStoreInputStream = new FileInputStream(f); keyStore.load(keyStoreInputStream, KEYSTORE_PASS); } //create keystore else { initializeKeyStore(); } } catch (IOException | GeneralSecurityException ex) { log.error(ex.toString(), ex); } } /** * get secret entry for alias * * @param alias keystore secret alias * @return secret byte array */ public static byte[] getSecretBytes(String alias) throws GeneralSecurityException { KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(KEYSTORE_PASS)); return entry.getSecretKey().getEncoded(); } /** * get secret entry for alias * * @param alias keystore secret alias * @return secret string */ public static String getSecretString(String alias) throws GeneralSecurityException { KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(KEYSTORE_PASS)); return new String(entry.getSecretKey().getEncoded()); } /** * set secret in keystore * * @param alias keystore secret alias * @param secret keystore entry */ public static void setSecret(String alias, byte[] secret) throws KeyStoreException { KeyStore.ProtectionParameter protectionParameter = new KeyStore.PasswordProtection(KEYSTORE_PASS); SecretKeySpec secretKey = new SecretKeySpec(secret, 0, secret.length, "AES"); KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey); keyStore.setEntry(alias, secretKeyEntry, protectionParameter); } /** * set secret in keystore * * @param alias keystore secret alias * @param secret keystore entry */ public static void setSecret(String alias, String secret) throws KeyStoreException { setSecret(alias, secret.getBytes()); } /** * delete existing and create new keystore */ public static void resetKeyStore() throws IOException, GeneralSecurityException { File file = new File(keyStoreFile); if (file.exists()) { FileUtils.forceDelete(file); } //create new keystore initializeKeyStore(); } /** * create new keystore */ private static void initializeKeyStore() throws GeneralSecurityException, IOException {<FILL_FUNCTION_BODY>} }
keyStore = KeyStore.getInstance("JCEKS"); //create keystore keyStore.load(null, KEYSTORE_PASS); //set encryption key KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(KEYLENGTH); KeyStoreUtil.setSecret(KeyStoreUtil.ENCRYPTION_KEY_ALIAS, keyGenerator.generateKey().getEncoded()); //write keystore FileOutputStream fos = new FileOutputStream(keyStoreFile); keyStore.store(fos, KEYSTORE_PASS); fos.close();
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/util/OTPUtil.java
OTPUtil
verifyToken
class OTPUtil { private static final Logger log = LoggerFactory.getLogger(OTPUtil.class); //sizes to generate OTP secret private static final int SECRET_SIZE = 10; private static final int NUM_SCRATCH_CODES = 5; private static final int SCRATCH_CODE_SIZE = 4; //token window in near future or past private static final int TOKEN_WINDOW = 3; //interval for validation token change private static final int CHANGE_INTERVAL = 30; private OTPUtil() { } /** * generates OPT secret * * @return String shared secret */ public static String generateSecret() { byte[] buffer = new byte[(NUM_SCRATCH_CODES * SCRATCH_CODE_SIZE) + SECRET_SIZE]; new SecureRandom().nextBytes(buffer); byte[] secret = Arrays.copyOf(buffer, SECRET_SIZE); return new String(new Base32().encode(secret)); } /** * verifies code for OTP secret * * @param secret shared secret * @param token verification token * @return true if success */ public static boolean verifyToken(String secret, long token) { //check token in near future or past int window = TOKEN_WINDOW; for (int i = window; i >= -window; i--) { long time = (new Date().getTime() / TimeUnit.SECONDS.toMillis(CHANGE_INTERVAL)) + i; if (verifyToken(secret, token, time)) { return true; } } return false; } /** * verifies code for OTP secret per time interval * * @param secret shared secret * @param token verification token * @param time time representation to calculate OTP * @return true if success */ private static boolean verifyToken(String secret, long token, long time) {<FILL_FUNCTION_BODY>} }
long calculated = -1; byte[] key = new Base32().decode(secret); SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA1"); try { Mac mac = Mac.getInstance("HmacSHA1"); mac.init(secretKey); byte[] hash = mac.doFinal(ByteBuffer.allocate(8).putLong(time).array()); int offset = hash[hash.length - 1] & 0xF; for (int i = 0; i < 4; ++i) { calculated <<= 8; calculated |= (hash[offset + i] & 0xFF); } calculated &= 0x7FFFFFFF; calculated %= 1000000; } catch (Exception ex) { log.error(ex.toString(), ex); } return (calculated != -1 && calculated == token);
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/util/RefreshAuthKeyUtil.java
RefreshAllSystemsTask
run
class RefreshAllSystemsTask implements Runnable { private static final Logger log = LoggerFactory.getLogger(RefreshAllSystemsTask.class); @Override public void run() {<FILL_FUNCTION_BODY>} }
//distribute all public keys try { SSHUtil.distributePubKeysToAllSystems(); } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); }
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/util/SessionOutputSerializer.java
SessionOutputSerializer
serialize
class SessionOutputSerializer implements JsonSerializer<Object> { @Override public JsonElement serialize(Object src, Type typeOfSrc, JsonSerializationContext context) {<FILL_FUNCTION_BODY>} }
JsonObject object = new JsonObject(); if (typeOfSrc.equals(AuditWrapper.class)) { AuditWrapper auditWrapper = (AuditWrapper) src; object.addProperty("user_id", auditWrapper.getUser().getId()); object.addProperty("username", auditWrapper.getUser().getUsername()); object.addProperty("user_type", auditWrapper.getUser().getUserType()); object.addProperty("first_nm", auditWrapper.getUser().getFirstNm()); object.addProperty("last_nm", auditWrapper.getUser().getLastNm()); object.addProperty("email", auditWrapper.getUser().getEmail()); object.addProperty("session_id", auditWrapper.getSessionOutput().getSessionId()); object.addProperty("instance_id", auditWrapper.getSessionOutput().getInstanceId()); object.addProperty("host_id", auditWrapper.getSessionOutput().getId()); object.addProperty("host", auditWrapper.getSessionOutput().getDisplayLabel()); object.addProperty("output", auditWrapper.getSessionOutput().getOutput().toString()); object.addProperty("timestamp", new Date().getTime()); } return object;
bastillion-io_Bastillion
Bastillion/src/main/java/io/bastillion/manage/util/SessionOutputUtil.java
SessionOutputUtil
getOutput
class SessionOutputUtil { private static final Map<Long, UserSessionsOutput> userSessionsOutputMap = new ConcurrentHashMap<>(); public final static boolean enableInternalAudit = "true".equals(AppConfig.getProperty("enableInternalAudit")); private static final Gson gson = new GsonBuilder().registerTypeAdapter(AuditWrapper.class, new SessionOutputSerializer()).create(); private static final Logger systemAuditLogger = LoggerFactory.getLogger("io.bastillion.manage.util.SystemAudit"); private SessionOutputUtil() { } /** * removes session for user session * * @param sessionId session id */ public static void removeUserSession(Long sessionId) { UserSessionsOutput userSessionsOutput = userSessionsOutputMap.get(sessionId); if (userSessionsOutput != null) { userSessionsOutput.getSessionOutputMap().clear(); } userSessionsOutputMap.remove(sessionId); } /** * removes session output for host system * * @param sessionId session id * @param instanceId id of host system instance */ public static void removeOutput(Long sessionId, Integer instanceId) { UserSessionsOutput userSessionsOutput = userSessionsOutputMap.get(sessionId); if (userSessionsOutput != null) { userSessionsOutput.getSessionOutputMap().remove(instanceId); } } /** * adds a new output * * @param sessionOutput session output object */ public static void addOutput(SessionOutput sessionOutput) { UserSessionsOutput userSessionsOutput = userSessionsOutputMap.get(sessionOutput.getSessionId()); if (userSessionsOutput == null) { userSessionsOutputMap.put(sessionOutput.getSessionId(), new UserSessionsOutput()); userSessionsOutput = userSessionsOutputMap.get(sessionOutput.getSessionId()); } userSessionsOutput.getSessionOutputMap().put(sessionOutput.getInstanceId(), sessionOutput); } /** * adds a new output * * @param sessionId session id * @param instanceId id of host system instance * @param value Array that is the source of characters * @param offset The initial offset * @param count The length */ public static void addToOutput(Long sessionId, Integer instanceId, char[] value, int offset, int count) { UserSessionsOutput userSessionsOutput = userSessionsOutputMap.get(sessionId); if (userSessionsOutput != null) { userSessionsOutput.getSessionOutputMap().get(instanceId).getOutput().append(value, offset, count); } } /** * returns list of output lines * * @param sessionId session id object * @param user user auth object * @return session output list */ public static List<SessionOutput> getOutput(Connection con, Long sessionId, User user) throws SQLException {<FILL_FUNCTION_BODY>} }
List<SessionOutput> outputList = new ArrayList<>(); UserSessionsOutput userSessionsOutput = userSessionsOutputMap.get(sessionId); if (userSessionsOutput != null) { for (Integer key : userSessionsOutput.getSessionOutputMap().keySet()) { //get output chars and set to output SessionOutput sessionOutput = userSessionsOutput.getSessionOutputMap().get(key); if (sessionOutput != null && sessionOutput.getOutput() != null && StringUtils.isNotEmpty(sessionOutput.getOutput())) { outputList.add(sessionOutput); //send to audit logger systemAuditLogger.info(gson.toJson(new AuditWrapper(user, sessionOutput))); if (enableInternalAudit) { SessionAuditDB.insertTerminalLog(con, sessionOutput); } userSessionsOutput.getSessionOutputMap().put(key, new SessionOutput(sessionId, sessionOutput)); } } } return outputList;
wkeyuan_DWSurvey
DWSurvey/src/main/java/com/baidu/ueditor/ActionEnter.java
ActionEnter
getStartIndex
class ActionEnter { private HttpServletRequest request = null; private String rootPath = null; private String contextPath = null; private String actionType = null; private ConfigManager configManager = null; public ActionEnter ( HttpServletRequest request, String rootPath, String userId) { this.request = request; this.rootPath = rootPath; this.actionType = request.getParameter( "action" ); this.contextPath = request.getContextPath(); this.configManager = ConfigManager.getInstance( this.rootPath, this.contextPath, request.getRequestURI(), userId ); } public String exec () { String callbackName = this.request.getParameter("callback"); if ( callbackName != null ) { if ( !validCallbackName( callbackName ) ) { return new BaseState( false, AppInfo.ILLEGAL ).toJSONString(); } String ww = callbackName+"("+this.invoke()+");"; return ww; } else { return this.invoke(); } } public String invoke() { if ( actionType == null || !ActionMap.mapping.containsKey( actionType ) ) { return new BaseState( false, AppInfo.INVALID_ACTION ).toJSONString(); } if ( this.configManager == null || !this.configManager.valid() ) { return new BaseState( false, AppInfo.CONFIG_ERROR ).toJSONString(); } State state = null; int actionCode = ActionMap.getType( this.actionType ); Map<String, Object> conf = null; switch ( actionCode ) { case ActionMap.CONFIG: String config = this.configManager.getAllConfig().toString(); return config; case ActionMap.UPLOAD_IMAGE: case ActionMap.UPLOAD_SCRAWL: case ActionMap.UPLOAD_VIDEO: case ActionMap.UPLOAD_FILE: conf = this.configManager.getConfig( actionCode ); state = new Uploader( request, conf ).doExec(); break; case ActionMap.CATCH_IMAGE: conf = configManager.getConfig( actionCode ); String[] list = this.request.getParameterValues( (String)conf.get( "fieldName" ) ); state = new ImageHunter( conf ).capture( list ); break; case ActionMap.LIST_IMAGE: case ActionMap.LIST_FILE: conf = configManager.getConfig( actionCode ); int start = this.getStartIndex(); state = new FileManager( conf ).listFile( start ); break; } System.out.println("upload state:"+state.toJSONString()); return state.toJSONString(); } public int getStartIndex () {<FILL_FUNCTION_BODY>} /** * callback参数验证 */ public boolean validCallbackName ( String name ) { if ( name.matches( "^[a-zA-Z_]+[\\w0-9_]*$" ) ) { return true; } return false; } }
String start = this.request.getParameter( "start" ); try { return Integer.parseInt( start ); } catch ( Exception e ) { return 0; }
wkeyuan_DWSurvey
DWSurvey/src/main/java/com/baidu/ueditor/Encoder.java
Encoder
toUnicode
class Encoder { public static String toUnicode ( String input ) {<FILL_FUNCTION_BODY>} }
StringBuilder builder = new StringBuilder(); char[] chars = input.toCharArray(); for ( char ch : chars ) { if ( ch < 256 ) { builder.append( ch ); } else { builder.append( "\\u" + Integer.toHexString( ch& 0xffff ) ); } } return builder.toString();
wkeyuan_DWSurvey
DWSurvey/src/main/java/com/baidu/ueditor/PathFormat.java
PathFormat
parse
class PathFormat { private static final String TIME = "time"; private static final String FULL_YEAR = "yyyy"; private static final String YEAR = "yy"; private static final String MONTH = "mm"; private static final String DAY = "dd"; private static final String HOUR = "hh"; private static final String MINUTE = "ii"; private static final String SECOND = "ss"; private static final String RAND = "rand"; private static Date currentDate = null; public static String parse ( String input ) {<FILL_FUNCTION_BODY>} /** * 格式化路径, 把windows路径替换成标准路径 * @param input 待格式化的路径 * @return 格式化后的路径 */ public static String format ( String input ) { return input.replace( "\\", "/" ); } public static String parse ( String input, String filename ) { Pattern pattern = Pattern.compile( "\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE ); Matcher matcher = pattern.matcher(input); String matchStr = null; PathFormat.currentDate = new Date(); StringBuffer sb = new StringBuffer(); while ( matcher.find() ) { matchStr = matcher.group( 1 ); if ( matchStr.indexOf( "filename" ) != -1 ) { filename = filename.replace( "$", "\\$" ).replaceAll( "[\\/:*?\"<>|]", "" ); matcher.appendReplacement(sb, filename ); } else { matcher.appendReplacement(sb, PathFormat.getString( matchStr ) ); } } matcher.appendTail(sb); return sb.toString(); } private static String getString ( String pattern ) { pattern = pattern.toLowerCase(); // time 处理 if ( pattern.indexOf( PathFormat.TIME ) != -1 ) { return PathFormat.getTimestamp(); } else if ( pattern.indexOf( PathFormat.FULL_YEAR ) != -1 ) { return PathFormat.getFullYear(); } else if ( pattern.indexOf( PathFormat.YEAR ) != -1 ) { return PathFormat.getYear(); } else if ( pattern.indexOf( PathFormat.MONTH ) != -1 ) { return PathFormat.getMonth(); } else if ( pattern.indexOf( PathFormat.DAY ) != -1 ) { return PathFormat.getDay(); } else if ( pattern.indexOf( PathFormat.HOUR ) != -1 ) { return PathFormat.getHour(); } else if ( pattern.indexOf( PathFormat.MINUTE ) != -1 ) { return PathFormat.getMinute(); } else if ( pattern.indexOf( PathFormat.SECOND ) != -1 ) { return PathFormat.getSecond(); } else if ( pattern.indexOf( PathFormat.RAND ) != -1 ) { return PathFormat.getRandom( pattern ); } return pattern; } private static String getTimestamp () { return System.currentTimeMillis() + ""; } private static String getFullYear () { return new SimpleDateFormat( "yyyy" ).format( PathFormat.currentDate ); } private static String getYear () { return new SimpleDateFormat( "yy" ).format( PathFormat.currentDate ); } private static String getMonth () { return new SimpleDateFormat( "MM" ).format( PathFormat.currentDate ); } private static String getDay () { return new SimpleDateFormat( "dd" ).format( PathFormat.currentDate ); } private static String getHour () { return new SimpleDateFormat( "HH" ).format( PathFormat.currentDate ); } private static String getMinute () { return new SimpleDateFormat( "mm" ).format( PathFormat.currentDate ); } private static String getSecond () { return new SimpleDateFormat( "ss" ).format( PathFormat.currentDate ); } private static String getRandom ( String pattern ) { int length = 0; pattern = pattern.split( ":" )[ 1 ].trim(); length = Integer.parseInt( pattern ); return ( Math.random() + "" ).replace( ".", "" ).substring( 0, length ); } public static void main(String[] args) { // TODO Auto-generated method stub } }
Pattern pattern = Pattern.compile( "\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE ); Matcher matcher = pattern.matcher(input); PathFormat.currentDate = new Date(); StringBuffer sb = new StringBuffer(); while ( matcher.find() ) { matcher.appendReplacement(sb, PathFormat.getString( matcher.group( 1 ) ) ); } matcher.appendTail(sb); return sb.toString();
wkeyuan_DWSurvey
DWSurvey/src/main/java/com/baidu/ueditor/define/BaseState.java
BaseState
toString
class BaseState implements State { private boolean state = false; private String info = null; private Map<String, String> infoMap = new HashMap<String, String>(); public BaseState () { this.state = true; } public BaseState ( boolean state ) { this.setState( state ); } public BaseState ( boolean state, String info ) { this.setState( state ); this.info = info; } public BaseState ( boolean state, int infoCode ) { this.setState( state ); this.info = AppInfo.getStateInfo( infoCode ); } public BaseState ( boolean state, int infoCode , File tempFile) { this.setState( state ); this.info = AppInfo.getStateInfo( infoCode ); this.tmpFile = tempFile; } public boolean isSuccess () { return this.state; } public void setState ( boolean state ) { this.state = state; } public void setInfo ( String info ) { this.info = info; } public void setInfo ( int infoCode ) { this.info = AppInfo.getStateInfo( infoCode ); } @Override public String toJSONString() { return this.toString(); } public String toString () {<FILL_FUNCTION_BODY>} @Override public void putInfo(String name, String val) { this.infoMap.put(name, val); } @Override public void putInfo(String name, long val) { this.putInfo(name, val+""); } private File tmpFile; public File getTmpFile() { return tmpFile; } public void setTmpFile(File tmpFile) { this.tmpFile = tmpFile; } }
String key = null; String stateVal = this.isSuccess() ? AppInfo.getStateInfo( AppInfo.SUCCESS ) : this.info; StringBuilder builder = new StringBuilder(); builder.append( "{\"state\": \"" + stateVal + "\"" ); Iterator<String> iterator = this.infoMap.keySet().iterator(); while ( iterator.hasNext() ) { key = iterator.next(); builder.append( ",\"" + key + "\": \"" + this.infoMap.get(key) + "\"" ); } builder.append( "}" ); return Encoder.toUnicode( builder.toString() );
wkeyuan_DWSurvey
DWSurvey/src/main/java/com/baidu/ueditor/define/MultiState.java
MultiState
toJSONString
class MultiState implements State { private boolean state = false; private String info = null; private Map<String, Long> intMap = new HashMap<String, Long>(); private Map<String, String> infoMap = new HashMap<String, String>(); private List<String> stateList = new ArrayList<String>(); public MultiState ( boolean state ) { this.state = state; } public MultiState ( boolean state, String info ) { this.state = state; this.info = info; } public MultiState ( boolean state, int infoKey ) { this.state = state; this.info = AppInfo.getStateInfo( infoKey ); } @Override public boolean isSuccess() { return this.state; } public void addState ( State state ) { stateList.add( state.toJSONString() ); } /** * 该方法调用无效果 */ @Override public void putInfo(String name, String val) { this.infoMap.put(name, val); } @Override public String toJSONString() {<FILL_FUNCTION_BODY>} @Override public void putInfo(String name, long val) { this.intMap.put( name, val ); } }
String stateVal = this.isSuccess() ? AppInfo.getStateInfo( AppInfo.SUCCESS ) : this.info; StringBuilder builder = new StringBuilder(); builder.append( "{\"state\": \"" + stateVal + "\"" ); // 数字转换 Iterator<String> iterator = this.intMap.keySet().iterator(); while ( iterator.hasNext() ) { stateVal = iterator.next(); builder.append( ",\""+ stateVal +"\": " + this.intMap.get( stateVal ) ); } iterator = this.infoMap.keySet().iterator(); while ( iterator.hasNext() ) { stateVal = iterator.next(); builder.append( ",\""+ stateVal +"\": \"" + this.infoMap.get( stateVal ) + "\"" ); } builder.append( ", list: [" ); iterator = this.stateList.iterator(); while ( iterator.hasNext() ) { builder.append( iterator.next() + "," ); } if ( this.stateList.size() > 0 ) { builder.deleteCharAt( builder.length() - 1 ); } builder.append( " ]}" ); return Encoder.toUnicode( builder.toString() );
wkeyuan_DWSurvey
DWSurvey/src/main/java/com/baidu/ueditor/hunter/FileManager.java
FileManager
getAllowFiles
class FileManager { private String dir = null; private String rootPath = null; private String[] allowFiles = null; private int count = 0; public FileManager ( Map<String, Object> conf ) { this.rootPath = (String)conf.get( "rootPath" ); this.dir = this.rootPath + (String)conf.get( "dir" ); this.allowFiles = this.getAllowFiles( conf.get("allowFiles") ); this.count = (Integer)conf.get( "count" ); } public State listFile ( int index ) { File dir = new File( this.dir ); State state = null; if ( !dir.exists() ) { return new BaseState( false, AppInfo.NOT_EXIST ); } if ( !dir.isDirectory() ) { return new BaseState( false, AppInfo.NOT_DIRECTORY ); } Collection<File> list = FileUtils.listFiles( dir, this.allowFiles, true ); if ( index < 0 || index > list.size() ) { state = new MultiState( true ); } else { Object[] fileList = Arrays.copyOfRange( list.toArray(), index, index + this.count ); state = this.getState( fileList ); } state.putInfo( "start", index ); state.putInfo( "total", list.size() ); return state; } private State getState ( Object[] files ) { MultiState state = new MultiState( true ); BaseState fileState = null; File file = null; for ( Object obj : files ) { if ( obj == null ) { break; } file = (File)obj; fileState = new BaseState( true ); fileState.putInfo( "url", PathFormat.format( this.getPath( file ) ) ); state.addState( fileState ); } return state; } private String getPath ( File file ) { String path = file.getAbsolutePath(); return path.replace( this.rootPath, "/" ); } private String[] getAllowFiles ( Object fileExt ) {<FILL_FUNCTION_BODY>} }
String[] exts = null; String ext = null; if ( fileExt == null ) { return new String[ 0 ]; } exts = (String[])fileExt; for ( int i = 0, len = exts.length; i < len; i++ ) { ext = exts[ i ]; exts[ i ] = ext.replace( ".", "" ); } return exts;
wkeyuan_DWSurvey
DWSurvey/src/main/java/com/baidu/ueditor/hunter/ImageHunter.java
ImageHunter
captureRemoteData
class ImageHunter { private String filename = null; private String savePath = null; private String rootPath = null; private List<String> allowTypes = null; private long maxSize = -1; private List<String> filters = null; public ImageHunter ( Map<String, Object> conf ) { this.filename = (String)conf.get( "filename" ); this.savePath = (String)conf.get( "savePath" ); this.rootPath = (String)conf.get( "rootPath" ); this.maxSize = (Long)conf.get( "maxSize" ); this.allowTypes = Arrays.asList( (String[])conf.get( "allowFiles" ) ); this.filters = Arrays.asList( (String[])conf.get( "filter" ) ); } public State capture ( String[] list ) { MultiState state = new MultiState( true ); for ( String source : list ) { state.addState( captureRemoteData( source ) ); } return state; } public State captureRemoteData ( String urlStr ) {<FILL_FUNCTION_BODY>} private String getPath ( String savePath, String filename, String suffix ) { return PathFormat.parse( savePath + suffix, filename ); } private boolean validHost ( String hostname ) { try { InetAddress ip = InetAddress.getByName(hostname); if (ip.isSiteLocalAddress()) { return false; } } catch (UnknownHostException e) { return false; } return !filters.contains( hostname ); } private boolean validContentState ( int code ) { return HttpURLConnection.HTTP_OK == code; } private boolean validFileType ( String type ) { return this.allowTypes.contains( type ); } private boolean validFileSize ( int size ) { return size < this.maxSize; } }
HttpURLConnection connection = null; URL url = null; String suffix = null; try { url = new URL( urlStr ); if ( !validHost( url.getHost() ) ) { return new BaseState( false, AppInfo.PREVENT_HOST ); } connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects( true ); connection.setUseCaches( true ); if ( !validContentState( connection.getResponseCode() ) ) { return new BaseState( false, AppInfo.CONNECTION_ERROR ); } suffix = MIMEType.getSuffix( connection.getContentType() ); if ( !validFileType( suffix ) ) { return new BaseState( false, AppInfo.NOT_ALLOW_FILE_TYPE ); } if ( !validFileSize( connection.getContentLength() ) ) { return new BaseState( false, AppInfo.MAX_SIZE ); } String savePath = this.getPath( this.savePath, this.filename, suffix ); String physicalPath = this.rootPath + savePath; State state = StorageManager.saveFileByInputStream( connection.getInputStream(), physicalPath ); if ( state.isSuccess() ) { state.putInfo( "url", PathFormat.format( savePath ) ); state.putInfo( "source", urlStr ); } return state; } catch ( Exception e ) { return new BaseState( false, AppInfo.REMOTE_FAIL ); }
wkeyuan_DWSurvey
DWSurvey/src/main/java/com/baidu/ueditor/upload/Base64Uploader.java
Base64Uploader
save
class Base64Uploader { public static State save(String content, Map<String, Object> conf) {<FILL_FUNCTION_BODY>} private static byte[] decode(String content) { return Base64.decodeBase64(content); } private static boolean validSize(byte[] data, long length) { return data.length <= length; } }
byte[] data = decode(content); long maxSize = ((Long) conf.get("maxSize")).longValue(); if (!validSize(data, maxSize)) { return new BaseState(false, AppInfo.MAX_SIZE); } String suffix = FileType.getSuffix("JPG"); String savePath = PathFormat.parse((String) conf.get("savePath"), (String) conf.get("filename")); savePath = savePath + suffix; String physicalPath = (String) conf.get("rootPath") + savePath; State storageState = StorageManager.saveBinaryFile(data, physicalPath); if (storageState.isSuccess()) { storageState.putInfo("url", PathFormat.format(savePath)); storageState.putInfo("type", suffix); storageState.putInfo("original", ""); } return storageState;
wkeyuan_DWSurvey
DWSurvey/src/main/java/com/baidu/ueditor/upload/BinaryUploader.java
BinaryUploader
save
class BinaryUploader { public static final State save(HttpServletRequest request, Map<String, Object> conf) {<FILL_FUNCTION_BODY>} private static boolean validType(String type, String[] allowTypes) { List<String> list = Arrays.asList(allowTypes); return list.contains(type); } }
FileItemStream fileStream = null; boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null; if (!ServletFileUpload.isMultipartContent(request)) { return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT); } ServletFileUpload upload = new ServletFileUpload( new DiskFileItemFactory()); if ( isAjaxUpload ) { upload.setHeaderEncoding( "UTF-8" ); } try { FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { fileStream = iterator.next(); if (!fileStream.isFormField()) break; fileStream = null; } if (fileStream == null) { return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA); } String savePath = (String) conf.get("savePath"); String originFileName = fileStream.getName(); String suffix = FileType.getSuffixByFilename(originFileName); originFileName = originFileName.substring(0, originFileName.length() - suffix.length()); savePath = savePath + suffix; long maxSize = ((Long) conf.get("maxSize")).longValue(); if (!validType(suffix, (String[]) conf.get("allowFiles"))) { return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE); } savePath = PathFormat.parse(savePath, originFileName); String physicalPath = (String) conf.get("rootPath") + savePath; InputStream is = fileStream.openStream(); State storageState = StorageManager.saveFileByInputStream(is, physicalPath, maxSize); is.close(); if (storageState.isSuccess()) { storageState.putInfo("url", PathFormat.format(savePath)); storageState.putInfo("type", suffix); storageState.putInfo("original", originFileName + suffix); } return storageState; } catch (FileUploadException e) { return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR); } catch (IOException e) { } return new BaseState(false, AppInfo.IO_ERROR);
wkeyuan_DWSurvey
DWSurvey/src/main/java/com/baidu/ueditor/upload/StorageManager.java
StorageManager
saveTmpFile
class StorageManager { public static final int BUFFER_SIZE = 8192; public StorageManager() { } public static State saveBinaryFile(byte[] data, String path) { if(!FileMagicUtils.isUserUpFileType(data,path.substring(path.lastIndexOf(".")))){ return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE); } File file = new File(path); State state = valid(file); if (!state.isSuccess()) { return state; } try { BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(file)); bos.write(data); bos.flush(); bos.close(); } catch (IOException ioe) { ioe.printStackTrace(); return new BaseState(false, AppInfo.IO_ERROR); } state = new BaseState(true, file.getAbsolutePath()); state.putInfo( "size", data.length ); state.putInfo( "title", file.getName() ); return state; } public static State saveFileByInputStream(InputStream is, String path, long maxSize) { BaseState validateState = isUserUpFileType(is,path.substring(path.lastIndexOf("."))); if(!validateState.isSuccess()) return validateState; State state = new BaseState(false, AppInfo.IO_ERROR); File tmpFile = validateState.getTmpFile(); if(tmpFile!=null){ state = saveTmpFile(tmpFile, path); deleteTmpFile(tmpFile); return state; } return state; } public static State saveFileByInputStream(InputStream is, String path) { BaseState validateState = isUserUpFileType(is,path.substring(path.lastIndexOf("."))); if(!validateState.isSuccess()) return validateState; State state = new BaseState(false, AppInfo.IO_ERROR); File tmpFile = validateState.getTmpFile(); if(tmpFile!=null){ state = saveTmpFile(tmpFile, path); deleteTmpFile(tmpFile); return state; } return state; } private static File getTmpFile() { File tmpDir = FileUtils.getTempDirectory(); String tmpFileName = (Math.random() * 10000 + "").replace(".", ""); return new File(tmpDir, tmpFileName); } private static State saveTmpFile(File tmpFile, String path) {<FILL_FUNCTION_BODY>} private static State valid(File file) { File parentPath = file.getParentFile(); if ((!parentPath.exists()) && (!parentPath.mkdirs())) { return new BaseState(false, AppInfo.FAILED_CREATE_FILE); } if (!parentPath.canWrite()) { return new BaseState(false, AppInfo.PERMISSION_DENIED); } return new BaseState(true); } public static BaseState isUserUpFileType(InputStream is,String fileSuffix) { File tmpFile = getTmpFile(); byte[] dataBuf = new byte[ 2048 ]; BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE); try { BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE); int count = 0; while ((count = bis.read(dataBuf)) != -1) { bos.write(dataBuf, 0, count); } bis.close(); bos.flush(); bos.close(); if(!FileMagicUtils.isUserUpFileType(tmpFile,fileSuffix)){ tmpFile.delete(); return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE); } // tmpFile.delete(); } catch (IOException e) { e.printStackTrace(); return new BaseState(false, AppInfo.IO_ERROR); } return new BaseState(true, AppInfo.SUCCESS, tmpFile); } private static void deleteTmpFile(File tmpFile) { try{ tmpFile.delete(); }catch (Exception e){ e.printStackTrace(); } } }
State state = null; File targetFile = new File(path); if (targetFile.canWrite()) { return new BaseState(false, AppInfo.PERMISSION_DENIED); } try { FileUtils.moveFile(tmpFile, targetFile); } catch (IOException e) { e.printStackTrace(); return new BaseState(false, AppInfo.IO_ERROR); } state = new BaseState(true); state.putInfo( "size", targetFile.length() ); state.putInfo( "title", targetFile.getName() ); return state;
wkeyuan_DWSurvey
DWSurvey/src/main/java/com/baidu/ueditor/upload/Uploader.java
Uploader
doExec
class Uploader { private HttpServletRequest request = null; private Map<String, Object> conf = null; public Uploader(HttpServletRequest request, Map<String, Object> conf) { this.request = request; this.conf = conf; } public final State doExec() {<FILL_FUNCTION_BODY>} }
String filedName = (String) this.conf.get("fieldName"); State state = null; if ("true".equals(this.conf.get("isBase64"))) { state = Base64Uploader.save(this.request.getParameter(filedName), this.conf); } else { state = BinaryUploader.save(this.request, this.conf); } return state;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/base/controller/JcaptchaController.java
JcaptchaController
execute
class JcaptchaController { @Autowired private ImageCaptchaService imageCaptchaService; @RequestMapping("/jcaptcha.do") public String execute(HttpServletRequest request,HttpServletResponse response) throws Exception {<FILL_FUNCTION_BODY>} }
byte[] captchaChallengeAsJpeg = null; // the output stream to render the captcha image as jpeg into ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); try { // get the session id that will identify the generated captcha. // the same id must be used to validate the response, the session id // is a good candidate! String captchaId = request.getSession().getId(); // call the ImageCaptchaService getChallenge method BufferedImage challenge = imageCaptchaService.getImageChallengeForID(captchaId, request.getLocale()); // a jpeg encoder /* JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream); jpegEncoder.encode(challenge); */ jpegOutputStream = new ByteArrayOutputStream(); ImageIO.write(challenge,"jpg",jpegOutputStream); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); // flush it in the response response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); ServletOutputStream responseOutputStream = response.getOutputStream(); responseOutputStream.write(captchaChallengeAsJpeg); responseOutputStream.flush(); responseOutputStream.close(); return null;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/base/controller/LoginRegisterResult.java
LoginRegisterResult
FAILURE
class LoginRegisterResult { private String status; private String type; private String[] currentAuthority; private HttpResult httpResult; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String[] getCurrentAuthority() { return currentAuthority; } public void setCurrentAuthority(String[] currentAuthority) { this.currentAuthority = currentAuthority; } public HttpResult getHttpResult() { return httpResult; } public void setHttpResult(HttpResult httpResult) { this.httpResult = httpResult; } public static LoginRegisterResult RESULT(String status,String type){ LoginRegisterResult loginResult = new LoginRegisterResult(); loginResult.setStatus(status); loginResult.setType(type); loginResult.setCurrentAuthority(new String[]{}); return loginResult; } public static LoginRegisterResult SUCCESS(String currentAuthority){ LoginRegisterResult loginResult = new LoginRegisterResult(); loginResult.setStatus("ok"); loginResult.setType("account"); // loginResult.setCurrentAuthority("admin"); loginResult.setCurrentAuthority(new String[]{currentAuthority}); return loginResult; } public static LoginRegisterResult SUCCESS(String[] currentAuthority){ LoginRegisterResult loginResult = new LoginRegisterResult(); loginResult.setStatus("ok"); loginResult.setType("account"); // loginResult.setCurrentAuthority("admin"); loginResult.setCurrentAuthority(currentAuthority); return loginResult; } public static LoginRegisterResult FAILURE(){ LoginRegisterResult loginResult = new LoginRegisterResult(); loginResult.setStatus("error"); loginResult.setType("account"); loginResult.setCurrentAuthority(new String[]{"guest"}); return loginResult; } public static LoginRegisterResult FAILURE(HttpResult httpResult){<FILL_FUNCTION_BODY>} }
LoginRegisterResult loginResult = new LoginRegisterResult(); loginResult.setStatus("error"); loginResult.setType("account"); loginResult.setCurrentAuthority(new String[]{"guest"}); loginResult.setHttpResult(httpResult); return loginResult;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/base/controller/SecurityController.java
SecurityController
loginPwd
class SecurityController { @Autowired private AccountManager accountManager; @Autowired private UserManager userManager; @Autowired private FormAuthenticationWithLockFilter formAuthFilter; @RequestMapping("/logout.do") @ResponseBody public HttpResult logout(HttpServletRequest request,HttpServletResponse response) throws Exception { if (SecurityUtils.getSubject() != null) { User curUser = accountManager.getCurUser(); String userId = ""; String loginName = ""; if(curUser!=null){ userId = curUser.getId(); loginName = curUser.getLoginName(); } SecurityUtils.getSubject().logout(); } request.getSession().invalidate(); return HttpResult.SUCCESS(); } @RequestMapping("/login.do") @ResponseBody public LoginRegisterResult login(HttpServletRequest request, HttpServletResponse response, String userName, String password) { Subject subject = SecurityUtils.getSubject(); boolean isAuth = subject.isAuthenticated(); if(isAuth){ User user = accountManager.getCurUser(); if(user!=null){ String[] authed = new String[]{}; if("1".equals(user.getId())) authed = new String[]{RoleCode.DWSURVEY_SUPER_ADMIN}; return LoginRegisterResult.SUCCESS(authed); } } //账号密码 request.setAttribute("username",userName); return loginPwd(request,response,userName,password); } @RequestMapping("/login-pwd.do") @ResponseBody public LoginRegisterResult loginPwd(HttpServletRequest request, HttpServletResponse response, @RequestParam String userName, @RequestParam String password) {<FILL_FUNCTION_BODY>} @RequestMapping("/checkEmail.do") @ResponseBody public boolean checkEmailUn(String id,String email) throws Exception{ User user=userManager.findEmailUn(id,email); boolean result=true; if(user!=null){ result=false; } return result; } @RequestMapping("/checkLoginNamelUn.do") @ResponseBody public boolean checkLoginNamelUn(String id,String loginName) throws Exception{ User user=userManager.findNameUn(id,loginName); boolean result=true; if(user!=null){ result=false; } return result; } }
Subject subject = SecurityUtils.getSubject(); boolean isAuth = subject.isAuthenticated(); String error="账号或密码错误"; String[] authed = null; try{ if(isAuth) subject.logout(); if(StringUtils.isNotEmpty(userName)){ User user = accountManager.findUserByLoginNameOrEmail(userName); if(user!=null){ UsernamePasswordToken loginToken = new UsernamePasswordToken(userName, password); request.setAttribute("username",userName); if (!formAuthFilter.checkIfAccountLocked(request)) { try { subject.login(loginToken); formAuthFilter.resetAccountLock(userName); subject.getSession().setAttribute("loginUserName", userName); user.setLastLoginTime(new Date()); accountManager.saveUp(user); if("1".equals(user.getId())) authed = new String[]{RoleCode.DWSURVEY_SUPER_ADMIN}; return LoginRegisterResult.SUCCESS(authed); } catch (IncorrectCredentialsException e) { formAuthFilter.decreaseAccountLoginAttempts(request); error = "密码不正确"; } catch (AuthenticationException e) { error = "身份认证错误"; } } else { // ExcessiveAttemptsException超过登录次数 error = "超过登录次数限制"; } }else{ error = "未找到userName对应用户"; } }else{ error = "登录名userName不能为空"; } }catch (Exception e) { e.printStackTrace(); error = e.getMessage(); } return LoginRegisterResult.FAILURE(HttpResult.FAILURE_MSG(error));
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/base/service/AccountManager.java
AccountManager
isSupervisor
class AccountManager { private static Logger logger = LoggerFactory.getLogger(AccountManager.class); @Autowired private UserDao userDao; // @Autowired // private NotifyMessageProducer notifyMessageProducer;//JMS消息推送 private ShiroDbRealm shiroRealm; /** * 在保存用户时,发送用户修改通知消息, 由消息接收者异步进行较为耗时的通知邮件发送. * * 如果企图修改超级用户,取出当前操作员用户,打印其信息然后抛出异常. * */ // 演示指定非默认名称的TransactionManager. @Transactional public void saveUser(User user) { if (isSupervisor(user)) { logger.warn("操作员{}尝试修改超级管理员用户", SecurityUtils.getSubject() .getPrincipal()); throw new ServiceException("不能修改超级管理员用户"); } //判断是否有重复用户 String shaPassword = DigestUtils.sha1Hex(user.getPlainPassword()); user.setShaPassword(shaPassword); boolean bool=user.getId()==null?true:false; userDao.save(user); if (shiroRealm != null) { shiroRealm.clearCachedAuthorizationInfo(user.getLoginName()); } /*if(bool){ // Email email=new Email(); // sendNotifyMessage(email); 使用jms辅助 发送邮件 simpleMailService.sendRegisterMailByAsync(user); }*/ } @Transactional public void saveUp(User user){ if (isSupervisor(user)) { logger.warn("操作员{}尝试修改超级管理员用户", SecurityUtils.getSubject().getPrincipal()); throw new ServiceException("不能修改超级管理员用户"); } userDao.save(user); } @Transactional public boolean updatePwd(String curpwd, String newPwd) { User user = getCurUser(); if(user!=null){ if(curpwd!=null && newPwd!=null){ //判断是否有重复用户 String curShaPassword = DigestUtils.sha1Hex(curpwd); if(user.getShaPassword().equals(curShaPassword)){ String shaPassword = DigestUtils.sha1Hex(newPwd); user.setShaPassword(shaPassword); userDao.save(user); return true; } } } return false; } /*public User getByUid(String userSource,String uid){ Criterion cri1=Restrictions.eq("thirdSource", userSource); Criterion cri2=Restrictions.eq("thirdUid", uid); return userDao.findUnique(cri1,cri2); }*/ //新注册用户,注册后 // private void sendNotifyMessage(Email email) { // notifyMessageProducer.sendQueue(email); // } /** * 判断是否超级管理员. */ private boolean isSupervisor(User user) {<FILL_FUNCTION_BODY>} @Transactional(readOnly = true) public User getUser(String id) { return userDao.get(id); } @Transactional(readOnly = true) public User findUserByLoginName(String loginName) { return userDao.findUniqueBy("loginName", loginName); } @Transactional(readOnly = true) public User findUserByLoginNameOrEmail(String loginName) { User user = null; if(loginName!=null){ user = userDao.findUniqueBy("loginName", loginName); if(user==null && loginName.contains("@")){ //是邮箱账号 user = userDao.findUniqueBy("email", loginName); } } return user; } /*验证邮箱是否存在*/ @Transactional(readOnly = true) public User findUserByEmail(String email){ List<User> users=userDao.findBy("email", email); if(users!=null && users.size()>0){ return users.get(0); } return null; } /** * 检查用户名是否唯一. * * @return loginName在数据库中唯一或等于oldLoginName时返回true. */ @Transactional(readOnly = true) public boolean isLoginNameUnique(String newLoginName, String oldLoginName) { return userDao.isPropertyUnique("loginName", newLoginName, oldLoginName); } /** * 取出当前登陆用户 */ public User getCurUser(){ Subject subject=SecurityUtils.getSubject(); if(subject!=null){ Object principal=subject.getPrincipal(); if(principal!=null){ User user = findUserByLoginName(principal.toString()); return user; } } return null; } }
// return (user.getId() != null && user.getId() == 1L); return false;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/email/Email.java
Email
toString
class Email { private String to;// 收件人 private String subject;// 主题 private String username;// 用户称呼 private String content;// 内容 private String date;// 日期 private String sendEmailId; public Email() { super(); } public Email(String to, String subject, String username, String content, String date) { super(); this.to = to; this.subject = subject; this.username = username; this.content = content; this.date = date; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getSendEmailId() { return sendEmailId; } public void setSendEmailId(String sendEmailId) { this.sendEmailId = sendEmailId; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "Email [content=" + content + ", date=" + date + ", subject=" + subject + ", to=" + to + ", username=" + username + "]";
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/file/FileMagicUtils.java
FileMagicUtils
getFileMagic
class FileMagicUtils { //非登录用户能够上传的文件类型 public static FileMagic[] anonUpFileType() { return new FileMagic[]{FileMagic.PNG,FileMagic.JPG,FileMagic.JPEG,FileMagic.GIF, FileMagic.TXT,FileMagic.PDF, FileMagic.XLSX,FileMagic.XLS,FileMagic.DOC,FileMagic.DOCX,FileMagic.PPT,FileMagic.PPTX, FileMagic.ZIP,FileMagic.RAR,FileMagic.Z7Z}; } //登录用户能够上传的文件类型 public static FileMagic[] userUpFileType() { return new FileMagic[]{FileMagic.PNG,FileMagic.JPG,FileMagic.JPEG,FileMagic.GIF, FileMagic.TXT,FileMagic.PDF, FileMagic.XLSX,FileMagic.XLS,FileMagic.DOC,FileMagic.DOCX,FileMagic.PPT,FileMagic.PPTX, FileMagic.ZIP,FileMagic.RAR,FileMagic.Z7Z}; } //根据文件获取对应的文件类型 public static FileMagic getFileMagic(File inp, String fileSuffix) throws Exception { FileMagic fileMagic = null; FileInputStream fis = null; try{ fis = new FileInputStream(inp); fileMagic = getFileMagic(fis,fileSuffix); }catch (Exception e){ e.printStackTrace(); }finally { if (fis!=null) fis.close(); } return fileMagic; } //切换到使用最新的tika验测 public static FileMagic getFileMagic(byte[] bytes,String fileName) throws IOException{<FILL_FUNCTION_BODY>} //切换到使用最新的tika验测 public static FileMagic getFileMagic(InputStream fis, String fileName) throws IOException{ String mineType = TikaFileUtils.mimeType(fis,fileName); if(mineType!=null){ FileMagic[] fileMagics = FileMagic.values(); int fileMagicLength = fileMagics.length; for(int i = 0; i < fileMagicLength; ++i) { FileMagic fm = fileMagics[i]; String fileSuffix = fm.getFileSuffix().toLowerCase(); if (fileSuffix.indexOf(mineType.toLowerCase())>=0) { return fm; } } } return FileMagic.UNKNOWN; } public static boolean isUserUpFileType(byte[] bytes, String suffix) { try { FileMagic fileMagic = getFileMagic(bytes,suffix); if (isUserUpFileMagic(fileMagic)) return true; } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean isUserUpFileType(File file, String suffix) { try { FileMagic fileMagic = getFileMagic(file,suffix); if (isUserUpFileMagic(fileMagic)) return true; } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean isUserUpFileType(InputStream inputStream, String suffix) { try { FileMagic fileMagic = getFileMagic(inputStream,suffix); if (isUserUpFileMagic(fileMagic)) return true; } catch (Exception e) { e.printStackTrace(); } return false; } /** * 判断是否在登录用户可上传白名单 * @param fileMagic * @return */ public static boolean isUserUpFileMagic(FileMagic fileMagic) { FileMagic[] fileMagics = userUpFileType(); for (FileMagic magic:fileMagics) { if(magic == fileMagic){ return true; } } return false; } }
String mineType = TikaFileUtils.mimeType(bytes,fileName); if(mineType!=null){ FileMagic[] fileMagics = FileMagic.values(); int fileMagicLength = fileMagics.length; for(int i = 0; i < fileMagicLength; ++i) { FileMagic fm = fileMagics[i]; String fileSuffix = fm.getFileSuffix().toLowerCase(); if (fileSuffix.indexOf(mineType.toLowerCase())>=0) { return fm; } } } return FileMagic.UNKNOWN;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/file/TikaFileUtils.java
TikaFileUtils
mimeType
class TikaFileUtils { public static String mimeType(byte[] bytes, String suffix) {<FILL_FUNCTION_BODY>} public static String mimeType(InputStream inputStream, String suffix) { try { Tika tika = new Tika(); String mimeTypeStr = tika.detect(inputStream,suffix); return getMimeType(mimeTypeStr, suffix); } catch (IOException e) { e.printStackTrace(); } catch (MimeTypeException e) { e.printStackTrace(); } return null; } private static String getMimeType(String mimeTypeStr, String suffix) throws MimeTypeException { MimeTypes mimeTypes = MimeTypes.getDefaultMimeTypes(); MimeType mimeType = mimeTypes.forName(mimeTypeStr); if(mimeType.getExtensions().stream().anyMatch(ext -> ext.equals(suffix))){ return suffix; } return null; } public static String getMimeType(InputStream inputStream, String suffix) { try { Tika tika = new Tika(); String mimeTypeStr = tika.detect(inputStream,suffix); return getMimeType(mimeTypeStr); } catch (IOException e) { e.printStackTrace(); } catch (MimeTypeException e) { e.printStackTrace(); } return null; } private static String getMimeType(String mimeTypeStr) throws MimeTypeException { MimeTypes mimeTypes = MimeTypes.getDefaultMimeTypes(); MimeType mimeType = mimeTypes.forName(mimeTypeStr); List<String> list = mimeType.getExtensions(); return JSON.toJSONString(list); } }
try { Tika tika = new Tika(); String mimeTypeStr = tika.detect(bytes,suffix); return getMimeType(mimeTypeStr, suffix); } catch (MimeTypeException e) { e.printStackTrace(); } return null;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/httpclient/IdleConnectionEvictor.java
IdleConnectionEvictor
run
class IdleConnectionEvictor extends Thread { private final HttpClientConnectionManager connMgr; private volatile boolean shutdown; public IdleConnectionEvictor(HttpClientConnectionManager connMgr) { this.connMgr = connMgr; // 启动当前线程 this.start(); } @Override public void run() {<FILL_FUNCTION_BODY>} public void shutdown() { shutdown = true; synchronized (this) { notifyAll(); } } }
try { while (!shutdown) { synchronized (this) { wait(5000); // 关闭失效的连接 connMgr.closeExpiredConnections(); } } } catch (InterruptedException ex) { // 结束 }
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/httpclient/ResultUtils.java
ResultUtils
getPageByPageResult
class ResultUtils { public static <T> Page<T> getPageByPageResult(PageResult<T> pageResult){<FILL_FUNCTION_BODY>} public static <T> PageResult<T> getPageResultByPage(Page<T> page,PageResult<T> pageResult){ if(page!=null){ if(pageResult==null){ pageResult = new PageResult<T>(); } pageResult.setCurrent(page.getPageNo()); pageResult.setSuccess(true); pageResult.setData(page.getResult()); pageResult.setPageSize(page.getPageSize()); pageResult.setTotal(Integer.parseInt(page.getTotalItems()+"")); } return pageResult; } }
Page<T> page = new Page<T>(); Integer current = pageResult.getCurrent(); if(current==null){ current=1; } Integer pageSize = pageResult.getPageSize(); if(pageSize==null){ pageSize = 10; } page.setPageNo(current); page.setPageSize(pageSize); return page;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/ipaddr/IPService.java
IPService
getIp
class IPService { @Autowired private IPLocationService ipLocationService; public IPLocation getIpLocation(String ip) { if(ip==null){ return null; } try{ return ipLocationService.getLocationByIp(ip); }catch (Exception e){ e.printStackTrace(); } return null; } /** * 根据ip取得所在地区 * @param ip * @return */ public String getCountry(String ip) { if(ip==null){ return ""; } return ipLocationService.getLocationByIp(ip).getProvince(); } /** * 根据IP,查出此ip所在的城市 * * @param ip * @return */ public String getCurCity(String ip) { //空实现 return null; } /** * * @param country * @return */ public String getCurCityByCountry(String country) { return null; } public String getIp(HttpServletRequest request) {<FILL_FUNCTION_BODY>} /** * 检查以localhost,127.0.0.1访问时得到真实IP * @param ip * @return */ public String checkLocalIp(String ip){ if("0:0:0:0:0:0:0:1".equals(ip) || "127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1%0".equals(ip)){ try { InetAddress inetAddress = InetAddress.getLocalHost(); ip=inetAddress.getHostAddress(); if(ip!=null && ip.length()>15){ //"***.***.***.***".length() = 15 if(ip.indexOf(",")>0){ ip = ip.substring(0,ip.indexOf(",")); } } } catch (UnknownHostException e) { // e.printStackTrace();2019000MA6TG48K } } return ip; } public String replaceIPv6LocalIp(String ip){ if("0:0:0:0:0:0:0:1".equals(ip)){ ip="127.0.0.1"; } return ip; } }
//Http Header:X-Forwarded-For String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } // ip=replaceIPv6LocalIp(ip); ip=checkLocalIp(ip); if(ip!=null && ip.indexOf(",")>0){ ip=ip.substring(0,ip.indexOf(",")); } return ip;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/jcaptcha/CaptchaEngineEx.java
CaptchaEngineEx
buildInitialFactories
class CaptchaEngineEx extends ListImageCaptchaEngine { /*protected void buildInitialFactories() { int minWordLength = 4; int maxWordLength = 5; int fontSize = 50; int imageWidth = 250; int imageHeight = 100; WordGenerator wordGenerator = new RandomWordGenerator( "0123456789abcdefghijklmnopqrstuvwxyz"); TextPaster randomPaster = new DecoratedRandomTextPaster(minWordLength, maxWordLength, new RandomListColorGenerator(new Color[] { new Color(23, 170, 27), new Color(220, 34, 11), new Color(23, 67, 172) }), new TextDecorator[] {}); BackgroundGenerator background = new UniColorBackgroundGenerator( imageWidth, imageHeight, Color.white); FontGenerator font = new RandomFontGenerator(fontSize, fontSize, new Font[] { new Font("nyala", Font.BOLD, fontSize), new Font("Bell MT", Font.PLAIN, fontSize), new Font("Credit valley", Font.BOLD, fontSize) }); ImageDeformation postDef = new ImageDeformationByFilters( new ImageFilter[] {}); ImageDeformation backDef = new ImageDeformationByFilters( new ImageFilter[] {}); ImageDeformation textDef = new ImageDeformationByFilters( new ImageFilter[] {}); WordToImage word2image = new DeformedComposedWordToImage(font, background, randomPaster, backDef, textDef, postDef); addFactory(new GimpyFactory(wordGenerator, word2image)); }*/ protected void buildInitialFactories() {<FILL_FUNCTION_BODY>} }
int minWordLength = 4; int maxWordLength = 5; /*int fontSize = 50; int imageWidth = 250; int imageHeight = 100;*/ int fontSize = 30; int imageWidth = 120; int imageHeight = 50; WordGenerator dictionnaryWords = new ComposeDictionaryWordGenerator(new FileDictionary("toddlist")); // word2image components TextPaster randomPaster = new DecoratedRandomTextPaster(minWordLength, maxWordLength, new RandomListColorGenerator(new Color[] { new Color(23, 170, 27), new Color(220, 34, 11), new Color(23, 67, 172) }), new TextDecorator[] {}); BackgroundGenerator background = new UniColorBackgroundGenerator( imageWidth, imageHeight, Color.white); // ColorGenerator colorGenerator=new RandomListColorGenerator(new Color[]{new Color(235, 234, 235),new Color(255, 255, 255)}); // BackgroundGenerator background=new FunkyBackgroundGenerator(imageWidth, imageHeight,colorGenerator); FontGenerator font = new RandomFontGenerator(fontSize, fontSize, new Font[] { new Font("nyala", Font.BOLD, fontSize), new Font("Bell MT", Font.PLAIN, fontSize), new Font("Credit valley", Font.BOLD, fontSize) }); ImageDeformation postDef = new ImageDeformationByFilters( new ImageFilter[] {}); ImageDeformation backDef = new ImageDeformationByFilters( new ImageFilter[] {}); ImageDeformation textDef = new ImageDeformationByFilters( new ImageFilter[] {}); WordToImage word2image = new DeformedComposedWordToImage(font, background, randomPaster, backDef, textDef, postDef); addFactory(new GimpyFactory(dictionnaryWords, word2image));
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/mapper/CollectionMapper.java
CollectionMapper
extractToMap
class CollectionMapper { /** * 提取集合中的对象的属性(通过Getter函数), 组合成Map. * * @param collection 来源集合. * @param keyPropertyName 要提取为Map中的Key值的属性名. * @param valuePropertyName 要提取为Map中的Value值的属性名. */ public static Map extractToMap(final Collection collection, final String keyPropertyName, final String valuePropertyName) {<FILL_FUNCTION_BODY>} /** * 提取集合中的对象的属性(通过Getter函数), 组合成List. * * @param collection 来源集合. * @param propertyName 要提取的属性名. */ public static List extractToList(final Collection collection, final String propertyName) { List list = new ArrayList(); try { for (Object obj : collection) { list.add(PropertyUtils.getProperty(obj, propertyName)); } } catch (Exception e) { throw ReflectionUtils.convertReflectionExceptionToUnchecked(e); } return list; } /** * 提取集合中的对象的属性(通过Getter函数), 组合成由分割符分隔的字符串. * * @param collection 来源集合. * @param propertyName 要提取的属性名. * @param separator 分隔符. */ public static String extractToString(final Collection collection, final String propertyName, final String separator) { List list = extractToList(collection, propertyName); return StringUtils.join(list, separator); } }
Map map = new HashMap(); try { for (Object obj : collection) { map.put(PropertyUtils.getProperty(obj, keyPropertyName), PropertyUtils.getProperty(obj, valuePropertyName)); } } catch (Exception e) { throw ReflectionUtils.convertReflectionExceptionToUnchecked(e); } return map;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/mapper/ImprovedNamingStrategy.java
ImprovedNamingStrategy
convert
class ImprovedNamingStrategy implements PhysicalNamingStrategy { @Override public Identifier toPhysicalCatalogName(Identifier identifier, JdbcEnvironment jdbcEnvironment) { return convert(identifier); } @Override public Identifier toPhysicalSchemaName(Identifier identifier, JdbcEnvironment jdbcEnvironment) { return convert(identifier); } @Override public Identifier toPhysicalTableName(Identifier identifier, JdbcEnvironment jdbcEnvironment) { return convert(identifier); } @Override public Identifier toPhysicalSequenceName(Identifier identifier, JdbcEnvironment jdbcEnvironment) { return convert(identifier); } @Override public Identifier toPhysicalColumnName(Identifier identifier, JdbcEnvironment jdbcEnvironment) { return convert(identifier); } private Identifier convert(Identifier identifier) {<FILL_FUNCTION_BODY>} }
if (identifier == null || StringUtils.isBlank(identifier.getText())) { return identifier; } String regex = "([a-z])([A-Z])"; String replacement = "$1_$2"; String newName = identifier.getText().replaceAll(regex, replacement).toLowerCase(); return Identifier.toIdentifier(newName);
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/mapper/ObjectMapper.java
ObjectMapper
convertToObject
class ObjectMapper { /** * 持有Dozer单例, 避免重复创建DozerMapper消耗资源. */ private static DozerBeanMapper dozer = new DozerBeanMapper(); /** * 基于Dozer转换对象的类型. */ public static <T> T map(Object source, Class<T> destinationClass) { return dozer.map(source, destinationClass); } /** * 基于Dozer转换Collection中对象的类型. */ public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass) { List<T> destinationList = Lists.newArrayList(); for (Object sourceObject : sourceList) { T destinationObject = dozer.map(sourceObject, destinationClass); destinationList.add(destinationObject); } return destinationList; } static { //初始化日期格式为yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss registerDateConverter("yyyy-MM-dd,yyyy-MM-dd HH:mm:ss"); } /** * 定义Apache BeanUtils日期Converter的格式,可注册多个格式,以','分隔 */ public static void registerDateConverter(String patterns) { DateConverter dc = new DateConverter(); dc.setUseLocaleFormat(true); dc.setPatterns(StringUtils.split(patterns, ",")); ConvertUtils.register(dc, Date.class); } /** * 基于Apache BeanUtils转换字符串到相应类型. * * @param value 待转换的字符串. * @param toType 转换目标类型. */ public static Object convertToObject(String value, Class<?> toType) {<FILL_FUNCTION_BODY>} }
Object cvt_value=null; try { cvt_value=ConvertUtils.convert(value, toType); // if(toType==Date.class){ // SimpleDateFormat dateFormat=null; // try{ // dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // cvt_value=dateFormat.parse(value); // }catch(Exception e){ // dateFormat=new SimpleDateFormat("yyyy-MM-dd"); // cvt_value=dateFormat.parse(value); // } // } } catch (Exception e) { throw ReflectionUtils.convertReflectionExceptionToUnchecked(e); } return cvt_value;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/mapper/PhysicalNamingStrategyImpl.java
PhysicalNamingStrategyImpl
addUnderscores
class PhysicalNamingStrategyImpl extends PhysicalNamingStrategyStandardImpl implements Serializable { public static final PhysicalNamingStrategyImpl INSTANCE = new PhysicalNamingStrategyImpl(); @Override public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) { return new Identifier(addUnderscores(name.getText()), name.isQuoted()); } @Override public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment context) { return new Identifier(addUnderscores(name.getText()), name.isQuoted()); } protected static String addUnderscores(String name) {<FILL_FUNCTION_BODY>} }
final StringBuilder buf = new StringBuilder( name.replace('.', '_') ); for (int i=1; i<buf.length()-1; i++) { if ( Character.isLowerCase( buf.charAt(i-1) ) && Character.isUpperCase( buf.charAt(i) ) && Character.isLowerCase( buf.charAt(i+1) ) ) { buf.insert(i++, '_'); } } return buf.toString().toLowerCase(Locale.ROOT);
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/page/Page.java
Page
setStartEndPageNo
class Page<T> extends PageRequest implements Iterable<T> { protected List<T> result = null; protected long totalItems = -1; public Page() { } public Page(PageRequest request) { this.pageNo = request.pageNo; this.pageSize = request.pageSize; this.countTotal = request.countTotal; this.orderBy = request.orderBy; this.orderDir = request.orderDir; } /** * 获得页内的记录列表. */ public List<T> getResult() { return result; } /** * 设置页内的记录列表. */ public void setResult(final List<T> result) { this.result = result; } /** * 获得总记录数, 默认值为-1. */ public long getTotalItems() { return totalItems; } /** * 设置总记录数. */ public void setTotalItems(final long totalItems) { this.totalItems = totalItems; // getSlider(this.pageNoSize); setStartEndPageNo(); } /** * 实现Iterable接口, 可以for(Object item : page)遍历使用 */ @Override public Iterator<T> iterator() { return result.iterator(); } /** * 根据pageSize与totalItems计算总页数. */ public int getTotalPages() { return (int) Math.ceil((double) totalItems / (double) getPageSize()); } /** * 是否还有下一页. */ public boolean hasNextPage() { return (getPageNo() + 1 <= getTotalPages()); } /** * 是否最后一页. */ public boolean isLastPage() { return !hasNextPage(); } /** * 取得下页的页号, 序号从1开始. * 当前页为尾页时仍返回尾页序号. */ public int getNextPage() { if (hasNextPage()) { return getPageNo() + 1; } else { return getPageNo(); } } /** * 是否还有上一页. */ public boolean hasPrePage() { return (getPageNo() > 1); } /** * 是否第一页. */ public boolean isFirstPage() { return !hasPrePage(); } /** * 取得上页的页号, 序号从1开始. * 当前页为首页时返回首页序号. */ public int getPrePage() { if (hasPrePage()) { return getPageNo() - 1; } else { return getPageNo(); } } /** * 计算以当前页为中心的页面列表,如"首页,23,24,25,26,27,末页" * @param count 需要计算的列表大小 * @return pageNo列表 */ public List<Integer> getSlider(int count) { int halfSize = count / 2; totalPage = getTotalPages(); int startPageNo = Math.max(getPageNo() - halfSize, 1); int endPageNo = Math.min(startPageNo + count - 1, totalPage); if (endPageNo - startPageNo < count) { startPageNo = Math.max(endPageNo - count, 1); } List<Integer> result = Lists.newArrayList(); for (int i = startPageNo; i <= endPageNo; i++) { result.add(i); } this.pageNos=result; return result; } private int startpage; private int endpage; public void setStartEndPageNo(){<FILL_FUNCTION_BODY>} public int getStartpage() { return startpage; } public void setStartpage(int startpage) { this.startpage = startpage; } public int getEndpage() { return endpage; } public void setEndpage(int endpage) { this.endpage = endpage; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
totalPage = getTotalPages(); startpage = pageNo - (pageNoSize % 2 == 0 ? pageNoSize / 2 - 1 : pageNoSize / 2); endpage = pageNo + pageNoSize / 2; if (startpage < 1) { startpage = 1; if (totalPage >= pageNoSize) { endpage = pageNoSize; } else { endpage = totalPage; } } if (endpage > totalPage) { endpage = totalPage; if ((endpage - pageNoSize) > 0) { startpage = endpage - pageNoSize + 1; } else { startpage = 1; } } // return new PageIndexUtil(startpage, endpage);
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/page/PageRequest.java
PageRequest
getSort
class PageRequest { protected int pageNo = 1; protected int pageSize = 10; protected String orderBy = null; protected String orderDir = null; protected boolean countTotal = true; protected List<Integer> pageNos; protected int pageNoSize = 5; public PageRequest() { } public PageRequest(int pageNo, int pageSize) { this.pageNo = pageNo; this.pageSize = pageSize; } /** * 获得当前页的页号, 序号从1开始, 默认为1. */ public int getPageNo() { return pageNo; } /** * 设置当前页的页号, 序号从1开始, 低于1时自动调整为1. */ public void setPageNo(final int pageNo) { this.pageNo = pageNo; if (pageNo < 1) { this.pageNo = 1; } } /** * 获得每页的记录数量, 默认为10. */ public int getPageSize() { return pageSize; } /** * 设置每页的记录数量, 低于1时自动调整为1. */ public void setPageSize(final int pageSize) { this.pageSize = pageSize; if (pageSize < 1) { this.pageSize = 1; } } /** * 获得排序字段, 无默认值. 多个排序字段时用','分隔. */ public String getOrderBy() { return orderBy; } /** * 设置排序字段, 多个排序字段时用','分隔. */ public void setOrderBy(final String orderBy) { this.orderBy = orderBy; } /** * 获得排序方向, 无默认值. */ public String getOrderDir() { return orderDir; } /** * 设置排序方式向. * * @param orderDir * 可选值为desc或asc,多个排序字段时用','分隔. */ public void setOrderDir(final String orderDir) { String lowcaseOrderDir = StringUtils.lowerCase(orderDir); // 检查order字符串的合法值 String[] orderDirs = StringUtils.split(lowcaseOrderDir, ','); for (String orderDirStr : orderDirs) { if (!StringUtils.equals(Sort.DESC, orderDirStr) && !StringUtils.equals(Sort.ASC, orderDirStr)) { throw new IllegalArgumentException("排序方向" + orderDirStr + "不是合法值"); } } this.orderDir = lowcaseOrderDir; } /** * 获得排序参数. */ public List<Sort> getSort() {<FILL_FUNCTION_BODY>} /** * 是否已设置排序字段,无默认值. */ public boolean isOrderBySetted() { return (StringUtils.isNotBlank(orderBy) && StringUtils .isNotBlank(orderDir)); } /** * 是否默认计算总记录数. */ public boolean isCountTotal() { return countTotal; } /** * 设置是否默认计算总记录数. */ public void setCountTotal(boolean countTotal) { this.countTotal = countTotal; } /** * 根据pageNo和pageSize计算当前页第一条记录在总结果集中的位置, 序号从0开始. */ public int getOffset() { return ((pageNo - 1) * pageSize); } public static class Sort { public static final String ASC = "asc"; public static final String DESC = "desc"; private final String property; private final String dir; public Sort(String property, String dir) { this.property = property; this.dir = dir; } public String getProperty() { return property; } public String getDir() { return dir; } } public List<Integer> getPageNos() { return pageNos; } public void setPageNoSize(int pageNoSize) { this.pageNoSize = pageNoSize; } // 总页数 protected int totalPage; public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } // 是否取最后一页数据 private boolean islastpage=false; public boolean isIslastpage() { return islastpage; } public void setIslastpage(boolean islastpage) { this.islastpage = islastpage; } }
String[] orderBys = StringUtils.split(orderBy, ','); String[] orderDirs = StringUtils.split(orderDir, ','); AssertUtils.isTrue(orderBys.length == orderDirs.length, "分页多重排序参数中,排序字段与排序方向的个数不相等"); List<Sort> orders = Lists.newArrayList(); for (int i = 0; i < orderBys.length; i++) { orders.add(new Sort(orderBys[i], orderDirs[i])); } return orders;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/security/ShiroDbRealm.java
ShiroDbRealm
doGetAuthenticationInfo
class ShiroDbRealm extends AuthorizingRealm { @Autowired protected AccountManager accountManager; public ShiroDbRealm() { setCredentialsMatcher(new HashedCredentialsMatcher("SHA-1")); } /** * 认证回调函数,登录时调用. */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {<FILL_FUNCTION_BODY>} /** * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用. */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String username = (String) principals.fromRealm(getName()).iterator().next(); // User user = accountManager.findUserByLoginName(username); User user = accountManager.findUserByLoginNameOrEmail(username); if(user!=null){ SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); if ("1".equals(user.getId())) { info.addRole(RoleCode.DWSURVEY_SUPER_ADMIN); } return info; } return null; } /** * 更新用户授权信息缓存. */ public void clearCachedAuthorizationInfo(String principal) { SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName()); clearCachedAuthorizationInfo(principals); } }
UsernamePasswordToken token = (UsernamePasswordToken) authcToken; // User user = accountManager.findUserByLoginName(token.getUsername()); //根据loginToken 看能不查到当前token token有效期就1分钟 String tokenPassword=new String(token.getPassword()); User user = accountManager.findUserByLoginNameOrEmail(token.getUsername()); //user.getStandardLock()==1 if (user != null && user.getStatus().intValue()!=0 && (user.getVisibility()==null || user.getVisibility()==1 )) { return new SimpleAuthenticationInfo(user.getLoginName(), user.getShaPassword() , getName()); } else { return null; }
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/security/filter/FormAuthenticationWithLockFilter.java
FormAuthenticationWithLockFilter
decreaseAccountLoginAttempts
class FormAuthenticationWithLockFilter extends FormAuthenticationFilter { Log log=LogFactory.getLog(FormAuthenticationWithLockFilter.class); private long maxLoginAttempts = 10; public static ConcurrentHashMap<String, AtomicLong> accountLockMap = new ConcurrentHashMap<String, AtomicLong>(); private String successAdminUrl; private String successAdminRole; @Autowired protected AccountManager accountManager; @Override public boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception { AuthenticationToken token = createToken(request, response); if (token == null) { String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " + "must be created in order to execute a login attempt."; throw new IllegalStateException(msg); } if (checkIfAccountLocked(request)) { return onLoginFailure(token, new ExcessiveAttemptsException(), request, response); } else { if (!doLogin(request, response, token)) { resetAccountLock(getUsername(request)); return false; } return true; } } public boolean checkIfAccountLocked(ServletRequest request) { String username = getUsername(request); if (username!=null && accountLockMap.get((String) username) != null) { long remainLoginAttempts = accountLockMap.get((String) username).get(); if (remainLoginAttempts <= 0) { return true; } } return false; } private boolean doLogin(ServletRequest request, ServletResponse response, AuthenticationToken token) throws Exception { try { Subject subject = getSubject(request, response); subject.login(token); // User user = accountManager.findUserByLoginName(getUsername(request)); User user = accountManager.findUserByLoginNameOrEmail(getUsername(request)); user.setLastLoginTime(new Date()); accountManager.saveUp(user); return onLoginSuccess(token, subject, request, response); } catch (IncorrectCredentialsException e) { decreaseAccountLoginAttempts(request); checkIfAccountLocked(request); return onLoginFailure(token, e, request, response); } catch (AuthenticationException e) { return onLoginFailure(token, e, request, response); } } public void decreaseAccountLoginAttempts(ServletRequest request) {<FILL_FUNCTION_BODY>} public void resetAccountLock(String username) { accountLockMap.put(username, new AtomicLong(maxLoginAttempts)); } public void setMaxLoginAttempts(long maxLoginAttempts) { this.maxLoginAttempts = maxLoginAttempts; } public void setSuccessAdminUrl(String successAdminUrl) { this.successAdminUrl = successAdminUrl; } public void setSuccessAdminRole(String successAdminRole) { this.successAdminRole = successAdminRole; } /* 得到某个账号还可以登录次数 */ public Long getAccountLocked(String username){ long remainLoginAttempts=0; if (username!=null && accountLockMap.get((String) username) != null) { remainLoginAttempts = accountLockMap.get((String) username).get(); } return remainLoginAttempts+1; } /* 重写登录失败,加入了失败时还可以重试的次数信息 */ @Override protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { request.setAttribute("remainLoginAttempt", getAccountLocked(getUsername(request))); return super.onLoginFailure(token, e, request, response); } @Override protected String getUsername(ServletRequest request) { // TODO Auto-generated method stub String username = super.getUsername(request); if(username==null){ Object temp=request.getAttribute(getUsernameParam()); username=temp!=null?temp.toString():null; } return username; } @Override protected String getPassword(ServletRequest request) { String password = super.getPassword(request); if(password==null){ Object temp=request.getAttribute(getPasswordParam()); password=temp!=null?temp.toString():null; } return password; } @Override protected boolean isRememberMe(ServletRequest request) { // TODO Auto-generated method stub return super.isRememberMe(request); } }
AtomicLong initValue = new AtomicLong(maxLoginAttempts); AtomicLong remainLoginAttempts = accountLockMap.putIfAbsent(getUsername(request), new AtomicLong(maxLoginAttempts)); if (remainLoginAttempts == null) { remainLoginAttempts = initValue; } remainLoginAttempts.getAndDecrement(); accountLockMap.put(getUsername(request), remainLoginAttempts);
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/security/filter/MyRolesAuthorizationFilter.java
MyRolesAuthorizationFilter
onAccessDenied
class MyRolesAuthorizationFilter extends RolesAuthorizationFilter { @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {<FILL_FUNCTION_BODY>} }
Subject subject = this.getSubject(request, response); if (subject.getPrincipal() == null) { // this.saveRequestAndRedirectToLogin(request, response); WebUtils.toHttp(response).sendError(401); } else { String unauthorizedUrl = this.getUnauthorizedUrl(); if (StringUtils.hasText(unauthorizedUrl)) { WebUtils.issueRedirect(request, response, unauthorizedUrl); } else { WebUtils.toHttp(response).sendError(403); } } return false;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/security/filter/MyUserFilter.java
MyUserFilter
redirectToLogin
class MyUserFilter extends UserFilter { @Override protected boolean isAccessAllowed(ServletRequest request,ServletResponse response, Object mappedValue) { return super.isAccessAllowed(request,response,mappedValue); } @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { return super.onAccessDenied(request, response); } @Override protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {<FILL_FUNCTION_BODY>} }
// super.redirectToLogin(request, response); response.setCharacterEncoding("utf-8"); response.setContentType("application/json; charset=utf-8"); PrintWriter writer = response.getWriter(); try { HttpResult httpResult = HttpResult.buildResult(HttpStatus.NOLOGIN); JSONObject responseJSONObject = JSONObject.fromObject(httpResult); writer.write(responseJSONObject.toString()); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } }
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/web/Token.java
Token
getToken
class Token { /*** * 设置令牌 * @param request */ public static void setToken(HttpServletRequest request){ request.getSession().setAttribute("sessionToken", UUID.randomUUID().toString() ); } public static String getToken(HttpServletRequest request){<FILL_FUNCTION_BODY>} /*** * 验证是否为重复提交 * @param request * @return String true非重复提交,false重复提交,error非法操作 */ public static boolean validToken(HttpServletRequest request){ String sessionToken = (String)request.getSession().getAttribute("sessionToken"); String requestToken = request.getParameter("sessionToken"); // System.out.println("sessionToken1:"+sessionToken); // System.out.println("requestToken1:"+requestToken); if(null == sessionToken || "null".equals(sessionToken)){ sessionToken = ""; } if(null == requestToken || "null".equals(requestToken) ){ requestToken = ""; } if(sessionToken.equals(requestToken)){ //返回前一定要重置session中的SesToken request.getSession().setAttribute("sessionToken",UUID.randomUUID().toString() ); //非重复提交 return true; }else{ //返回前一定要重置session中的SesToken request.getSession().setAttribute("sessionToken", UUID.randomUUID().toString() ); //重复提交 return false; } } }
String sessionToken = (String)request.getSession().getAttribute("sessionToken"); if(null == sessionToken || "".equals(sessionToken)){ sessionToken = UUID.randomUUID().toString(); request.getSession().setAttribute("sessionToken",sessionToken ); //把这个sessionToken保存在redis中 //然后判断的时候根据redis是否有这个sessionToken,有看是不是使用过,使用过不能可以用 } return sessionToken;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/xss/esapi/ManageSecurityFilter.java
ManageSecurityFilter
doFilter
class ManageSecurityFilter implements Filter { private static final String FILTER_APPLIED = ManageSecurityFilter.class.getName() + ".FILTERED"; private Set<String> excludePathRegex = new HashSet<String>(); public void setExcludePathRegex(Set<String> excludePathRegex) { this.excludePathRegex = excludePathRegex; } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>} @Override public void destroy() { } }
if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { throw new ServletException("XSSFilter just supports HTTP requests"); } HttpServletRequest httpRequest = (HttpServletRequest) request; String uri = httpRequest.getRequestURI(); for (String regex : excludePathRegex) { if (uri.matches(regex)) { chain.doFilter(request, response); return; } } // Apply Filter if (null != httpRequest.getAttribute(FILTER_APPLIED)) { chain.doFilter(request, response); return; } try { request.setAttribute(FILTER_APPLIED, Boolean.TRUE); SecurityRequestWrapper requestWrapper = new SecurityRequestWrapper(httpRequest); chain.doFilter(requestWrapper, response); } finally { httpRequest.removeAttribute(FILTER_APPLIED); }
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/plugs/zxing/ZxingUtil.java
ZxingUtil
qRCodeCommon
class ZxingUtil { public static BufferedImage qRCodeCommon(String content, String imgType, int size){<FILL_FUNCTION_BODY>} }
int imgSize = 67 + 12 * (size - 1); Hashtable hints = new Hashtable(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); hints.put(EncodeHintType.MARGIN, 2); try{ BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, imgSize, imgSize, hints); return MatrixToImageWriter.toBufferedImage(bitMatrix); }catch (WriterException e){ e.printStackTrace(); } return null;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/service/BaseServiceImpl.java
BaseServiceImpl
getBaseDao
class BaseServiceImpl<T extends IdEntity, ID extends Serializable> implements BaseService<T, ID> { protected BaseDao<T, ID> baseDao; protected BaseDao<T, ID> getBaseDao() {<FILL_FUNCTION_BODY>} @Override public void save(T t) { String id = t.getId(); if (id != null && "".equals(id)) { t.setId(null); } getBaseDao().save(t); } @Override public void delete(T t) { getBaseDao().delete(t); } public void delete(ID id) { getBaseDao().delete(get(id)); }; public T get(ID id) { return getBaseDao().get(id); } public T getModel(ID id) { return getBaseDao().getModel(id); }; @Override public T findById(ID id) { return getBaseDao().findUniqueBy("id",id); } @Override public List<T> findList(Criterion... criterions) { return getBaseDao().find(criterions); } @Override public Page<T> findPage(Page<T> page, Criterion... criterions) { return getBaseDao().findPage(page, criterions); } public Page<T> findPageByCri(Page<T> page, List<Criterion> criterions) { return getBaseDao().findPageByCri(page, criterions); } }
if (baseDao == null) { setBaseDao(); } return baseDao;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/BuildHtml.java
BuildHtml
writeLocal
class BuildHtml { /** * 内容输入到本地 * @param fileName * @param fileRealPath * @param os * @throws IOException * @throws FileNotFoundException */ public static File writeLocal(String fileName, String fileRealPath, final ByteArrayOutputStream os) throws IOException, FileNotFoundException {<FILL_FUNCTION_BODY>} }
File file2 = new File(fileRealPath); if (!file2.exists() || !file2.isDirectory()) { file2.mkdirs(); } File file = new File(fileRealPath + fileName); if (!file.exists()) { file.createNewFile(); } FileOutputStream fos = new FileOutputStream(file); os.writeTo(fos); fos.close(); return file;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/CookieUtils.java
CookieUtils
getCookie
class CookieUtils { /** * 添加cookie * * @param response * @param name * Cookie的名称,不能为null * @param value * Cookie的值,默认值空字符串 * @param maxAge * @param path * 默认值'/' */ public static void addCookie(HttpServletResponse response, String name, String value, Integer maxAge, String path) { if (value == null) { value = ""; } if (path == null) { path = "/"; } Cookie cookie = new Cookie(name, value); cookie.setPath(path); if (maxAge != null) { cookie.setMaxAge(maxAge); } response.addCookie(cookie); } /** * 设置cookie * * @param response * @param name * cookie名字 * @param value * cookie值 * @param maxAge * cookie生命周期 以秒为单位 */ public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) { Cookie cookie = new Cookie(name, value); cookie.setPath("/"); if (maxAge > 0) cookie.setMaxAge(maxAge); response.addCookie(cookie); } /** * @param request * @param cookieName * @return 指定的cookie */ public static Cookie getCookie(HttpServletRequest request, String cookieName) {<FILL_FUNCTION_BODY>} }
Cookie[] cookies = request.getCookies(); if (cookies == null) { return null; } for (Cookie c : cookies) { if (c.getName().equals(cookieName)) { return c; } } return null;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/DiaowenProperty.java
DiaowenProperty
processProperties
class DiaowenProperty extends PropertyPlaceholderConfigurer { public static String STORAGE_URL_PREFIX = null; public static String SURVEYURL_MODE = "auto"; public static String WEBSITE_URL = "http://192.168.3.20:8080/#"; // private static Map<String, String> ctxPropertiesMap; public static String LICENSE_DESC = null; public static String LICENSE_ORGAN = null; public static String LICENSE_EMAIL = null; public static String LICENSE_TYPENAME = null; public static String LICENSE_DOMAIN = null; public static String LICENSE_CREATIONDATE = null; public static String LICENSE_SERVERID = null; public static String LICENSE_ID = null; public static String LICENSE_VERSION = null; public static String LICENSE_EVALUATION = null; public static String LICENSE_PUBLICKEY = null; public static String LICENSE_SIGN = null; @Override protected void processProperties( ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {<FILL_FUNCTION_BODY>} /* public static String getContextProperty(String name) { return ctxPropertiesMap.get(name); } */ public void diaowenInit(){ } }
super.processProperties(beanFactoryToProcess, props); /*STORAGE_URL_PREFIX = props.getProperty("dw.storage.url_prefix"); SURVEYURL_MODE = props.getProperty("dw.surveyurl.mode"); WEBSITE_URL = props.getProperty("dw.website.url"); LICENSE_DESC = props.getProperty("dw.license.description"); LICENSE_ORGAN = props.getProperty("dw.license.organisation"); LICENSE_EMAIL = props.getProperty("dw.license.email"); LICENSE_TYPENAME = props.getProperty("dw.license.licenseTypeName"); LICENSE_CREATIONDATE = props.getProperty("dw.license.creationDate"); LICENSE_DOMAIN = props.getProperty("dw.license.licenseDomain"); LICENSE_SERVERID = props.getProperty("dw.license.serverId"); LICENSE_ID = props.getProperty("dw.license.licenseId"); LICENSE_VERSION = props.getProperty("dw.license.licenseVersion"); LICENSE_EVALUATION = props.getProperty("dw.license.evaluation"); LICENSE_PUBLICKEY = props.getProperty("dw.license.publickey"); LICENSE_SIGN = props.getProperty("dw.license.sign"); */ /* ctxPropertiesMap = new HashMap<String, String>(); for (Object key : props.keySet()) { String keyStr = key.toString(); String value = props.getProperty(keyStr); ctxPropertiesMap.put(keyStr, value); } */
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/DwWriteFile.java
DwWriteFile
writeOS
class DwWriteFile { /** * OS写到文件 * @param fileName * @param fileRealPath * @param os * @throws IOException * @throws FileNotFoundException */ public static File writeOS(String fileName, String fileRealPath, final ByteArrayOutputStream os) throws IOException, FileNotFoundException {<FILL_FUNCTION_BODY>} }
fileRealPath = fileRealPath.substring(fileRealPath.lastIndexOf("/wjHtml")+1); // fileRealPath = "/Users/xiajunlanna/IdeaProjects/dwsurvey/target/"+fileRealPath; fileRealPath = DWSurveyConfig.DWSURVEY_WEB_FILE_PATH+fileRealPath; File file = new File(fileRealPath); if (!file.isDirectory() || !file.exists()) { file.mkdirs(); } File newFile = new File(fileRealPath + fileName); if (!newFile.exists()) { newFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(newFile); os.writeTo(fos); fos.close(); return newFile;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/DwsUtils.java
DwsUtils
downloadFile
class DwsUtils { public static String BASEURL_DEFAULT = "http://www.surveyform.cn"; public static String baseUrl(HttpServletRequest request){ String baseUrl = ""; baseUrl = request.getScheme() +"://" + request.getServerName() + (request.getServerPort() == 80 || request.getServerPort() == 443 ? "" : ":" +request.getServerPort()) + request.getContextPath(); return baseUrl; } public static Date str2Date(String date){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { return simpleDateFormat.parse(date); } catch (ParseException e) { e.printStackTrace(); } return null; } public static void downloadFile(HttpServletResponse response, String fileName, String downFilePath) throws IOException {<FILL_FUNCTION_BODY>} }
downFilePath = downFilePath.replace("/", File.separator); downFilePath = downFilePath.replace("\\", File.separator); response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8")); FileInputStream in = new FileInputStream(downFilePath); //创建输出流 OutputStream out = response.getOutputStream(); //创建缓冲区 byte buffer[] = new byte[1024]; int len = 0; //循环将输入流中的内容读取到缓冲区当中 while((len=in.read(buffer))>0){ //输出缓冲区的内容到浏览器,实现文件下载 out.write(buffer, 0, len); } //关闭文件输入流 in.close(); //关闭输出流 out.close();
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/EncodeUtils.java
EncodeUtils
urlDecode
class EncodeUtils { private static final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private static final String DEFAULT_URL_ENCODING = "UTF-8"; /** * Hex编码, byte[]->String. */ public static String encodeHex(byte[] input) { return Hex.encodeHexString(input); } /** * Hex解码, String->byte[]. */ public static byte[] decodeHex(String input) { try { return Hex.decodeHex(input.toCharArray()); } catch (DecoderException e) { throw new IllegalStateException("Hex Decoder exception", e); } } /** * Base64编码, byte[]->String. */ public static String encodeBase64(byte[] input) { return Base64.encodeBase64String(input); } /** * Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548). */ public static String encodeUrlSafeBase64(byte[] input) { return Base64.encodeBase64URLSafeString(input); } /** * Base64解码, String->byte[]. */ public static byte[] decodeBase64(String input) { return Base64.decodeBase64(input); } /** * Base62(0_9A_Za_z)编码数字, long->String. */ public static String encodeBase62(long num) { return alphabetEncode(num, 62); } /** * Base62(0_9A_Za_z)解码数字, String->long. */ public static long decodeBase62(String str) { return alphabetDecode(str, 62); } private static String alphabetEncode(long num, int base) { num = Math.abs(num); StringBuilder sb = new StringBuilder(); for (; num > 0; num /= base) { sb.append(ALPHABET.charAt((int) (num % base))); } return sb.toString(); } private static long alphabetDecode(String str, int base) { AssertUtils.hasText(str); long result = 0; for (int i = 0; i < str.length(); i++) { result += ALPHABET.indexOf(str.charAt(i)) * Math.pow(base, i); } return result; } /** * URL 编码, Encode默认为UTF-8. */ public static String urlEncode(String part) { try { return URLEncoder.encode(part, DEFAULT_URL_ENCODING); } catch (UnsupportedEncodingException e) { throw ExceptionUtils.unchecked(e); } } /** * URL 解码, Encode默认为UTF-8. */ public static String urlDecode(String part) {<FILL_FUNCTION_BODY>} /** * Html 转码. */ public static String htmlEscape(String html) { return StringEscapeUtils.escapeHtml(html); } /** * Html 解码. */ public static String htmlUnescape(String htmlEscaped) { return StringEscapeUtils.unescapeHtml(htmlEscaped); } /** * Xml 转码. */ public static String xmlEscape(String xml) { return StringEscapeUtils.escapeXml(xml); } /** * Xml 解码. */ public static String xmlUnescape(String xmlEscaped) { return StringEscapeUtils.unescapeXml(xmlEscaped); } }
try { return URLDecoder.decode(part, DEFAULT_URL_ENCODING); } catch (UnsupportedEncodingException e) { throw ExceptionUtils.unchecked(e); }
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/ExceptionUtils.java
ExceptionUtils
unchecked
class ExceptionUtils { /** * 将CheckedException转换为UnCheckedException. */ public static RuntimeException unchecked(Exception e) {<FILL_FUNCTION_BODY>} }
if (e instanceof RuntimeException) { return (RuntimeException) e; } return new RuntimeException(e.getMessage(), e);
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/HttpRequest.java
HttpRequest
sendGet
class HttpRequest { /** * 向指定URL发送GET方法的请求 * * @param url * 发送请求的URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return URL 所代表远程资源的响应结果 */ public static String sendGet(String url, String param) {<FILL_FUNCTION_BODY>} /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */ public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } //使用finally块来关闭输出流、输入流 finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return result; } }
String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/IpUtils.java
IpUtils
getIpNum
class IpUtils { public static String[] getIps(String ips){ String[] ip2 = ips.split("/"); String ip0 = ip2[0]; String ip1 = ip0.substring(0,ip0.lastIndexOf(".")+1)+ip2[1]; return new String[]{ip0,ip1}; } public static long getIpNum(String ipAddress){<FILL_FUNCTION_BODY>} }
String[] ip = ipAddress.split("\\."); long a = Integer.parseInt(ip[0]); long b = Integer.parseInt(ip[1]); long c = Integer.parseInt(ip[2]); long d = Integer.parseInt(ip[3]); return a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/RandomUtils.java
RandomUtils
randomDate
class RandomUtils { public static void main(String[] args) throws Exception{ } public static String randomWord(int min,int max) { String randomStr = ""; int ranNum = randomInt(min, max); for (int i = 0; i < ranNum; i++) { char c = 'a'; c = (char) (c + (int) (Math.random() * 26)); randomStr += c; } return randomStr; } public static String randomWordNum(int max) { int ranNum = randomInt(1, max); int ranWord=max-ranNum; String randomWord=randomWord(ranWord, ranWord); if(max>3){ String randomNum=random(ranNum-2, ranNum)+""; return randomNum+randomWord; } return randomWord; } public static int randomInt(int minNum, int maxNum) { Random random = new Random(); int randomInt = random.nextInt(maxNum); if (randomInt < minNum) { return minNum; } return randomInt; } public static Date randomDate(String beginDate, String endDate) {<FILL_FUNCTION_BODY>} public static long random(long begin, long end) { if((begin+2)>=end){ begin = end-2; } long rtnn = begin + (long) (Math.random() * (end - begin)); if (rtnn == begin || rtnn == end) { return random(begin, end); } return rtnn; } public static String randomStr(int minLen,int maxLen){ String base = "abcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StringBuffer sb = new StringBuffer(); int length=random.nextInt(maxLen-minLen)+minLen; for (int i = 0; i < length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); } public static String buildOrderCode(){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMddHsSSS"); String dateFormat = simpleDateFormat.format(new Date()); // return dateFormat+RandomUtils.randomNum(4,4); // dateFormat = RandomUtils.randomWord(5,5).toUpperCase(); return dateFormat+"-"+RandomUtils.random(100000l,999999l); } public static long getVerifyCode() { return random(100000l,999999l); } public static String buildCodeyyMMdd(){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMddHHmmsSSS"); String dateFormat = simpleDateFormat.format(new Date()); // return dateFormat+RandomUtils.randomNum(4,4); // dateFormat = RandomUtils.randomWord(5,5).toUpperCase(); return dateFormat+"-"+RandomUtils.getVerifyCode(); // 20150806125346 } public static String buildCodeyyMMdd32(){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMddHHmmssSSS"); String dateFormat = simpleDateFormat.format(new Date()); // return dateFormat+RandomUtils.randomNum(4,4); // dateFormat = RandomUtils.randomWord(5,5).toUpperCase(); return dateFormat+"-"+RandomUtils.getVerifyCode(); // yyMMdd HHmmss SSS 15 } public static String buildOrderNo(){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMddHHmmsSSS"); String dateFormat = simpleDateFormat.format(new Date()); // return dateFormat+RandomUtils.randomNum(4,4); // dateFormat = RandomUtils.randomWord(5,5).toUpperCase(); return dateFormat+RandomUtils.getVerifyCode(); // 20150806125346 } public static String buildEntCode() { return randomWord(4,6); } public static String buildAppKey() { return randomWord(8,10)+randomStr(8,10); } public static String buildAppSecret() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmsSSS"); String dateFormat = simpleDateFormat.format(new Date()); return randomWord(8,10)+System.currentTimeMillis(); } }
try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date start = format.parse(beginDate);// 开始日期 Date end = format.parse(endDate);// 结束日期 if (start.getTime() >= end.getTime()) { return null; } long date = random(start.getTime(), end.getTime()); return new Date(date); } catch (Exception e) { e.printStackTrace(); } return null;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/RunAnswerUtil.java
RunAnswerUtil
getQuestionMap
class RunAnswerUtil { /** * 返回新question Map * @param questions * @param surveyAnswerId * @return */ public Map<Integer,Question> getQuestionMap(List<Question> questions,String surveyAnswerId) {<FILL_FUNCTION_BODY>} public class RAnswerQuestionMap implements Runnable{ private int quIndex; private Map<Integer,Question> questionMap; private String surveyAnswerId; private Question question; public RAnswerQuestionMap(int quIndex, Map<Integer,Question> questionMap, String surveyAnswerId, Question question){ this.quIndex = quIndex; this.questionMap = questionMap; this.surveyAnswerId = surveyAnswerId; this.question = question; } @Override public void run() { SurveyAnswerManager surveyManager = SpringContextHolder.getBean(SurveyAnswerManagerImpl.class); surveyManager.getquestionAnswer(surveyAnswerId, question); questionMap.put(quIndex, question); } } }
int quIndex = 0; Map<Integer,Question> questionMap = new ConcurrentHashMap<Integer,Question>(); for (Question question : questions) { new Thread(new RAnswerQuestionMap(quIndex++,questionMap,surveyAnswerId,question)).start(); } while (questionMap.size() != questions.size()){ try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } return questionMap;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/SpringContextHolder.java
SpringContextHolder
setApplicationContext
class SpringContextHolder implements ApplicationContextAware, DisposableBean { private static ApplicationContext applicationContext = null; private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class); /** * 取得存储在静态变量中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { assertContextInjected(); return applicationContext; } /** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. */ public static <T> T getBean(String name) { assertContextInjected(); return (T) applicationContext.getBean(name); } /** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. */ public static <T> T getBean(Class<T> requiredType) { assertContextInjected(); return applicationContext.getBean(requiredType); } /** * 清除SpringContextHolder中的ApplicationContext为Null. */ public static void clearHolder() { logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext); applicationContext = null; } /** * 实现ApplicationContextAware接口, 注入Context到静态变量中. */ @Override public void setApplicationContext(ApplicationContext applicationContext) {<FILL_FUNCTION_BODY>} /** * 实现DisposableBean接口, 在Context关闭时清理静态变量. */ @Override public void destroy() throws Exception { SpringContextHolder.clearHolder(); } /** * 检查ApplicationContext不为空. */ private static void assertContextInjected() { AssertUtils.state(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder."); } }
logger.debug("注入ApplicationContext到SpringContextHolder:" + applicationContext); if (SpringContextHolder.applicationContext != null) { logger.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext); } SpringContextHolder.applicationContext = applicationContext; //NOSONAR
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/UserAgentUtils.java
UserAgentUtils
userAgentInt
class UserAgentUtils { public static UserAgent userAgent(HttpServletRequest request){ // String agent=request.getHeader("User-Agent"); // 如下,我们获取了一个agent的字符串: // "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36" // 由此,通过User-agent-utils解析: String agent=request.getHeader("User-Agent"); //解析agent字符串 UserAgent userAgent = UserAgent.parseUserAgentString(agent); return userAgent; } public static int[] userAgentInt(HttpServletRequest request){<FILL_FUNCTION_BODY>} }
int[] result = new int[]{0,0,0}; try{ String agent=request.getHeader("User-Agent"); if(agent!=null){ UserAgent userAgentObj = UserAgent.parseUserAgentString(agent); Browser browser = userAgentObj.getBrowser(); OperatingSystem operatingSystem = userAgentObj.getOperatingSystem(); Browser browserGroup = browser.getGroup(); OperatingSystem sysGroup = operatingSystem.getGroup(); DeviceType deviceType = operatingSystem.getDeviceType(); Integer sys = 0; if(OperatingSystem.ANDROID == sysGroup){ sys=1; }else if(OperatingSystem.WINDOWS == sysGroup ){ sys=2; }else if(OperatingSystem.IOS == sysGroup){ sys=3; }else if(OperatingSystem.MAC_OS == sysGroup || OperatingSystem.MAC_OS_X == sysGroup){ sys=4; } result[0] = sys; Integer bro = 0; if(browserGroup.IE == browserGroup){ bro=1; }else if(browserGroup.SAFARI == browserGroup){ bro=2; }else if(browserGroup.FIREFOX == browserGroup){ bro=3; }else if(browserGroup.OPERA == browserGroup){ bro=4; }else if(browserGroup.CHROME == browserGroup){ bro=5; } result[1] = bro; Integer dt=0; if(DeviceType.COMPUTER == deviceType){ dt=1; }else if(DeviceType.MOBILE == deviceType){ dt=2; } result[2] = dt; } }catch (Exception e){ e.printStackTrace(); } return result;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/ZipUtil.java
ZipUtil
createZip
class ZipUtil { private static final Logger log = LoggerFactory.getLogger(ZipUtil.class); private ZipUtil() { } /** * 创建ZIP文件 * @param sourcePath 文件或文件夹路径 * @param zipPath 生成的zip文件存在路径(包括文件名) * @param isDrop 是否删除原文件:true删除、false不删除 */ public static void createZip(String sourcePath, String zipPath,Boolean isDrop) {<FILL_FUNCTION_BODY>} /** * 清空文件和文件目录 * * @param f */ public static void clean(File f) throws Exception { String cs[] = f.list(); if (cs == null || cs.length <= 0) { boolean isDelete = f.delete(); if (!isDelete) { throw new Exception(f.getName() + "文件删除失败!"); } } else { for (int i = 0; i < cs.length; i++) { String cn = cs[i]; String cp = f.getPath() + File.separator + cn; File f2 = new File(cp); if (f2.exists() && f2.isFile()) { boolean isDelete = f2.delete(); if (!isDelete) { throw new Exception(f2.getName() + "文件删除失败!"); } } else if (f2.exists() && f2.isDirectory()) { clean(f2); } } boolean isDelete = f.delete(); if (!isDelete) { throw new Exception(f.getName() + "文件删除失败!"); } } } private static void writeZip(File file, String parentPath, ZipOutputStream zos,Boolean isDrop) { if(file.exists()){ if(file.isDirectory()){//处理文件夹 parentPath+=file.getName()+File.separator; File [] files=file.listFiles(); if(files.length != 0) { for(File f:files){ writeZip(f, parentPath, zos,isDrop); } } else { //空目录则创建当前目录 try { zos.putNextEntry(new ZipEntry(parentPath)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }else{ FileInputStream fis=null; try { fis=new FileInputStream(file); ZipEntry ze = new ZipEntry(parentPath + file.getName()); zos.putNextEntry(ze); byte [] content=new byte[1024]; int len; while((len=fis.read(content))!=-1){ zos.write(content,0,len); } } catch (FileNotFoundException e) { log.error("创建ZIP文件失败",e); } catch (IOException e) { log.error("创建ZIP文件失败",e); }finally{ try { if(fis!=null){ fis.close(); } if(isDrop){ clean(file); } }catch(IOException e){ log.error("创建ZIP文件失败",e); } catch (Exception e) { e.printStackTrace(); } } } } } public static void main(String[] args) { // ZipUtil.createZip("/Users/keyuan/Documents/GIT/my-gitlab/dw/dwsurvey_b1/dwsurvey/target/dwsurvey/file/402880e864e15c150164e3917b930000", "/Users/keyuan/Documents/GIT/my-gitlab/dw/dwsurvey_b1/dwsurvey/target/dwsurvey/file/402880e864e15c150164e3917b930000.zip",false); } }
FileOutputStream fos = null; ZipOutputStream zos = null; try { fos = new FileOutputStream(zipPath); zos = new ZipOutputStream(fos); //createXmlFile(sourcePath,"293.xml"); writeZip(new File(sourcePath), "", zos,isDrop); } catch (FileNotFoundException e) { log.error("创建ZIP文件失败",e); } finally { try { if (zos != null) { zos.close(); } } catch (IOException e) { log.error("创建ZIP文件失败",e); } }
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/excel/ReadExcelUtil.java
ReadExcelUtil
getWorkBook
class ReadExcelUtil { public static Workbook getWorkBook(String filePath){<FILL_FUNCTION_BODY>} public static HSSFSheet getHSSFSheet(HSSFWorkbook wb, int index) { HSSFSheet sheet = wb.getSheetAt(0); return sheet; } public static String getValueByRowCol(Row sfrow, int col){ Cell cell = sfrow.getCell((short)col); if (cell == null) return ""; String msg = getCellStringValue(cell); return msg; } public static String getValueByCol(Cell sfCell){ String msg = getCellStringValue(sfCell); return msg; } public static void reader(String filePath) { try { POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filePath)); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row = sheet.getRow(3); } catch (IOException e) { e.printStackTrace(); } } public static String getCellStringValue(Cell cell) { String cellValue = ""; switch (cell.getCellType()) { case STRING: cellValue = cell.getStringCellValue(); if (cellValue.trim().equals("") || cellValue.trim().length() <= 0) { cellValue = " "; } break; case NUMERIC: // cellValue = String.valueOf(cell.getNumericCellValue()); DecimalFormat formatter = new DecimalFormat("######"); cellValue = formatter.format(cell.getNumericCellValue()); break; case FORMULA: cell.setCellType(CellType.NUMERIC); cellValue = String.valueOf(cell.getNumericCellValue()); break; case BLANK: cellValue = " "; break; case BOOLEAN: break; case ERROR: break; default: break; } return cellValue; } public static int getRowSize(Sheet sheet){ return sheet.getLastRowNum(); } public static int getCellSize(HSSFRow sfRow){ return sfRow.getLastCellNum(); } public static void main(String[] args) { reader("F://terchers.xls"); } }
POIFSFileSystem fs; Workbook wb = null; try { wb = new XSSFWorkbook(filePath); } catch (Exception e) { try { fs = new POIFSFileSystem(new FileInputStream(filePath)); wb = new HSSFWorkbook(fs); } catch (IOException e1) { e1.printStackTrace(); } } return wb;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/excel/XLSExportUtil.java
XLSExportUtil
exportXLS
class XLSExportUtil { // 设置cell编码解决中文高位字节截断 // 定制日期格式 private static String DATE_FORMAT = " m/d/yy "; // "m/d/yy h:mm" // 定制浮点数格式 private static String NUMBER_FORMAT = " #,##0.00 "; private String xlsFileName; private String path; private HSSFWorkbook workbook; private HSSFSheet sheet; private HSSFRow row; /** * 初始化Excel * * @param fileName * 导出文件名 */ public XLSExportUtil(String fileName,String path) { this.xlsFileName = fileName; this.path=path; this.workbook = new HSSFWorkbook(); this.sheet = workbook.createSheet(); } /** */ /** * 导出Excel文件 * */ public void exportXLS() throws Exception {<FILL_FUNCTION_BODY>} /** */ /** * 增加一行 * * @param index * 行号 */ public void createRow(int index) { this.row = this.sheet.createRow(index); } /** */ /** * 设置单元格 * * @param index * 列号 * @param value * 单元格填充值 */ @SuppressWarnings("deprecation") public void setCell(int index, String value) { HSSFCell cell = this.row.createCell((short) index); cell.setCellType(CellType.STRING); cell.setCellValue(value); } /** */ /** * 设置单元格 * * @param index * 列号 * @param value * 单元格填充值 */ @SuppressWarnings("deprecation") public void setCell(int index, Calendar value) { HSSFCell cell = this.row.createCell((short) index); cell.setCellValue(value.getTime()); HSSFCellStyle cellStyle = workbook.createCellStyle(); // 建立新的cell样式 cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(DATE_FORMAT)); // 设置cell样式为定制的日期格式 cell.setCellStyle(cellStyle); // 设置该cell日期的显示格式 } /** */ /** * 设置单元格 * * @param index * 列号 * @param value * 单元格填充值 */ public void setCell(int index, int value) { HSSFCell cell = this.row.createCell((short) index); cell.setCellType(CellType.NUMERIC); cell.setCellValue(value); } /** */ /** * 设置单元格 * * @param index * 列号 * @param value * 单元格填充值 */ public void setCell(int index, double value) { HSSFCell cell = this.row.createCell((short) index); cell.setCellType(CellType.NUMERIC); cell.setCellValue(value); HSSFCellStyle cellStyle = workbook.createCellStyle(); // 建立新的cell样式 HSSFDataFormat format = workbook.createDataFormat(); cellStyle.setDataFormat(format.getFormat(NUMBER_FORMAT)); // 设置cell样式为定制的浮点数格式 cell.setCellStyle(cellStyle); // 设置该cell浮点数的显示格式 } }
try { File file=new File(path); if(!file.exists()) { file.mkdirs(); } FileOutputStream fOut = new FileOutputStream(path+File.separator+xlsFileName); workbook.write(fOut); fOut.flush(); fOut.close(); } catch (FileNotFoundException e) { throw new Exception(" 生成导出Excel文件出错! ", e); } catch (IOException e) { throw new Exception(" 写入Excel文件出错! ", e); }
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/excel/XLSXExportUtil.java
XLSXExportUtil
setCellBlue
class XLSXExportUtil { // 设置cell编码解决中文高位字节截断 // 定制日期格式 private static String DATE_FORMAT = " m/d/yy "; // "m/d/yy h:mm" // 定制浮点数格式 private static String NUMBER_FORMAT = " #,##0.00 "; private String xlsFileName; private String path; private XSSFWorkbook workbook; private XSSFSheet sheet; private XSSFRow row; private XSSFCellStyle cellStyle; private XSSFDataFormat dataFormat ; /** * 初始化Excel * * @param fileName * 导出文件名 */ public XLSXExportUtil(String fileName, String path) { this.xlsFileName = fileName; this.path=path; this.workbook = new XSSFWorkbook(); this.sheet = workbook.createSheet(); this.cellStyle = workbook.createCellStyle(); // 建立新的cell样式; this.dataFormat = workbook.createDataFormat(); // SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(workbook1, 100); } /** */ /** * 导出Excel文件 * */ public void exportXLS() throws Exception { try { File file=new File(path); if(!file.exists()) { file.mkdirs(); } FileOutputStream fOut = new FileOutputStream(path+File.separator+xlsFileName); workbook.write(fOut); fOut.flush(); fOut.close(); } catch (FileNotFoundException e) { throw new Exception(" 生成导出Excel文件出错! ", e); } catch (IOException e) { throw new Exception(" 写入Excel文件出错! ", e); } } /** */ /** * 增加一行 * * @param index * 行号 */ public void createRow(int index) { this.row = this.sheet.createRow(index); } public void setCellBlue(int index, String value) {<FILL_FUNCTION_BODY>} public void setCellYellow(int index, String value) { XSSFCell cell = this.row.createCell((short) index); cell.setCellType(CellType.STRING); // Font font = workbook.createFont(); // font.setColor(IndexedColors.BLUE.getIndex()); // style.setFont(font); cellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.YELLOW.getIndex()); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); cell.setCellStyle(cellStyle); cell.setCellValue(value); } /** */ /** * 设置单元格 * * @param index * 列号 * @param value * 单元格填充值 */ @SuppressWarnings("deprecation") public void setCell(int index, String value) { XSSFCell cell = this.row.createCell((short) index); cell.setCellType(CellType.STRING); cell.setCellValue(value); } /** */ /** * 设置单元格 * * @param index * 列号 * @param value * 单元格填充值 */ @SuppressWarnings("deprecation") public void setCell(int index, Calendar value) { XSSFCell cell = this.row.createCell((short) index); cell.setCellValue(value.getTime()); cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(DATE_FORMAT)); // 设置cell样式为定制的日期格式 cell.setCellStyle(cellStyle); // 设置该cell日期的显示格式 } /** */ /** * 设置单元格 * * @param index * 列号 * @param value * 单元格填充值 */ public void setCell(int index, int value) { XSSFCell cell = this.row.createCell((short) index); cell.setCellType(CellType.NUMERIC); cell.setCellValue(value); } /** */ /** * 设置单元格 * * @param index * 列号 * @param value * 单元格填充值 */ public void setCell(int index, double value) { XSSFCell cell = this.row.createCell((short) index); cell.setCellType(CellType.NUMERIC); cell.setCellValue(value); cellStyle.setDataFormat(dataFormat.getFormat(NUMBER_FORMAT)); // 设置cell样式为定制的浮点数格式 cell.setCellStyle(cellStyle); // 设置该cell浮点数的显示格式 } }
XSSFCell cell = this.row.createCell((short) index); cell.setCellType(CellType.STRING); // CellStyle style = workbook.createCellStyle(); // Font font = workbook.createFont(); // font.setColor(IndexedColors.BLUE.getIndex()); // style.setFont(font); cellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIME.getIndex()); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); cell.setCellStyle(cellStyle); cell.setCellValue(value);
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/parsehtml/HtmlUtil.java
HtmlUtil
removeTagFromText
class HtmlUtil { public static String removeTagFromText(String htmlStr) {<FILL_FUNCTION_BODY>} }
if (htmlStr == null || "".equals(htmlStr)) return ""; String textStr = ""; Pattern pattern; java.util.regex.Matcher matcher; try { String regEx_remark = "<!--.+?-->"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script> // } String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style> // } String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式 String regEx_html1 = "<[^>]+"; htmlStr = htmlStr.replaceAll("\n", ""); htmlStr = htmlStr.replaceAll("\t", ""); htmlStr = htmlStr.replaceAll("\r", ""); pattern = Pattern.compile(regEx_remark);// 过滤注释标签 matcher = pattern.matcher(htmlStr); htmlStr = matcher.replaceAll(""); pattern = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE); matcher = pattern.matcher(htmlStr); htmlStr = matcher.replaceAll(""); // 过滤script标签 pattern = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE); matcher = pattern.matcher(htmlStr); htmlStr = matcher.replaceAll(""); // 过滤style标签 pattern = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); matcher = pattern.matcher(htmlStr); htmlStr = matcher.replaceAll(""); // 过滤html标签 pattern = Pattern.compile(regEx_html1, Pattern.CASE_INSENSITIVE); matcher = pattern.matcher(htmlStr); htmlStr = matcher.replaceAll(""); // 过滤html标签 htmlStr = htmlStr.replaceAll("\n[\\s| ]*\r", ""); htmlStr = htmlStr.replaceAll("<(.*)>(.*)<\\/(.*)>|<(.*)\\/>", ""); textStr = htmlStr.trim(); } catch (Exception e) { e.printStackTrace(); } return textStr;// dwv402880e666e15b790166e16222000000 返回文本字符串
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/security/DigestUtils.java
DigestUtils
digest
class DigestUtils { private static final String SHA1 = "SHA-1"; private static final String MD5 = "MD5"; //-- String Hash function --// /** * 对输入字符串进行sha1散列, 返回Hex编码的结果. */ public static String sha1Hex(String input) { byte[] digestResult = digest(input, SHA1); return EncodeUtils.encodeHex(digestResult); } /** * 对输入字符串进行sha1散列, 返回Base64编码的结果. */ public static String sha1Base64(String input) { byte[] digestResult = digest(input, SHA1); return EncodeUtils.encodeBase64(digestResult); } /** * 对输入字符串进行sha1散列, 返回Base64编码的URL安全的结果. */ public static String sha1Base64UrlSafe(String input) { byte[] digestResult = digest(input, SHA1); return EncodeUtils.encodeUrlSafeBase64(digestResult); } /** * 对字符串进行散列, 支持md5与sha1算法. */ private static byte[] digest(String input, String algorithm) { try { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); return messageDigest.digest(input.getBytes()); } catch (GeneralSecurityException e) { throw ExceptionUtils.unchecked(e); } } //-- File Hash function --// /** * 对文件进行md5散列, 返回Hex编码结果. */ public static String md5Hex(InputStream input) throws IOException { return digest(input, MD5); } /** * 对文件进行sha1散列, 返回Hex编码结果. */ public static String sha1Hex(InputStream input) throws IOException { return digest(input, SHA1); } private static String digest(InputStream input, String algorithm) throws IOException {<FILL_FUNCTION_BODY>} }
try { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); int bufferLength = 1024; byte[] buffer = new byte[bufferLength]; int read = input.read(buffer, 0, bufferLength); while (read > -1) { messageDigest.update(buffer, 0, read); read = input.read(buffer, 0, bufferLength); } return EncodeUtils.encodeHex(messageDigest.digest()); } catch (GeneralSecurityException e) { throw ExceptionUtils.unchecked(e); }
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/web/InitAppliction.java
InitAppliction
contextInitialized
class InitAppliction implements ServletContextListener { public static String contextPath = null; @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub } @Override public void contextInitialized(ServletContextEvent sce) {<FILL_FUNCTION_BODY>} }
// TODO Auto-generated method stub ServletContext servletContext = sce.getServletContext(); contextPath = servletContext.getContextPath();
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/common/utils/web/ServletUtils.java
ServletUtils
getParametersStartingWith
class ServletUtils { //-- Content Type 定义 --// public static final String EXCEL_TYPE = "application/vnd.ms-excel"; public static final String HTML_TYPE = "text/html"; public static final String JS_TYPE = "text/javascript"; public static final String JSON_TYPE = "application/json"; public static final String XML_TYPE = "text/xml"; public static final String TEXT_TYPE = "text/plain"; //-- Header 定义 --// public static final String AUTHENTICATION_HEADER = "Authorization"; //-- 常用数值定义 --// public static final long ONE_YEAR_SECONDS = 60 * 60 * 24 * 365; /** * 设置客户端缓存过期时间 的Header. */ public static void setExpiresHeader(HttpServletResponse response, long expiresSeconds) { //Http 1.0 header response.setDateHeader("Expires", System.currentTimeMillis() + expiresSeconds * 1000); //Http 1.1 header response.setHeader("Cache-Control", "private, max-age=" + expiresSeconds); } /** * 设置禁止客户端缓存的Header. */ public static void setDisableCacheHeader(HttpServletResponse response) { //Http 1.0 header response.setDateHeader("Expires", 1L); response.addHeader("Pragma", "no-cache"); //Http 1.1 header response.setHeader("Cache-Control", "no-cache, no-store, max-age=0"); } /** * 设置LastModified Header. */ public static void setLastModifiedHeader(HttpServletResponse response, long lastModifiedDate) { response.setDateHeader("Last-Modified", lastModifiedDate); } /** * 设置Etag Header. */ public static void setEtag(HttpServletResponse response, String etag) { response.setHeader("ETag", etag); } /** * 根据浏览器If-Modified-Since Header, 计算文件是否已被修改. * * 如果无修改, checkIfModify返回false ,设置304 not modify status. * * @param lastModified 内容的最后修改时间. */ public static boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response, long lastModified) { long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if ((ifModifiedSince != -1) && (lastModified < ifModifiedSince + 1000)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return false; } return true; } /** * 根据浏览器 If-None-Match Header, 计算Etag是否已无效. * * 如果Etag有效, checkIfNoneMatch返回false, 设置304 not modify status. * * @param etag 内容的ETag. */ public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) { String headerValue = request.getHeader("If-None-Match"); if (headerValue != null) { boolean conditionSatisfied = false; if (!"*".equals(headerValue)) { StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ","); while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) { String currentToken = commaTokenizer.nextToken(); if (currentToken.trim().equals(etag)) { conditionSatisfied = true; } } } else { conditionSatisfied = true; } if (conditionSatisfied) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", etag); return false; } } return true; } /** * 设置让浏览器弹出下载对话框的Header. * * @param fileName 下载后的文件名. */ public static void setFileDownloadHeader(HttpServletResponse response, String fileName) { try { //中文文件名支持 String encodedfileName = new String(fileName.getBytes(), "ISO8859-1"); response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\""); } catch (UnsupportedEncodingException e) { } } /** * 取得带相同前缀的Request Parameters. * * 返回的结果的Parameter名已去除前缀. */ public static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix) {<FILL_FUNCTION_BODY>} /** * 客户端对Http Basic验证的 Header进行编码. */ public static String encodeHttpBasic(String userName, String password) { String encode = userName + ":" + password; return "Basic " + EncodeUtils.encodeBase64(encode.getBytes()); } }
AssertUtils.notNull(request, "Request must not be null"); Enumeration paramNames = request.getParameterNames(); Map<String, Object> params = new TreeMap<String, Object>(); if (prefix == null) { prefix = ""; } while (paramNames != null && paramNames.hasMoreElements()) { String paramName = (String) paramNames.nextElement(); if ("".equals(prefix) || paramName.startsWith(prefix)) { String unprefixed = paramName.substring(prefix.length()); String[] values = request.getParameterValues(paramName); if (values == null || values.length == 0) { // Do nothing, no values found at all. } else if (values.length > 1) { params.put(unprefixed, values); } else { params.put(unprefixed, values[0]); } } } return params;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/dwsurvey/DwsurveyApplication.java
DwsurveyApplication
tomcatFactory
class DwsurveyApplication { public static void main(String[] args) { SpringApplication.run(DwsurveyApplication.class, args); } @Bean public TomcatServletWebServerFactory tomcatFactory(){<FILL_FUNCTION_BODY>} }
return new TomcatServletWebServerFactory(){ @Override protected void postProcessContext(Context context) { ((StandardJarScanner) context.getJarScanner()).setScanManifest(false); } };
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/dwsurvey/config/CorsConfig.java
CorsConfig
buildConfig
class CorsConfig { // private static String AllowOrigin = "*"; private CorsConfiguration buildConfig() {<FILL_FUNCTION_BODY>} @Bean public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // source.registerCorsConfiguration("/file/**", buildConfig()); source.registerCorsConfiguration("/**", buildConfig()); CorsFilter corsFilter = new CorsFilter(source); FilterRegistrationBean bean = new FilterRegistrationBean(corsFilter); bean.setOrder(0); return bean; } /** * 可以根据需求调整 AllowOrigin ,默认是所有 * @return */ public static List<String> getAllowOrigin() { List<String> list = new ArrayList<>(); list.add("*");//所有域名 return list; } }
CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.setAllowCredentials(true);//sessionid 多次访问一致 corsConfiguration.setAllowedOriginPatterns(getAllowOrigin()); // corsConfiguration.addAllowedOrigin("*");// 允许任何域名使用 corsConfiguration.addAllowedHeader("*");// 允许任何头 corsConfiguration.addAllowedMethod("*");// 允许任何方法(post、get等) return corsConfiguration;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/dwsurvey/config/HibernateConfig.java
HibernateConfig
hibernateProperties
class HibernateConfig { @Autowired private Environment environment; @Autowired private DataSource dataSource; @Bean public LocalSessionFactoryBean sessionFactoryBean() { LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); sessionFactoryBean.setDataSource(dataSource); sessionFactoryBean.setPhysicalNamingStrategy(new net.diaowen.common.plugs.mapper.SnakeCaseNamingStrategy()); sessionFactoryBean.setPackagesToScan("net.diaowen.common","net.diaowen.dwsurvey");//dao和entity的公共包 sessionFactoryBean.setHibernateProperties(hibernateProperties()); return sessionFactoryBean; } /* @Bean public HibernateTransactionManager transactionManager() { HibernateTransactionManager transactionManager = new HibernateTransactionManager(); transactionManager.setSessionFactory(sessionFactoryBean().getObject()); return transactionManager; }*/ //获取hibernate配置 private Properties hibernateProperties() {<FILL_FUNCTION_BODY>} }
Properties properties = new Properties(); properties.setProperty("hibernate.current_session_context_class", environment.getProperty("spring.jpa.properties.hibernate.current_session_context_class")); properties.setProperty("hibernate.hbm2ddl.auto", environment.getProperty("spring.jpa.hibernate.ddl-auto")); properties.setProperty("hibernate.show_sql", environment.getProperty("spring.jpa.properties.hibernate.show_sql")); properties.setProperty("hibernate.format_sql", environment.getProperty("spring.jpa.properties.hibernate.format_sql")); properties.setProperty("hibernate.cache.use_second_level_cache", environment.getProperty("spring.jpa.properties.hibernate.cache.use_second_level_cache")); properties.setProperty("hibernate.cache.use_query_cache", environment.getProperty("spring.jpa.properties.hibernate.cache.use_query_cache")); return properties;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/dwsurvey/config/MyCommonsMultipartResolver.java
MyCommonsMultipartResolver
isMultipart
class MyCommonsMultipartResolver extends CommonsMultipartResolver { @Override public boolean isMultipart(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
String uri = request.getRequestURI(); if(uri!=null && uri.contains("/config")){ return false; }else{ return super.isMultipart(request); }
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/dwsurvey/config/ShiroConfig.java
ShiroConfig
shiroFilter
class ShiroConfig { @Bean public ShiroDbRealm myShiroRealm() { ShiroDbRealm customRealm = new ShiroDbRealm(); return customRealm; } //权限管理,配置主要是Realm的管理认证 SecurityManager @Bean public DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(myShiroRealm()); securityManager.setRememberMeManager(rememberMeManager()); return securityManager; } @Bean public FormAuthenticationWithLockFilter formAuthFilter() { FormAuthenticationWithLockFilter formAuthFilter = new FormAuthenticationWithLockFilter(); formAuthFilter.setMaxLoginAttempts(100); formAuthFilter.setSuccessAdminUrl("/design/my-survey/list.do"); formAuthFilter.setSuccessAdminRole("admin"); formAuthFilter.setRememberMeParam("rememberMe"); return formAuthFilter; } @Bean public UserFilter userAuthFilter() { MyUserFilter formAuthFilter = new MyUserFilter(); return formAuthFilter; } @Bean public MyRolesAuthorizationFilter rolesAuthFilter() { MyRolesAuthorizationFilter rolesAuthorizationFilter = new MyRolesAuthorizationFilter(); return rolesAuthorizationFilter; } @Bean public AnonymousFilter anonymousFilter() { AnonymousFilter anonymousFilter = new AnonymousFilter(); return anonymousFilter; } //Filter工厂,设置对应的过滤条件和跳转条件 @Bean public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {<FILL_FUNCTION_BODY>} @Bean public SimpleCookie rememberMeCookie() { SimpleCookie rememberMeCookie = new SimpleCookie("rememberMe"); rememberMeCookie.setHttpOnly(true); rememberMeCookie.setMaxAge(2592000); return rememberMeCookie; } @Bean public CookieRememberMeManager rememberMeManager() { CookieRememberMeManager rememberMeManager = new CookieRememberMeManager(); rememberMeManager.setCookie(rememberMeCookie()); return rememberMeManager; } }
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); Map<String, String> map = new LinkedHashMap<>(); //登出 map.put("/logout", "logout"); //对所有用户认证 map.put("/api/dwsurvey/anon/**", "anon"); map.put("/login", "authc"); map.put("/ic/**", "user"); map.put("/design/**", "user"); map.put("/da/**", "user"); map.put("/api/dwsurvey/app/**", "user"); map.put("/api/dwsurvey/admin/**", "roles["+ RoleCode.DWSURVEY_SUPER_ADMIN +"]"); //登录 // shiroFilterFactoryBean.setLoginUrl("/login.do"); //首页 shiroFilterFactoryBean.setSuccessUrl("/design/my-survey/list.do"); //错误页面,认证不通过跳转 // shiroFilterFactoryBean.setUnauthorizedUrl("/login.do?una=0"); shiroFilterFactoryBean.setFilterChainDefinitionMap(map); Map<String, Filter> filters = new HashMap<>(); filters.put("authc", formAuthFilter()); filters.put("user", userAuthFilter()); filters.put("roles", rolesAuthFilter()); // filters.put("anon", anonymousFilter()); shiroFilterFactoryBean.setFilters(filters); return shiroFilterFactoryBean;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/dwsurvey/config/UrlRewriteConf.java
UrlRewriteConf
loadUrlRewriter
class UrlRewriteConf extends UrlRewriteFilter { private static final String URL_REWRITE = "classpath:conf/urlrewrite.xml"; //注入urlrewrite配置文件 @Value(URL_REWRITE) private Resource resource; //重写配置文件加载方式 protected void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {<FILL_FUNCTION_BODY>} }
try { //将Resource对象转换成Conf对象 Conf conf = new Conf(filterConfig.getServletContext(), resource.getInputStream(), resource.getFilename(), "@@traceability@@"); checkConf(conf); } catch (IOException ex) { throw new ServletException("Unable to load URL rewrite configuration file from " + URL_REWRITE, ex); }
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/dwsurvey/config/WebConfigure.java
WebConfigure
delegatingFilterProxy
class WebConfigure implements WebMvcConfigurer { /* @Bean(name="sitemesh3") SiteMeshFilter siteMeshFilter(){ return new SiteMeshFilter(); } public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("forward:/login.do"); registry.setOrder(Ordered.HIGHEST_PRECEDENCE); } */ @Bean public FilterRegistrationBean registerOpenEntityManagerInViewFilterBean() { FilterRegistrationBean registrationBean = new FilterRegistrationBean(); OpenEntityManagerInViewFilter filter = new OpenEntityManagerInViewFilter(); registrationBean.setFilter(filter); registrationBean.addUrlPatterns("*.do"); return registrationBean; } @Bean public FilterRegistrationBean delegatingFilterProxy(){<FILL_FUNCTION_BODY>} /* @Bean public FilterRegistrationBean filterRegistrationBean(@Qualifier("sitemesh3") SiteMeshFilter siteMeshFilter){ FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(siteMeshFilter); filterRegistrationBean.setEnabled(true); filterRegistrationBean.addUrlPatterns("*.do"); return filterRegistrationBean; } @Bean public FilterRegistrationBean filterRegistrationBean(){ FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); UrlRewriteFilter urlRewriteFilter = new UrlRewriteFilter(); filterRegistrationBean.setFilter(urlRewriteFilter); filterRegistrationBean.setEnabled(true); filterRegistrationBean.addUrlPatterns("/*"); return filterRegistrationBean; } */ public void addResourceHandlers(ResourceHandlerRegistry registry) { //文件磁盘图片url 映射 //配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径 //registry.addResourceHandler("/WEB-INF/**").addResourceLocations("file:/home/IdeaProjects/dwsurvey/src/main/webapp/WEB-INF"); // registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); } }
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); DelegatingFilterProxy proxy = new DelegatingFilterProxy(); proxy.setTargetFilterLifecycle(true); proxy.setTargetBeanName("shiroFilter"); filterRegistrationBean.setFilter(proxy); filterRegistrationBean.addUrlPatterns("/*"); return filterRegistrationBean;
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/DwWebController.java
DwWebController
footerInfo
class DwWebController { @Autowired private AccountManager accountManager; /** * 获取问卷详情 * @return */ @RequestMapping(value = "/footer-info.do",method = RequestMethod.GET) @ResponseBody public HttpResult<SurveyDirectory> footerInfo() {<FILL_FUNCTION_BODY>} }
try{ FooterInfo footerInfo = new FooterInfo(); footerInfo.setVersionInfo(DWSurveyConfig.DWSURVEY_VERSION_INFO); footerInfo.setVersionNumber(DWSurveyConfig.DWSURVEY_VERSION_NUMBER); footerInfo.setVersionBuilt(DWSurveyConfig.DWSURVEY_VERSION_BUILT); footerInfo.setSiteName(DWSurveyConfig.DWSURVEY_WEB_INFO_SITE_NAME); footerInfo.setSiteUrl(DWSurveyConfig.DWSURVEY_WEB_INFO_SITE_URL); footerInfo.setSiteIcp(DWSurveyConfig.DWSURVEY_WEB_INFO_SITE_ICP); footerInfo.setSiteMail(DWSurveyConfig.DWSURVEY_WEB_INFO_SITE_MAIL); footerInfo.setSitePhone(DWSurveyConfig.DWSURVEY_WEB_INFO_SITE_PHONE); footerInfo.setYears("2012-"+new SimpleDateFormat("yyyy").format(new Date())); User user = accountManager.getCurUser(); if(user!=null){ //登录用户返回带版本号 return HttpResult.SUCCESS(footerInfo); }else{ //非登录用户返回不带版本号 footerInfo.setVersionNumber(""); return HttpResult.SUCCESS(footerInfo); } }catch (Exception e){ e.printStackTrace(); } return HttpResult.FAILURE();
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/UEditorController.java
UEditorController
config
class UEditorController { // 第二种方式 @Autowired // 注入到容器中 private Environment environment; @Autowired private AccountManager accountManager; @RequestMapping(value="/config") public void config(HttpServletRequest request, HttpServletResponse response) {<FILL_FUNCTION_BODY>} }
response.setContentType("application/json"); String webFilePath = DWSurveyConfig.DWSURVEY_WEB_FILE_PATH; String rootPath = webFilePath; try { User user = accountManager.getCurUser(); if(user!=null){ String exec = new ActionEnter(request, rootPath, user.getId()).exec(); PrintWriter writer = response.getWriter(); writer.write(exec); writer.flush(); writer.close(); } } catch (IOException e) { e.printStackTrace(); }
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/question/QuFillblankController.java
QuFillblankController
buildResultJson
class QuFillblankController{ @Autowired private QuestionManager questionManager; @Autowired private AnFillblankManager anFillblankManager; @RequestMapping("/ajaxSave.do") public String ajaxSave(HttpServletRequest request,HttpServletResponse response) throws Exception { try{ Question entity=ajaxBuildSaveOption(request); questionManager.save(entity); String resultJson=buildResultJson(entity); response.getWriter().write(resultJson); }catch (Exception e) { e.printStackTrace(); response.getWriter().write("error"); } return null; } private Question ajaxBuildSaveOption(HttpServletRequest request) throws UnsupportedEncodingException { String quId=request.getParameter("quId"); String belongId=request.getParameter("belongId"); String quTitle=request.getParameter("quTitle"); String orderById=request.getParameter("orderById"); String tag=request.getParameter("tag"); String isRequired=request.getParameter("isRequired"); String answerInputWidth=request.getParameter("answerInputWidth"); String answerInputRow=request.getParameter("answerInputRow"); String contactsAttr=request.getParameter("contactsAttr"); String contactsField=request.getParameter("contactsField"); String checkType=request.getParameter("checkType"); String hv=request.getParameter("hv"); String randOrder=request.getParameter("randOrder"); String cellCount=request.getParameter("cellCount"); String paramInt01=request.getParameter("paramInt01"); //System.out.println("paramInt01:"+paramInt01); if("".equals(quId)){ quId=null; } Question entity=questionManager.getModel(quId); entity.setBelongId(belongId); if(quTitle!=null){ quTitle=URLDecoder.decode(quTitle,"utf-8"); entity.setQuTitle(quTitle); } entity.setOrderById(Integer.parseInt(orderById)); entity.setTag(Integer.parseInt(tag)); entity.setQuType(QuType.FILLBLANK); isRequired=(isRequired==null || "".equals(isRequired))?"0":isRequired; hv=(hv==null || "".equals(hv))?"0":hv; randOrder=(randOrder==null || "".equals(randOrder))?"0":randOrder; cellCount=(cellCount==null || "".equals(cellCount))?"0":cellCount; contactsAttr=(contactsAttr==null || "".equals(contactsAttr))?"0":contactsAttr; entity.setContactsAttr(Integer.parseInt(contactsAttr)); entity.setContactsField(contactsField); answerInputWidth=(answerInputWidth==null || "".equals(answerInputWidth))?"300":answerInputWidth; answerInputRow=(answerInputRow==null || "".equals(answerInputRow))?"1":answerInputRow; paramInt01=(StringUtils.isEmpty(paramInt01))?"0":paramInt01; entity.setAnswerInputWidth(Integer.parseInt(answerInputWidth)); entity.setAnswerInputRow(Integer.parseInt(answerInputRow)); entity.setIsRequired(Integer.parseInt(isRequired)); entity.setHv(Integer.parseInt(hv)); entity.setRandOrder(Integer.parseInt(randOrder)); entity.setCellCount(Integer.parseInt(cellCount)); checkType=(checkType==null || "".equals(checkType))?"NO":checkType; entity.setCheckType(CheckType.valueOf(checkType)); entity.setParamInt01(Integer.parseInt(paramInt01)); Map<String, Object> quLogicIdMap=WebUtils.getParametersStartingWith(request, "quLogicId_"); List<QuestionLogic> quLogics=new ArrayList<QuestionLogic>(); for (String key : quLogicIdMap.keySet()) { String cgQuItemId=request.getParameter("cgQuItemId_"+key); String skQuId=request.getParameter("skQuId_"+key); String visibility=request.getParameter("visibility_"+key); String logicType=request.getParameter("logicType_"+key); Object quLogicId=quLogicIdMap.get(key); String quLogicIdValue=(quLogicId!=null)?quLogicId.toString():null; QuestionLogic quLogic=new QuestionLogic(); quLogic.setId(quLogicIdValue); quLogic.setCgQuItemId(cgQuItemId); quLogic.setSkQuId(skQuId); quLogic.setVisibility(Integer.parseInt(visibility)); quLogic.setTitle(key); quLogic.setLogicType(logicType); quLogics.add(quLogic); } entity.setQuestionLogics(quLogics); return entity; } public static String buildResultJson(Question entity){<FILL_FUNCTION_BODY>} }
StringBuffer strBuf=new StringBuffer(); strBuf.append("{id:'").append(entity.getId()); strBuf.append("',orderById:"); strBuf.append(entity.getOrderById()); strBuf.append(",quLogics:["); List<QuestionLogic> questionLogics=entity.getQuestionLogics(); if(questionLogics!=null){ for (QuestionLogic questionLogic : questionLogics) { strBuf.append("{id:'").append(questionLogic.getId()); strBuf.append("',title:'").append(questionLogic.getTitle()).append("'},"); } } int strLen=strBuf.length(); if(strBuf.lastIndexOf(",")==(strLen-1)){ strBuf.replace(strLen-1, strLen, ""); } strBuf.append("]}"); return strBuf.toString();
wkeyuan_DWSurvey
DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/question/QuOrderquController.java
QuOrderquController
ajaxBuildSaveOption
class QuOrderquController{ @Autowired private QuestionManager questionManager; @Autowired private QuOrderbyManager quOrderbyManager; @RequestMapping("/ajaxSave.do") public String ajaxSave(HttpServletRequest request,HttpServletResponse response) throws Exception { try{ Question entity=ajaxBuildSaveOption(request); questionManager.save(entity); String resultJson=buildResultJson(entity); response.getWriter().write(resultJson); }catch (Exception e) { e.printStackTrace(); response.getWriter().write("error"); } return null; } private Question ajaxBuildSaveOption(HttpServletRequest request) throws UnsupportedEncodingException {<FILL_FUNCTION_BODY>} public static String buildResultJson(Question entity){ StringBuffer strBuf=new StringBuffer(); strBuf.append("{id:'").append(entity.getId()); strBuf.append("',orderById:"); strBuf.append(entity.getOrderById()); strBuf.append(",quItems:["); List<QuOrderby> quOrderbys=entity.getQuOrderbys(); for (QuOrderby quOrderby : quOrderbys) { strBuf.append("{id:'").append(quOrderby.getId()); strBuf.append("',title:'").append(quOrderby.getOrderById()).append("'},"); } int strLen=strBuf.length(); if(strBuf.lastIndexOf(",")==(strLen-1)){ strBuf.replace(strLen-1, strLen, ""); } strBuf.append("]"); strBuf.append(",quLogics:["); List<QuestionLogic> questionLogics=entity.getQuestionLogics(); if(questionLogics!=null){ for (QuestionLogic questionLogic : questionLogics) { strBuf.append("{id:'").append(questionLogic.getId()); strBuf.append("',title:'").append(questionLogic.getTitle()).append("'},"); } } strLen=strBuf.length(); if(strBuf.lastIndexOf(",")==(strLen-1)){ strBuf.replace(strLen-1, strLen, ""); } strBuf.append("]}"); return strBuf.toString(); } /** * 删除选项 * @return * @throws Exception */ @RequestMapping("/ajaxDelete.do") public String ajaxDelete(HttpServletRequest request,HttpServletResponse response) throws Exception { try{ String quItemId=request.getParameter("quItemId"); quOrderbyManager.ajaxDelete(quItemId); response.getWriter().write("true"); }catch(Exception e){ e.printStackTrace(); response.getWriter().write("error"); } return null; } }
String quId=request.getParameter("quId"); String belongId=request.getParameter("belongId"); String quTitle=request.getParameter("quTitle"); String orderById=request.getParameter("orderById"); String tag=request.getParameter("tag"); //isRequired 是否必选 String isRequired=request.getParameter("isRequired"); //hv 1水平显示 2垂直显示 String hv=request.getParameter("hv"); //randOrder 选项随机排列 String randOrder=request.getParameter("randOrder"); String cellCount=request.getParameter("cellCount"); if("".equals(quId)){ quId=null; } Question entity=questionManager.getModel(quId); entity.setBelongId(belongId); if(quTitle!=null){ quTitle=URLDecoder.decode(quTitle,"utf-8"); entity.setQuTitle(quTitle); } entity.setOrderById(Integer.parseInt(orderById)); entity.setTag(Integer.parseInt(tag)); entity.setQuType(QuType.ORDERQU); isRequired=(isRequired==null || "".equals(isRequired))?"0":isRequired; hv=(hv==null || "".equals(hv))?"0":hv; randOrder=(randOrder==null || "".equals(randOrder))?"0":randOrder; cellCount=(cellCount==null || "".equals(cellCount))?"0":cellCount; entity.setIsRequired(Integer.parseInt(isRequired)); entity.setHv(Integer.parseInt(hv)); entity.setRandOrder(Integer.parseInt(randOrder)); entity.setCellCount(Integer.parseInt(cellCount)); Map<String, Object> optionNameMap=WebUtils.getParametersStartingWith(request, "optionValue_"); List<QuOrderby> quOrderbys=new ArrayList<QuOrderby>(); for (String key : optionNameMap.keySet()) { String optionId=request.getParameter("optionId_"+key); Object optionName=optionNameMap.get(key); String optionNameValue=(optionName!=null)?optionName.toString():""; QuOrderby quOrderby=new QuOrderby(); if("".equals(optionId)){ optionId=null; } quOrderby.setId(optionId); // quRadio.setOptionTitle(key); optionNameValue=URLDecoder.decode(optionNameValue,"utf-8"); quOrderby.setOptionName(optionNameValue); quOrderby.setOrderById(Integer.parseInt(key)); quOrderbys.add(quOrderby); } entity.setQuOrderbys(quOrderbys); //逻辑选项设置 Map<String, Object> quLogicIdMap=WebUtils.getParametersStartingWith(request, "quLogicId_"); List<QuestionLogic> quLogics=new ArrayList<QuestionLogic>(); for (String key : quLogicIdMap.keySet()) { String cgQuItemId=request.getParameter("cgQuItemId_"+key); String skQuId=request.getParameter("skQuId_"+key); String visibility=request.getParameter("visibility_"+key); String logicType=request.getParameter("logicType_"+key); Object quLogicId=quLogicIdMap.get(key); String quLogicIdValue=(quLogicId!=null)?quLogicId.toString():null; QuestionLogic quLogic=new QuestionLogic(); quLogic.setId(quLogicIdValue); quLogic.setCgQuItemId(cgQuItemId); quLogic.setSkQuId(skQuId); quLogic.setVisibility(Integer.parseInt(visibility)); quLogic.setTitle(key); quLogic.setLogicType(logicType); quLogics.add(quLogic); } entity.setQuestionLogics(quLogics); return entity;