csip.Utils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of csip-core Show documentation
Show all versions of csip-core Show documentation
The Cloud Services Integration Platform is a SoA implementation to offer a Model-as-a-Service framework, Application Programming Interface, deployment infrastructure, and service implementations for environmental modeling.
/*
* $Id: Utils.java dcb5aa2353e5 2020-02-19 od $
*
* This file is part of the Cloud Services Integration Platform (CSIP),
* a Model-as-a-Service framework, API and application suite.
*
* 2012-2019, Olaf David and others, OMSLab, Colorado State University.
*
* OMSLab licenses this file to you under the MIT license.
* See the LICENSE file in the project root for more information.
*/
package csip;
import csip.annotations.Author;
import csip.annotations.Description;
import csip.annotations.Documentation;
import csip.annotations.License;
import csip.annotations.State;
import csip.annotations.Name;
import csip.annotations.VersionInfo;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
/**
* CSIP core package Utilities.
*
* @author od
*/
public class Utils {
static final void checkRemoteAccessACL(HttpServletRequest req) {
String reqIp = req.getHeader("X-Forwarded-For");
if (reqIp == null) {
reqIp = req.getRemoteAddr();
}
if (!checkRemoteAccessACL(reqIp)) {
Config.LOG.log(Level.WARNING, req.getMethod() + " " + req.getRequestURI() + ", denied for " + reqIp);
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
Config.LOG.log(Level.INFO, req.getMethod() + " " + req.getRequestURI() + ", OK for " + reqIp);
}
static final boolean checkRemoteAccessACL(String ip) {
String acls = Config.getString(Config.CSIP_REMOTE_ACL);
String[] acl = acls.split("\\s+");
for (String ace : acl) {
try {
if (new IpMatcher(ace).matches(ip)) {
return true;
}
} catch (UnknownHostException E) {
Config.LOG.log(Level.WARNING, E.getMessage(), E);
return false;
}
}
return false;
}
/**
* Resolve a string with system and CSIP properties.
*
* @param str the string to resolve
* @return the resolved string.
*/
public static String resolve(String str) {
if (str == null) {
return null;
}
if (!str.contains("${")) {
return str;
}
String res = resolve0(str, Config.getMergedProperties(), new HashSet<>());
if (res.contains("${")) {
Config.LOG.warning("Resolving one or more varariables failed in: " + res);
}
return res;
}
/**
* property substitution in a string.
*
* @param str
* @return
*/
private static String resolve0(String str, Properties prop, Set keys) {
int idx = 0;
while (idx < str.length()) {
int start = str.indexOf("${", idx);
int end = str.indexOf("}", idx);
if (start == -1 || end == -1 || end < start) {
break;
}
String key = str.substring(start + 2, end);
if (keys.contains(key)) {
System.err.println("Circular property reference: " + key);
break;
}
String val = prop.getProperty(key);
if (val != null) {
keys.add(key);
val = resolve0(val, prop, keys);
keys.remove(key);
str = str.replace("${" + key + "}", val);
idx = start + val.length();
} else {
idx = start + key.length() + 3;
}
}
return str;
}
static void callStaticMethodIfExist(Class> c, String method) {
try {
Method m = c.getMethod(method);
m.invoke(null);
Config.LOG.info(" Invoked '" + method + "' in: " + c);
} catch (NoSuchMethodException ex) {
return; // no problem
} catch (SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Config.LOG.log(Level.SEVERE, null, ex);
}
}
static String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit) {
return bytes + " B";
}
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
static String getServicePath(Class> c) {
Path p = c.getAnnotation(Path.class);
return (p != null) ? p.value() : "";
}
static String getServiceName(Class> c) {
Name p = c.getAnnotation(Name.class);
return (p != null) ? p.value() : c.getName();
}
/**
* Populate service matainfo into a JSONObject
*
* @return The service name or null if there is none
*/
public static JSONObject getServiceInfo(Class> c) throws JSONException {
JSONObject o = new JSONObject();
Name p = c.getAnnotation(Name.class);
if (p != null) {
o.put("name", p.value());
} else {
oms3.annotations.Name n = c.getAnnotation(oms3.annotations.Name.class);
if (n != null) {
o.put("name", n.value());
}
}
Description d = c.getAnnotation(Description.class);
if (d != null) {
o.put("description", d.value());
} else {
oms3.annotations.Description n = c.getAnnotation(oms3.annotations.Description.class);
if (n != null) {
o.put("description", n.value());
}
}
Documentation doc = c.getAnnotation(Documentation.class);
if (doc != null) {
o.put("documentation", doc.value());
}
License lic = c.getAnnotation(License.class);
if (lic != null) {
o.put("license", lic.value());
}
VersionInfo ver = c.getAnnotation(VersionInfo.class);
if (ver != null) {
o.put("version", ver.value());
}
Author aut = c.getAnnotation(Author.class);
if (aut != null) {
o.put("author", (aut.name() + " " + aut.email() + " " + aut.org()).trim());
}
Deprecated dep = c.getAnnotation(Deprecated.class);
if (dep != null) {
o.put("state", State.DEPRECATED);
} else {
State sta = c.getAnnotation(State.class);
if (sta != null) {
o.put("state", sta.value());
}
}
o.put("built", Config.getFullVersion());
return o;
}
public static File[] expandFiles(File work, String pattern) throws IOException {
if (pattern == null || pattern.isEmpty()) {
return new File[]{};
}
List f = new ArrayList<>();
final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + work + "/" + pattern);
Files.walkFileTree(Paths.get(work.toString()), new SimpleFileVisitor() {
@Override
public FileVisitResult postVisitDirectory(java.nio.file.Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(java.nio.file.Path file, BasicFileAttributes attrs) throws IOException {
if (matcher.matches(file)) {
f.add(file.toFile());
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(java.nio.file.Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
return f.toArray(new File[0]);
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy