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 ...
HttpServletRequest servletRequest = (HttpServletRequest) req; HttpServletResponse servletResponse = (HttpServletResponse) resp; boolean isAdmin = false; try { //read auth token String authToken = AuthUtil.getAuthToken(servletRequest.getSession()); ...
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.getClassLoa...
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() { }...
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.getPr...
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...
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 fina...
String username; String secret; try { username = UserDB.getUser(AuthUtil.getUserId(getRequest().getSession())).getUsername(); secret = AuthUtil.getOTPSecret(getRequest().getSession()); AuthUtil.setOTPSecret(getRequest().getSession(), null); } catch (...
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, H...
try { if (profile.getId() != null) { ProfileDB.updateProfile(profile); } else { ProfileDB.insertProfile(profile); } } catch (SQLException | GeneralSecurityException ex) { log.error(ex.toString(), ex); throw new...
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> syst...
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.toS...
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> userSelect...
if (userSelectId != null) { try { UserProfileDB.setUsersForProfile(profile.getId(), userSelectId); } 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/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, HttpServ...
if (script == null || script.getDisplayNm() == null || script.getDisplayNm().trim().equals("")) { addFieldError("script.displayNm", "Required"); } if (script == null || script.getScript() == null || script.getScript()....
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; ...
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); ...
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 Hos...
if (hostSystem == null || hostSystem.getDisplayNm() == null || hostSystem.getDisplayNm().trim().equals("")) { addFieldError("hostSystem.displayNm", REQUIRED); } if (hostSystem == null || hostSystem.getUser() == null || ...
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 = ...
try { Long userId = AuthUtil.getUserId(getRequest().getSession()); Long sessionId = AuthUtil.getSessionId(getRequest().getSession()); //get next pending system pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId); if (pendingSystemStat...
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("Ta...
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 { ...
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...
if (user == null || user.getUsername() == null || user.getUsername().trim().equals("")) { addFieldError("user.username", REQUIRED); } if (user == null || user.getLastNm() == null || user.getLastNm().trim().equals("")) ...
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...
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 * ...
ArrayList<Profile> profileList = new ArrayList<>(); String orderBy = ""; if (sortedSet.getOrderByField() != null && !sortedSet.getOrderByField().trim().equals("")) { orderBy = " order by " + sortedSet.getOrderByField() + " " + sortedSet.getOrderByDirection(); } Str...
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,...
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...
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 u...
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(); ...
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 use...
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); ...
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 { ...
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(); ...
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 ...
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(...
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; } ...
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 S...
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 = sessio...
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) { Sess...
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 = se...
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 = gso...
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 s...
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 != n...
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 (GeneralSecurityExcept...
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.encod...
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[]{ ...
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_ALI...
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 ...
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).putLon...
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()); ...
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().registerTypeAdapt...
List<SessionOutput> outputList = new ArrayList<>(); UserSessionsOutput userSessionsOutput = userSessionsOutputMap.get(sessionId); if (userSessionsOutput != null) { for (Integer key : userSessionsOutput.getSessionOutputMap().keySet()) { //get output chars and set t...
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 = ...
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 = ...
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.gro...
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 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() ) { ...
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 ( boole...
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() ) { ...
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...
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(...
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.setInstanceFol...
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....
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()); ...
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); } Fil...
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...
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 ...
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 getT...
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 reque...
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.fi...
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; /** * 在保存用户时,发送用户修改通知消息, 由消息接收者异步进行较为耗时的通知邮件发送. * * 如果企...
// 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) { sup...
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,File...
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]; ...
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...
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>} pu...
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>...
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.setPag...
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...
//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-...
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"...
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 ComposeDicti...
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 valueProper...
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) { ...
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中对象的类型. ...
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 S...
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(ad...
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) ) ) { ...
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.o...
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 (endp...
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 pag...
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(o...
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) ...
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())...
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 St...
AtomicLong initValue = new AtomicLong(maxLoginAttempts); AtomicLong remainLoginAttempts = accountLockMap.putIfAbsent(getUsername(request), new AtomicLong(maxLoginAttempts)); if (remainLoginAttempts == null) { remainLoginAttempts = initValue; } remainLoginAttempts.get...
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(); ...
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 res...
// 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); ...
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>} /*** * 验证是否为重复提交 * @...
String sessionToken = (String)request.getSession().getAttribute("sessionToken"); if(null == sessionToken || "".equals(sessionToken)){ sessionToken = UUID.randomUUID().toString(); request.getSession().setAttribute("sessionToken",sessionToken ); //把这个sessionToken保存在redis中 //然后判断的时候根据redis是否有这个sessi...
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; ...
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...
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 Mu...
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); }...
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_...
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 ...
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 =...
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 =...
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_BOD...
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()) { ...
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.getServe...
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)...
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); } /** ...
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>} /** ...
String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection...
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; ...
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 = ra...
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{ priv...
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.s...
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 getApplicatio...
logger.debug("注入ApplicationContext到SpringContextHolder:" + applicationContext); if (SpringContextHolder.applicationContext != null) { logger.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext); } SpringContextHolder.applicationContext = ...
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" // ...
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 opera...
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 s...
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 (FileNotFoun...
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)c...
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; /...
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); } catc...
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; ...
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.HSSFColorPredefine...
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]*?\\/[...
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); ...
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); ...
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_...
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) par...
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.registerCorsConfigur...
CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.setAllowCredentials(true);//sessionid 多次访问一致 corsConfiguration.setAllowedOriginPatterns(getAllowOrigin()); // corsConfiguration.addAllowedOrigin("*");// 允许任何域名使用 corsConfiguration.addAllowedHeader("*...
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.setDataSourc...
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.d...
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 securityMan...
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); Map<String, String> map = new LinkedHashMap<>(); //登出 map.put("/logout", "logout"); //对所有用户认证 map.put("/api/dwsurvey/anon/**...
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_FUN...
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 ...
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"); re...
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); DelegatingFilterProxy proxy = new DelegatingFilterProxy(); proxy.setTargetFilterLifecycle(true); proxy.setTargetBeanName("shiroFilter"); filterRegistrationBean.setFilter(proxy); filterRegistrat...
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); foo...
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,...
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=ajaxBuildSaveOpti...
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 question...
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(req...
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"); ...