📄 coreutil.java
字号:
ReplacementEngine engine = new ReplacementEngine();
if(encoder != null) {
engine.setEncoder(encoder);
}
engine.addPattern("\\$\\{[^}]*\\}", createGlobalReplacer(), null);
engine.addPattern("\\$\\{[^}]*\\}", new Replacer() {
public String getReplacement(Pattern pattern, Matcher matcher, String replacementPattern) {
String match = matcher.group();
String key = match.substring(2, match.length() - 1);
try {
int idx = key.indexOf(":");
if (idx == -1) {
throw new Exception("String replacement pattern is in incorrect format for " + key
+ ". Must be <TYPE>:<key>");
}
String type = key.substring(0, idx);
key = key.substring(idx + 1);
if (log.isDebugEnabled())
log.debug("Found replacement variable " + type + ":" + key);
if (type.equalsIgnoreCase("property")) {
if (sessionInfo == null) {
return null;
}
return CoreServlet.getServlet().getPropertyDatabase().getProperty(
CoreUtil.getCurrentPropertyProfileId(sessionInfo.getHttpSession()),
sessionInfo.getUser().getPrincipalName(), key);
} else if (type.equalsIgnoreCase("session")) {
if (sessionInfo == null) {
return null;
}
if (key.equals("username")) {
return sessionInfo.getUser().getPrincipalName();
} else if (key.equals("email")) {
return sessionInfo.getUser().getEmail();
} else if (key.equals("fullname")) {
return sessionInfo.getUser().getFullname();
} else if (key.equals("clientProxyURL")) {
String proxyURL = getProxyURL(sessionInfo.getUser(), CoreUtil.getCurrentPropertyProfileId(sessionInfo
.getHttpSession()));
return proxyURL == null ? "" : proxyURL;
} else if (key.equals("password")) {
/**
* LDP - This is broken, I'm guessing that the VPN
* client session is different from the browser
* session so the scheme is not being found
*/
AuthenticationScheme scheme = (AuthenticationScheme) sessionInfo.getHttpSession().getAttribute(
Constants.AUTH_SESSION);
if (scheme != null) {
char[] pw = CoreServlet.getServlet().getLogonController().getPasswordFromCredentials(scheme);
return pw == null ? "" : new String(pw);
} else {
return "";
}
} else {
throw new Exception("Unknown key " + key + " for type " + type + ".");
}
} else if (type.equalsIgnoreCase("attr")) {
if (sessionInfo == null) {
return null;
}
UserAttributeDefinition def = CoreServlet.getServlet().getUserDatabase().getUserAttributeDefinition(key);
if (def == null) {
log.warn("Invalid user attribute '" + key + "'");
return null;
} else {
return sessionInfo.getUser().getAttributes().getProperty(key, def.getDefaultValue());
}
} else if (type.equalsIgnoreCase("ticket")) {
if (sessionInfo == null) {
return null;
}
if (key.equals("id")) {
return (String) sessionInfo.getHttpSession().getAttribute(Constants.VPN_AUTHORIZATION_TICKET);
} else {
throw new Exception(
"String replacement pattern for ticket only supports the 'id' key. I.e. ${ticket:new}");
}
}
} catch (Exception e) {
log.error("A replacement failed for " + key + ".", e);
}
return null;
}
}, null);
return engine.replace(input);
}
public static String platformPath(String originalPath) {
String p = originalPath.replace("/", File.separator).replace("\\", File.separator);
if (log.isDebugEnabled())
log.debug("Original path of '" + originalPath + "' is '" + p + "' for platform");
return p;
}
public static long generateChecksum(File f) throws IOException {
Adler32 alder = new Adler32();
FileInputStream fin = new FileInputStream(f);
CheckedInputStream in = new CheckedInputStream(fin, alder);
byte[] buf = new byte[32768];
Util.readFullyIntoBuffer(in, buf);
alder = (Adler32) in.getChecksum();
try {
in.close();
} catch (IOException ex) {
}
try {
fin.close();
} catch (IOException ex1) {
}
return alder.getValue();
}
public static User[] getUsersInRole(Role role, UserDatabase database) throws Exception {
User[] u = database.listAllUsers("*");
List ur = new ArrayList();
for (int i = 0; i < u.length; i++) {
Role[] r = u[i].getRoles();
for (int j = 0; j < r.length; j++) {
if (r[j].getPrincipalName().equals(role.getPrincipalName())) {
ur.add(u[i]);
break;
}
}
}
return (User[]) ur.toArray(new User[ur.size()]);
}
/**
* Dump tile attributes to {@link System#err}.
*
* @param pageContext page context from which to get tile.
*/
public static void dumpTileScope(PageContext pageContext) {
// TODO Auto-generated method stub
ComponentContext compContext = (ComponentContext) pageContext.getAttribute(ComponentConstants.COMPONENT_CONTEXT,
PageContext.REQUEST_SCOPE);
System.err.println("Tile attributes");
for (Iterator i = compContext.getAttributeNames(); i.hasNext();) {
String n = (String) i.next();
System.err.println(" " + n + " = " + compContext.getAttribute(n));
}
}
/**
* Get message resources given the ID and the session. <code>null</code>
* will be returned if no such resources exist.
*
* @param session session
* @param key bundle key
* @return resources
*/
public static MessageResources getMessageResources(HttpSession session, String key) {
ServletContext context = session.getServletContext();
ModuleConfig moduleConfig = ModuleUtils.getInstance().getModuleConfig("", context);
return (MessageResources) context.getAttribute(key + moduleConfig.getPrefix());
}
/**
* Set a user attribute (note that the user database must be updated
* manually using {@link UserDatabase#updateAttributes(String, Properties)}).
* The attribute will be removed if it is the same value as the default from
* the definition.
*
* @param sessionInfo session of the user performing the change
* @param user user to set attributes on
* @param definition user attribute definition object
* @param value value
*/
public static void setUserAttribute(SessionInfo sessionInfo, UserAttributeDefinition definition, String value, User user)
throws Exception {
String oldValue = null;
if (definition.getDefaultValue().equals(value)) {
oldValue = (String) user.getAttributes().remove(definition.getName());
} else {
oldValue = (String) user.getAttributes().put(definition.getName(), value);
}
if (oldValue == null)
oldValue = "";
if (value == null)
value = "";
//if ((oldValue == null && value != null) || (value == null && oldValue != null) || (!oldValue.equals(value))) {
if (!oldValue.equals(value)) {
if (log.isInfoEnabled())
log.info("User attribute '" + definition.getName() + "' has changed for user '" + user.getPrincipalName()
+ "' to '" + value + "'");
CoreServlet.getServlet().getUserDatabase().updateAttribute(user.getPrincipalName(), definition.getName(), value);
PropertyChangeEvent evt = new PropertyChangeEvent(CoreServlet.getServlet(), CoreEventConstants.USER_ATTRIBUTE_CHANGED,
definition, sessionInfo, oldValue, value, CoreEvent.STATE_SUCCESSFUL);
evt.addAttribute(CoreAttributeConstants.EVENT_ATTR_USER_ATTRIBUTE_USER, user.getPrincipalName());
CoreServlet.getServlet().fireCoreEvent(evt);
}
}
/**
* Adds a new path to the paths search for native libraries. Because
* <i>java.library.path</i> cannot be changed at runtime. This method is a
* workaround that directly changes a private variables in the Sun classes,
* so will probably not work on other JVMs.
*
* @param path path to add
* @throws IOException ioe
*/
public static void addLibraryPath(String path) throws IOException {
try {
Field field = ClassLoader.class.getDeclaredField("usr_paths");
field.setAccessible(true);
String[] paths = (String[]) field.get(null);
for (int i = 0; i < paths.length; i++) {
if (path.equals(paths[i])) {
return;
}
}
String[] tmp = new String[paths.length + 1];
System.arraycopy(paths, 0, tmp, 0, paths.length);
tmp[paths.length] = path;
field.set(null, tmp);
} catch (IllegalAccessException e) {
throw new IOException("Failed to get permissions to set library path");
} catch (NoSuchFieldException e) {
/*
* This will likely happen if not Suns JVM. Just in case it does
* work, we'll set java.library.path
*/
System.setProperty("java.library.path", System.getProperty("java.library.path") + File.pathSeparator + path);
log.warn("Failed to set library path using Sun JDK workaround. Just setting java.library.path in case "
+ "it works. If it doesn't, plugins that use native libraries will probably fail. To fix "
+ "this you will have to alter " + ContextHolder.getContext().getConfDirectory().getAbsolutePath()
+ File.separator + "wrapper.conf to include the additional library path '" + path + "'.");
}
}
/**
* Replace all occurences of string <i>token</i> in <i>source</i> with
* <i>value</i>.
*
* @param source source to search for occurences of <i>token</i>
* @param token string to search for
* @param value value to replace occurences of <i>token</i> with
* @return processed string
*/
public static String replaceAllTokens(String source, String token, String value) {
return StringUtils.replace(source, token, value);
}
/**
* Add a new upload to the sessions upload manager, creating one if needed.
*
* @param session session
* @param upload upload
* @return id;
*/
public static int addUpload(HttpSession session, UploadDetails upload) {
synchronized (session) {
UploadManager mgr = (UploadManager) session.getAttribute(Constants.UPLOAD_MANAGER);
if (mgr == null) {
mgr = new UploadManager();
session.setAttribute(Constants.UPLOAD_MANAGER, mgr);
}
return mgr.addUpload(upload);
}
}
/**
* Remove an upload given its id, removing the upload manager if it is
* empty.
*
* @param session session
* @param uploadId upload id
* @return removed upload details
*/
public static UploadDetails removeUpload(HttpSession session, int uploadId) {
UploadManager mgr = (UploadManager) session.getAttribute(Constants.UPLOAD_MANAGER);
if (mgr != null) {
UploadDetails details = mgr.removeUpload(uploadId);
if (mgr.isEmpty()) {
session.removeAttribute(Constants.UPLOAD_MANAGER);
}
return details;
}
return null;
}
/**
* Get an upload given its id. <code>null</code> will be retur
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -