Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
* Java wrapper library for PMA.start, a universal viewer for whole slide
* imaging and microscopy
*
*
* @author Yassine Iddaoui
* @version 2.0.0.116
*/
public class Core {
/**
* So afterwards we can look up what username actually belongs to a sessions
*/
private static Map pmaSessions = new HashMap();
/**
* So afterwards we can determine the PMA.core URL to connect to for a given
* SessionID
*/
private static Map pmaUsernames = new HashMap<>();
/**
* A caching mechanism for slide information; obsolete and should be improved
* through httpGet()
*/
private static Map pmaSlideInfos = new HashMap();
private static final String pmaCoreLiteURL = "http://localhost:54001/";
private static final String pmaCoreLiteSessionID = "SDK.Java";
private static Boolean pmaUseCacheWhenRetrievingTiles = true;
/**
* Keep track of how much data was downloaded
*/
@SuppressWarnings("serial")
private static Map pmaAmountOfDataDownloaded = new HashMap() {
{
put(pmaCoreLiteSessionID, 0);
}
};
/**
* Object Mapper for Jackson library
*/
private static ObjectMapper objectMapper = new ObjectMapper();
/**
* @return the pmaSessions
*/
public static Map getPmaSessions() {
return pmaSessions;
}
/**
* @return the pmaUsernames
*/
public static Map getPmaUsernames() {
return pmaUsernames;
}
/**
* @return the pmaSlideInfos
*/
public static Map getPmaSlideInfos() {
return pmaSlideInfos;
}
/**
* @return the pmaCoreLiteURL
*/
public static String getPmaCoreLiteURL() {
return pmaCoreLiteURL;
}
/**
* @return the pmaCoreLiteSessionID
*/
public static String getPmaCoreLiteSessionID() {
return pmaCoreLiteSessionID;
}
/**
* @return the pmaAmountOfDataDownloaded
*/
public static Map getPmaAmountOfDataDownloaded() {
return pmaAmountOfDataDownloaded;
}
/**
* Readable bytes for upload and download methods. To integrate into the progress bar.
*/
public static BlockingQueue bytes = new LinkedBlockingQueue<>();
/**
* This method is used to determine whether the Java SDK runs in debugging mode
* or not. When in debugging mode (flag = true), extra output is produced when
* certain conditions in the code are not met
*
* @param flag Debugging mode (activated or deactivated)
*/
public static void setDebugFlag(boolean flag) {
PMA.setDebugFlag(flag);
if (flag) {
if (PMA.logger != null) {
PMA.logger.severe(
"Debug flag enabled. You will receive extra feedback and messages from the Java SDK (like this one)");
}
}
}
/**
* This method is used to get the session's ID
*
* @param varargs Array of optional arguments
*
* sessionID : First optional argument(String), default
* value(null), session's ID
*
* @return The same sessionID if explicited, otherwise it recovers a session's
* ID
*/
private static String sessionId(String... varargs) {
// setting the default value when argument's value is omitted
String sessionID = varargs.length > 0 ? varargs[0] : null;
if (sessionID == null) {
// if the sessionID isn't specified, maybe we can still recover it somehow
return firstSessionId();
} else {
// nothing to do in this case; a SessionID WAS passed along, so just continue
// using it
return sessionID;
}
}
/**
* This method is used to get PMA.core active session
*
* @return PMA.core active session
*/
private static String firstSessionId() {
// do we have any stored sessions from earlier login events?
if (pmaSessions.size() > 0) {
// yes we do! This means that when there's a PMA.core active session AND
// PMA.core.lite version running,
// the PMA.core active will be selected and returned
return pmaSessions.keySet().toArray()[0].toString();
} else {
// ok, we don't have stored sessions; not a problem per se...
if (pmaIsLite()) {
if (!pmaSlideInfos.containsKey(pmaCoreLiteSessionID)) {
pmaSlideInfos.put(pmaCoreLiteSessionID, new HashMap());
}
if (!pmaAmountOfDataDownloaded.containsKey(pmaCoreLiteSessionID)) {
pmaAmountOfDataDownloaded.put(pmaCoreLiteSessionID, 0);
}
return pmaCoreLiteSessionID;
} else {
// no stored PMA.core sessions found NOR PMA.core.lite
return null;
}
}
}
/**
* This method is used to get the url related to the session's ID
*
* @param varargs Array of optional arguments
*
* sessionID : First optional argument(String), default
* value(null), session's ID
*
* @return Url related to the session's ID
* @throws Exception if sessionID is invalid
*/
public static String pmaUrl(String... varargs) throws Exception {
// setting the default value when argument's value is omitted
String sessionID = varargs.length > 0 ? varargs[0] : null;
sessionID = sessionId(sessionID);
if (sessionID == null) {
// sort of a hopeless situation; there is no URL to refer to
return null;
} else if (sessionID.equals(pmaCoreLiteSessionID)) {
return pmaCoreLiteURL;
} else {
// assume sessionID is a valid session; otherwise the following will generate an
// error
if (pmaSessions.containsKey(sessionID)) {
String url = pmaSessions.get(sessionID).toString();
if (!url.endsWith("/")) {
url = url + "/";
}
return url;
} else {
if (PMA.logger != null) {
PMA.logger.severe("Invalid sessionID:" + sessionID);
}
throw new Exception("Invalid sessionID:" + sessionID);
}
}
}
/**
* This method is used to retrieve HTML Code from URL
*
* @param url
* to get HTML code from
* @return String HTML code generated from the url argument
*/
public static String urlReader(String url) {
try {
URL urlResource = new URL(url);
URLConnection con = urlResource.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
return IOUtils.toString(in, encoding);
} catch (Exception e) {
return null;
}
}
/**
* This method is used to parse a XML content
*
* @param s
* XML content to parse
* @return Document parsed XML
*/
public static Document domParser(String s) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
InputSource inputStream = new InputSource();
inputStream.setCharacterStream(new StringReader(s));
return documentBuilder.parse(inputStream);
} catch (Exception e) {
return null;
}
}
/**
* This method is used to encode a String to be compatible as a url
*
* @param arg
* string to be encoded
* @return String encoded String to be compatible as a url
*/
public static String pmaQ(String arg) {
if (arg == null) {
return "";
} else {
try {
return URLEncoder.encode(arg, "UTF-8").replace("+", "%20");
} catch (Exception e) {
return "";
}
}
}
/**
* This method is used to get the list of sessions
*
* @param pmaControlURL
* URL for PMA.Control
* @param pmaCoreSessionID
* PMA.core session ID
* @return JSONArray containing the list of sessions
*/
public static JSONArray getSessions(String pmaControlURL, String pmaCoreSessionID) {
String url = join(pmaControlURL, "api/Sessions?sessionID=" + pmaQ(pmaCoreSessionID));
System.out.println(url);
try {
URL urlResource = new URL(url);
HttpURLConnection con;
if (url.startsWith("https")) {
con = (HttpsURLConnection) urlResource.openConnection();
} else {
con = (HttpURLConnection) urlResource.openConnection();
}
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
String jsonString = getJSONAsStringBuffer(con).toString();
JSONArray jsonResponse = getJSONArrayResponse(jsonString);
return jsonResponse;
} catch (Exception e) {
System.out.print(e.getMessage());
return null;
}
}
/**
*
* This method is used to get the list of sessions' IDs
*
* @param pmaControlURL
* URL for PMA.Control
* @param pmaCoreSessionID
* PMA.core session ID
* @return newSession containing the sessions' IDs
*/
public static Map> getSessionIds(String pmaControlURL, String pmaCoreSessionID) {
JSONArray fullSessions = getSessions(pmaControlURL, pmaCoreSessionID);
Map> newSession = new HashMap<>();
for (int i = 0; i < fullSessions.length(); i++) {
Map sessData = new HashMap();
try {
sessData.put("LogoPath", fullSessions.getJSONObject(i).getString("LogoPath"));
sessData.put("StartsOn", fullSessions.getJSONObject(i).getString("StartsOn"));
sessData.put("EndsOn", fullSessions.getJSONObject(i).getString("EndsOn"));
sessData.put("ModuleId", fullSessions.getJSONObject(i).getString("ModuleId"));
sessData.put("State", fullSessions.getJSONObject(i).getString("State"));
newSession.put(fullSessions.getJSONObject(i).getString("Id"), sessData);
} catch (JSONException e) {
// ignore
}
}
return newSession;
}
/**
* This method is used to get case collections
*
* @param pmaControlURL
* URL for PMA.Control
* @param pmaCoreSessionID
* PMA.core session ID
* @return JSONArray containing the list of case sessions
*/
public static JSONArray getCaseCollections(String pmaControlURL, String pmaCoreSessionID) {
String url = join(pmaControlURL, "api/CaseCollections?sessionID=" + pmaQ(pmaCoreSessionID));
System.out.println(url);
try {
URL urlResource = new URL(url);
HttpURLConnection con;
if (url.startsWith("https")) {
con = (HttpsURLConnection) urlResource.openConnection();
} else {
con = (HttpURLConnection) urlResource.openConnection();
}
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
String jsonString = getJSONAsStringBuffer(con).toString();
JSONArray jsonResponse = getJSONArrayResponse(jsonString);
return jsonResponse;
} catch (Exception e) {
System.out.print(e.getMessage());
return null;
}
}
/**
* This method is used to get the list of projects
*
* @param pmaControlURL
* URL for PMA.Control
* @param pmaCoreSessionID
* PMA.core session ID
* @return JSONArray containing the list of projects
*/
public static JSONArray getProjects(String pmaControlURL, String pmaCoreSessionID) {
String url = join(pmaControlURL, "api/Projects?sessionID=" + pmaQ(pmaCoreSessionID));
System.out.println(url);
try {
URL urlResource = new URL(url);
HttpURLConnection con;
if (url.startsWith("https")) {
con = (HttpsURLConnection) urlResource.openConnection();
} else {
con = (HttpURLConnection) urlResource.openConnection();
}
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
String jsonString = getJSONAsStringBuffer(con).toString();
JSONArray jsonResponse = getJSONArrayResponse(jsonString);
return jsonResponse;
} catch (Exception e) {
System.out.print(e.getMessage());
return null;
}
}
/**
* This method is used to check to see if PMA.core.lite (server component of
* PMA.start) is running at a given endpoint. if pmaCoreURL is omitted, default
* check is to see if PMA.start is effectively running at localhost (defined by
* pmaCoreLiteURL). note that PMA.start may not be running, while it is actually
* installed. This method doesn't detect whether PMA.start is installed; merely
* whether it's running! if pmaCoreURL is specified, then the method checks if
* there's an instance of PMA.start (results in True), PMA.core (results in
* False) or nothing (at least not a Pathomation software platform component) at
* all (results in None)
*
* @param varargs Array of optional arguments
*
* pmaCoreURL : First optional argument(String), default
* value(Class field pmaCoreLiteURL), url of PMA.core instance
*
* @return True if an instance of PMA.core.lite is running, false otherwise
*/
private static Boolean pmaIsLite(String... varargs) {
// setting the default value when argument's value is omitted
String pmaCoreURL = varargs.length > 0 ? varargs[0] : pmaCoreLiteURL;
String url = PMA.join(pmaCoreURL, "api/json/IsLite");
try {
String jsonString = PMA.httpGet(url, "application/json");
return jsonString.equals("true");
} catch (Exception e) {
// this happens when NO instance of PMA.core is detected
e.printStackTrace();
if (PMA.logger != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
PMA.logger.severe(sw.toString());
}
return null;
}
}
/**
* This method is used to define which content will be received "XML" or "Json"
* for "API" Web service calls
*
* @param varargs Array of optional arguments
*
* sessionID : First optional argument(String), default
* value(null), session's ID
*
*
* xml : Second optional argument(Boolean), default value(true),
* define if method will return XML or Json content
*
* @return Add a sequence to the url to specify which content to be received
* (XML or Json)
*/
private static String apiUrl(Object... varargs) {
// setting the default values when arguments' values are omitted
String sessionID = null;
Boolean xml = false;
if (varargs.length > 0) {
if (!(varargs[0] instanceof String) && varargs[0] != null) {
if (PMA.logger != null) {
PMA.logger.severe("apiUrl() : Invalid argument");
}
throw new IllegalArgumentException("...");
}
sessionID = (String) varargs[0];
}
if (varargs.length > 1) {
if (!(varargs[1] instanceof Boolean) && varargs[1] != null) {
if (PMA.logger != null) {
PMA.logger.severe("apiUrl() : Invalid argument");
}
throw new IllegalArgumentException("...");
}
xml = (Boolean) varargs[1];
}
// let's get the base URL first for the specified session
String url;
try {
url = pmaUrl(sessionID);
} catch (Exception e) {
e.printStackTrace();
if (PMA.logger != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
PMA.logger.severe(sw.toString());
}
url = null;
}
if (url == null) {
// sort of a hopeless situation; there is no URL to refer to
return null;
}
// remember, _pma_url is guaranteed to return a URL that ends with "/"
if (xml) {
return PMA.join(url, "api/xml/");
} else {
return PMA.join(url, "api/json/");
}
}
/**
* This method concatenates strings with "/"
*
* @param s
* @return
*/
private static String join(String... s) {
String joinString = "";
for (String ss : s) {
if (!joinString.endsWith("/") && (!joinString.equals(""))) {
joinString = joinString.concat("/");
}
if (ss != null) {
joinString = joinString.concat(ss);
}
}
return joinString;
}
/**
* This method is used to get a list of the values of "String" tags of a XML
* document
*
* @param root
* XML document
* @param varargs limit it's an optional argument (int), default value set to "0"
* @return List{@literal <}String{@literal >} a list of the values of "String"
* tags of a XML document
*/
public static List xmlToStringArray(Document root, Integer... varargs) {
// setting the default value when argument's value is omitted
int limit = varargs.length > 0 ? varargs[0] : 0;
NodeList eLs = root.getElementsByTagName("string");
List l = new ArrayList<>();
if (limit > 0) {
for (int i = 0; i < limit; i++) {
l.add(eLs.item(i).getFirstChild().getNodeValue());
}
} else {
for (int i = 0; i < eLs.getLength(); i++) {
l.add(eLs.item(i).getFirstChild().getNodeValue());
}
}
return l;
}
/**
* This method is used to create the query URL for a session ID
*
* @param varargs Array of optional arguments
*
* sessionID : First optional argument(String), default
* value(null), session's ID
*
* @return Query URL
*/
public static String queryUrl(String... varargs) {
// setting the default value when argument's value is omitted
String sessionID = varargs.length > 0 ? varargs[0] : null;
// let's get the base URL first for the specified session
try {
String url = pmaUrl(sessionID);
if (url == null) {
// sort of a hopeless situation; there is no URL to refer to
return null;
}
// remember, pmaUrl is guaranteed to return a URL that ends with "/"
return PMA.join(url, "query/json/");
} catch (Exception e) {
e.printStackTrace();
if (PMA.logger != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
PMA.logger.severe(sw.toString());
}
return null;
}
}
/**
* checks to see if PMA.core.lite (server component of PMA.start) is running at
* a given endpoint. if pmaCoreURL is omitted, default check is to see if
* PMA.start is effectively running at localhost (defined by pmaCoreLiteURL).
* note that PMA.start may not be running, while it is actually installed. This
* method doesn't detect whether PMA.start is installed; merely whether it's
* running! if pmaCoreURL is specified, then the method checks if there's an
* instance of PMA.start (results in True), PMA.core (results in False) or
* nothing (at least not a Pathomation software platform component) at all
* (results in None)
*
* @param varargs Array of optional arguments
*
* pmaCoreURL : First optional argument(String), default
* value(Class field pmaCoreLiteURL), url of PMA.core instance
*
* @return Checks if there is a PMA.core.lite or PMA.core instance running
*/
public static Boolean isLite(String... varargs) {
// setting the default value when argument's value is omitted
String pmaCoreURL = varargs.length > 0 ? varargs[0] : pmaCoreLiteURL;
// See if there's a PMA.core.lite or PMA.core instance running at pmacoreURL
return pmaIsLite(pmaCoreURL);
}
/**
* This method is used to get the version number
*
* @param varargs Array of optional arguments
*
* pmaCoreURL : First optional argument(String), default
* value(Class field pmaCoreLiteURL), url of PMA.core instance
*
* @return Version number
*/
public static String getVersionInfo(String... varargs) {
// setting the default value when argument's value is omitted
String pmaCoreURL = varargs.length > 0 ? varargs[0] : pmaCoreLiteURL;
// Get version info from PMA.core instance running at pmacoreURL.
// Return null if PMA.core not found running at pmacoreURL endpoint
// purposefully DON'T use helper function apiUrl() here:
// why? because GetVersionInfo can be invoked WITHOUT a valid SessionID;
// apiUrl() takes session information into account
String url = PMA.join(pmaCoreURL, "api/json/GetVersionInfo");
String version = null;
if (PMA.debug) {
System.out.println(url);
}
try {
URL urlResource = new URL(url);
HttpURLConnection con;
if (url.startsWith("https")) {
con = (HttpsURLConnection) urlResource.openConnection();
} else {
con = (HttpURLConnection) urlResource.openConnection();
}
con.setRequestMethod("GET");
String jsonString = PMA.getJSONAsStringBuffer(con).toString();
if (PMA.isJSONObject(jsonString)) {
JSONObject jsonResponse = PMA.getJSONObjectResponse(jsonString);
if (jsonResponse.has("Code")) {
if (PMA.logger != null) {
PMA.logger.severe("getVersionInfo failed : " + jsonResponse.get("Message"));
}
throw new Exception("getVersionInfo failed : " + jsonResponse.get("Message"));
} else if (jsonResponse.has("d")) {
version = jsonResponse.getString("d");
} else {
return null;
}
} else {
version = jsonString.replaceAll("\"$|^\"", "");
}
if (version.startsWith("3.0")) {
String revision = getBuildRevision(pmaCoreURL);
if (!revision.isEmpty()) {
version += "." + revision;
}
}
return version;
} catch (Exception e) {
e.printStackTrace();
if (PMA.logger != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
PMA.logger.severe(sw.toString());
}
return null;
}
}
/**
* This method is used to get version info from PMA.control instance running at
* pmacontrolURL
*
* @param pmaControlURL
* PMA Control's URL
* @return JSONObject containing the version info
*/
public static JSONObject getVersionInfoPmaControl(String pmaControlURL) {
// Get version info from PMA.control instance running at pmacontrolURL
// why? because GetVersionInfo can be invoked WITHOUT a valid SessionID;
// _pma_api_url() takes session information into account
String url = join(pmaControlURL, "api/version");
try {
URL urlResource = new URL(url);
HttpURLConnection con;
if (url.startsWith("https")) {
con = (HttpsURLConnection) urlResource.openConnection();
} else {
con = (HttpURLConnection) urlResource.openConnection();
}
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
String jsonString = getJSONAsStringBuffer(con).toString();
JSONObject jsonResponse = getJSONResponse(jsonString);
return jsonResponse;
} catch (Exception e) {
System.out.print(e.getMessage());
return null;
}
}
/**
* This method checks the spelling of the server version, namely the length.
*
* @param serverVersion
* @return
*/
private static boolean doesServerSupportPostAuth(String serverVersion) {
if (serverVersion == null || serverVersion.length() == 0) {
return false;
}
String[] version = serverVersion.split("\\.");
if (version.length != 4) {
return false;
}
try {
int major = Integer.parseInt(version[0], 10);
int build = Integer.parseInt(version[3], 10);
return major > 2 || (major == 2 && build >= 1836);
} catch (Exception e) {
return false;
}
}
/**
* This method is used to get the version number
*
* @param varargs Array of optional arguments
*
* pmaCoreURL : First optional argument(String), default
* value(Class field pmaCoreLiteURL), url of PMA.core instance
*
* @return Version number
*/
public static String getBuildRevision(String... varargs) {
// setting the default value when argument's value is omitted
String pmaCoreURL = varargs.length > 0 ? varargs[0] : pmaCoreLiteURL;
String url = PMA.join(pmaCoreURL, "api/json/GetBuildRevision");
String version = null;
if (PMA.debug) {
System.out.println(url);
}
try {
URL urlResource = new URL(url);
HttpURLConnection con;
if (url.startsWith("https")) {
con = (HttpsURLConnection) urlResource.openConnection();
} else {
con = (HttpURLConnection) urlResource.openConnection();
}
con.setRequestMethod("GET");
String jsonString = PMA.getJSONAsStringBuffer(con).toString();
if (PMA.isJSONObject(jsonString)) {
JSONObject jsonResponse = PMA.getJSONObjectResponse(jsonString);
if (jsonResponse.has("Code")) {
if (PMA.logger != null) {
PMA.logger.severe("getBuildRevision failed : " + jsonResponse.get("Message"));
}
throw new Exception("getBuildRevision failed : " + jsonResponse.get("Message"));
} else if (jsonResponse.has("d")) {
version = jsonResponse.getString("d");
} else {
return null;
}
} else {
version = jsonString.replaceAll("\"$|^\"", "");
}
return version;
} catch (Exception e) {
e.printStackTrace();
if (PMA.logger != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
PMA.logger.severe(sw.toString());
}
return null;
}
}
/**
* This method is used to get the API version in a list fashion
*
* @param varargs Array of optional arguments
*
* pmacoreURL : First optional argument(String), default
* value(Class field pmaCoreLiteURL), url of PMA.core instance
*
* @return API version in a list fashion
* @throws Exception If GetAPIVersion isn't available on the API
*/
public static List getAPIVersion(String... varargs) throws Exception {
// setting the default values when arguments' values are omitted
String pmaCoreURL = varargs.length > 0 ? varargs[0] : pmaCoreLiteURL;
String url = PMA.join(pmaCoreURL, "api/json/GetAPIVersion");
if (PMA.debug) {
System.out.println(url);
}
String jsonString = null;
try {
URL urlResource = new URL(url);
HttpURLConnection con;
if (url.startsWith("https")) {
con = (HttpsURLConnection) urlResource.openConnection();
} else {
con = (HttpURLConnection) urlResource.openConnection();
}
con.setRequestMethod("GET");
jsonString = PMA.getJSONAsStringBuffer(con).toString();
} catch (Exception e) {
e.printStackTrace();
if (PMA.logger != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
PMA.logger.severe(sw.toString());
}
return null;
}
List version = null;
try {
if (PMA.isJSONObject(jsonString)) {
JSONObject jsonResponse = PMA.getJSONObjectResponse(jsonString);
if (jsonResponse.has("Code")) {
if (PMA.logger != null) {
PMA.logger.severe("get_api_version resulted in: " + jsonResponse.get("Message"));
}
throw new Exception("get_api_version resulted in: " + jsonResponse.get("Message"));
} else if (jsonResponse.has("d")) {
JSONArray array = jsonResponse.getJSONArray("d");
version = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
version.add(array.optInt(i));
}
} else {
return null;
}
} else {
JSONArray jsonResponse = getJSONArrayResponse(jsonString);
version = new ArrayList<>();
for (int i = 0; i < jsonResponse.length(); i++) {
version.add(jsonResponse.optInt(i));
}
}
return version;
} catch (Exception e) {
e.printStackTrace();
if (PMA.logger != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
PMA.logger.severe(sw.toString());
PMA.logger.severe("GetAPIVersion method not available at " + pmaCoreURL);
}
throw new Exception("GetAPIVersion method not available at " + pmaCoreURL);
}
}
/**
* This method is used to get the API version in a single string
*
* @param varargs Array of optional arguments
*
* pmacoreURL : First optional argument(String), default
* value(Class field pmaCoreLiteURL), url of PMA.core instance
*
* @return API version in a single string
* @throws Exception If GetAPIVersion isn't available on the API
*
*/
public static String getAPIVersionString(String... varargs) throws Exception {
// setting the default values when arguments' values are omitted
String pmaCoreURL = varargs.length > 0 ? varargs[0] : pmaCoreLiteURL;
List version = getAPIVersion(pmaCoreURL);
String versionString = version.stream().map(n -> (n + ".")).collect(Collectors.joining("", "", ""));
return versionString.substring(0, versionString.length() - 1);
}
/**
* This method is used to authenticate & connect to a PMA.core instance
* using credentials
*
* @param varargs Array of optional arguments
*
* pmacoreURL : First optional argument(String), default
* value(Class field pmaCoreLiteURL), url of PMA.core instance
*
*
* pmacoreUsername : Second optional argument(String), default
* value(""), username for PMA.core instance
*
*
* pmacorePassword : Third optional argument(String), default
* value(""), password for PMA.core instance
*
* @return session's ID if session was created successfully, otherwise null
*/
public static String connect(String... varargs) {
// setting the default values when arguments' values are omitted
String pmaCoreURL = varargs.length > 0 ? varargs[0] : pmaCoreLiteURL;
String pmaCoreUsername = varargs.length > 1 ? varargs[1] : "";
String pmaCorePassword = varargs.length > 2 ? varargs[2] : "";
// Attempt to connect to PMA.core instance; success results in a SessionID
if (pmaCoreURL.equals(pmaCoreLiteURL)) {
if (isLite()) {
// no point authenticating localhost / PMA.core.lite
return pmaCoreLiteSessionID;
} else {
return null;
}
}
// purposefully DON'T use helper function apiUrl() here:
// why? Because apiUrl() takes session information into account (which we
// don't have yet)
String url = PMA.join(pmaCoreURL, "api/json/authenticate?caller=SDK.Java");
if (!pmaCoreUsername.equals("")) {
url = url.concat("&username=").concat(PMA.pmaQ(pmaCoreUsername));
}
if (!pmaCorePassword.equals("")) {
url = url.concat("&password=").concat(PMA.pmaQ(pmaCorePassword));
}
try {
URL urlResource = new URL(url);
HttpURLConnection con;
if (url.startsWith("https")) {
con = (HttpsURLConnection) urlResource.openConnection();
} else {
con = (HttpURLConnection) urlResource.openConnection();
}
con.setRequestMethod("GET");
String jsonString = PMA.getJSONAsStringBuffer(con).toString();
String sessionID = null;
if (PMA.isJSONObject(jsonString)) {
JSONObject jsonResponse = PMA.getJSONObjectResponse(jsonString);
if (!jsonResponse.get("Success").toString().toLowerCase().equals("true")) {
return null;
} else {
sessionID = jsonResponse.getString("SessionId");
pmaUsernames.put(sessionID, pmaCoreUsername);
pmaSessions.put(sessionID, pmaCoreURL);
if (!pmaSlideInfos.containsKey(sessionID)) {
pmaSlideInfos.put(sessionID, new HashMap());
}
pmaAmountOfDataDownloaded.put(sessionID, jsonResponse.length());
return sessionID;
}
} else {
return null;
}
} catch (Exception e) {
// Something went wrong; unable to communicate with specified endpoint
e.printStackTrace();
if (PMA.logger != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
PMA.logger.severe(sw.toString());
}
return null;
}
}
/**
* This method is used to disconnect from a running PMA.core instance
*
* @param varargs Array of optional arguments
*
* sessionID : First optional argument(String), default
* value(null), session's ID
*
* @return true if there was a PMA.core instance running to disconnect from,
* false otherwise
*/
public static Boolean disconnect(String... varargs) {
// setting the default value when argument's value is omitted
String sessionID = varargs.length > 0 ? varargs[0] : null;
// Disconnect from a PMA.core instance; return True if session exists; return
// False if session didn't exist (anymore)
sessionID = sessionId(sessionID);
String url = apiUrl(sessionID, false) + "DeAuthenticate?sessionID=" + PMA.pmaQ((sessionID));
String contents = PMA.httpGet(url, "application/json");
pmaAmountOfDataDownloaded.put(sessionID, pmaAmountOfDataDownloaded.get(sessionID) + contents.length());
if (pmaSessions.size() > 0) {
// yes we do! This means that when there's a PMA.core active session AND
// PMA.core.lite version running,
// the PMA.core active will be selected and returned
pmaSessions.remove(sessionID);
pmaSlideInfos.remove(sessionID);
return true;
} else {
return false;
}
}
/**
* This method is used to test if sessionID is valid and the server is online
* and reachable This method works only for PMA.core, don't use it for PMA.start
* for it will return always false
*
* @param varargs Array of optional arguments
*
* sessionID : First optional argument(String), default
* value(null), session's ID
*
* @return true if sessionID is valid and the server is online and reachable,
* false otherwise
*/
public static boolean ping(String... varargs) {
// setting the default value when argument's value is omitted
String sessionID = varargs.length > 0 ? varargs[0] : null;
sessionID = sessionId(sessionID);
String url = apiUrl(sessionID, false) + "Ping?sessionID=" + PMA.pmaQ(sessionID);
try {
URL urlResource = new URL(url);
HttpURLConnection con;
if (url.startsWith("https")) {
con = (HttpsURLConnection) urlResource.openConnection();
} else {
con = (HttpURLConnection) urlResource.openConnection();
}
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
String jsonString = PMA.getJSONAsStringBuffer(con).toString();
return jsonString.equals("true") ? true : false;
} catch (Exception e) {
e.printStackTrace();
if (PMA.logger != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
PMA.logger.severe(sw.toString());
}
return false;
}
}
/**
* This method is used to get root-directories available for a sessionID
*
* @param varargs Array of optional arguments
*
* sessionID : First optional argument(String), default
* value(null), session's ID
*
* @return Array of root-directories available to a session's ID
*/
public static List getRootDirectories(String... varargs) {
// setting the default value when argument's value is omitted
String sessionID = varargs.length > 0 ? varargs[0] : null;
// Return a list of root-directories available to sessionID
sessionID = sessionId(sessionID);
try {
String url = apiUrl(sessionID, false) + "GetRootDirectories?sessionID=" + PMA.pmaQ(sessionID);
String jsonString = PMA.httpGet(url, "application/json");
List rootDirs;
if (PMA.isJSONArray(jsonString)) {
JSONArray jsonResponse = getJSONArrayResponse(jsonString);
pmaAmountOfDataDownloaded.put(sessionID,
pmaAmountOfDataDownloaded.get(sessionID) + jsonResponse.length());
rootDirs = new ArrayList<>();
for (int i = 0; i < jsonResponse.length(); i++) {
rootDirs.add(jsonResponse.optString(i));
}
// return dirs;
} else {
JSONObject jsonResponse = PMA.getJSONObjectResponse(jsonString);
pmaAmountOfDataDownloaded.put(sessionID,
pmaAmountOfDataDownloaded.get(sessionID) + jsonResponse.length());
if (jsonResponse.has("Code")) {
if (PMA.logger != null) {
PMA.logger.severe("getrootdirectories() failed with error " + jsonResponse.get("Message"));
}
// throw new Exception("getrootdirectories() failed with error " +
// jsonResponse.get("Message"));
}
return null;
}
return rootDirs;
} catch (Exception e) {
e.printStackTrace();
if (PMA.logger != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
PMA.logger.severe(sw.toString());
}
return null;
}
}
/**
* This method is used to get sub-directories available to sessionID in the
* start directory following a recursive (or not) approach
*
* @param startDir Start directory
* @param varargs Array of optional arguments
*
* sessionID : First optional argument(String), default
* value(null), session's ID
*
*
* recursivity : Second optional argument(Boolean or Integer),
* default value(Boolean, false), if it's a Boolean if defines
* either no recursivity or a limitless recursivity, if it's an
* Integer it defines a limited in depth recursivity or no
* recursivity at all if this Integer equals 0
*
* @return Sub-directories available to a session's ID in a start directory
*/
public static List getDirectories(String startDir, Object... varargs) {
// setting the default values when arguments' values are omitted
String sessionID = null;
// we can either choose to have a non recursive call, a complete recursive call
// or a recursive call to a certain depth, in the last case we use an integer to
// define
// depth
// the following three variables intend to implement this
Boolean recursive = false;
Integer integerRecursive = 0;
String booleanOrInteger = "";
if (varargs.length > 0) {
if (!(varargs[0] instanceof String) && varargs[0] != null) {
if (PMA.logger != null) {
PMA.logger.severe("getDirectories() : Invalid argument");
}
throw new IllegalArgumentException("...");
}
sessionID = (String) varargs[0];
}
if (varargs.length > 1) {
if ((!(varargs[1] instanceof Integer) && !(varargs[1] instanceof Boolean)) && (varargs[1] != null)) {
if (PMA.logger != null) {
PMA.logger.severe("getDirectories() : Invalid argument");
}
throw new IllegalArgumentException("...");
}
if (varargs[1] instanceof Boolean) {
recursive = (Boolean) varargs[1];
booleanOrInteger = "boolean";
}
if (varargs[1] instanceof Integer) {
integerRecursive = (Integer) varargs[1];
recursive = ((Integer) varargs[1]) > 0 ? true : false;
booleanOrInteger = "integer";
}
}
// Return a list of sub-directories available to sessionID in the startDir
// directory
sessionID = sessionId(sessionID);
String url = apiUrl(sessionID, false) + "GetDirectories?sessionID=" + PMA.pmaQ(sessionID) + "&path="
+ PMA.pmaQ(startDir);
if (PMA.debug) {
System.out.println(url);
}
try {
URL urlResource = new URL(url);
HttpURLConnection con;
if (url.startsWith("https")) {
con = (HttpsURLConnection) urlResource.openConnection();
} else {
con = (HttpURLConnection) urlResource.openConnection();
}
con.setRequestMethod("GET");
String jsonString = PMA.getJSONAsStringBuffer(con).toString();
List dirs;
if (PMA.isJSONObject(jsonString)) {
JSONObject jsonResponse = PMA.getJSONObjectResponse(jsonString);
pmaAmountOfDataDownloaded.put(sessionID,
pmaAmountOfDataDownloaded.get(sessionID) + jsonResponse.length());
if (jsonResponse.has("Code")) {
if (PMA.logger != null) {
PMA.logger.severe("get_directories to " + startDir + " resulted in: "
+ jsonResponse.get("Message") + " (keep in mind that startDir is case sensitive!)");
}
throw new Exception("get_directories to " + startDir + " resulted in: "
+ jsonResponse.get("Message") + " (keep in mind that startDir is case sensitive!)");
} else if (jsonResponse.has("d")) {
JSONArray array = jsonResponse.getJSONArray("d");
dirs = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
dirs.add(array.optString(i));
}
// return dirs;
} else {
return null;
}
} else {
JSONArray jsonResponse = getJSONArrayResponse(jsonString);
pmaAmountOfDataDownloaded.put(sessionID,
pmaAmountOfDataDownloaded.get(sessionID) + jsonResponse.length());
dirs = new ArrayList<>();
for (int i = 0; i < jsonResponse.length(); i++) {
dirs.add(jsonResponse.optString(i));
}
// return dirs;
}
// we test if call is recursive, and if yes to which depth
if (recursive) {
for (String dir : getDirectories(startDir, sessionID)) {
if (booleanOrInteger.equals("boolean")) {
dirs.addAll(getDirectories(dir, sessionID, recursive));
}
if (booleanOrInteger.equals("integer")) {
dirs.addAll(getDirectories(dir, sessionID, integerRecursive - 1));
}
}
}
return dirs;
} catch (Exception e) {
e.printStackTrace();
if (PMA.logger != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
PMA.logger.severe(sw.toString());
}
return null;
}
}
/**
* This method is used to get the first non empty directory
*
* @param varargs Array of optional arguments
*
* sessionID : Second optional argument(String), default
* value(null), session's ID
*
* @return Path to the first non empty directory found
*/
public static String getFirstNonEmptyDirectory(String... varargs) {
// setting the default values when arguments' values are omitted
String startDir = varargs.length > 0 ? varargs[0] : null;
String sessionID = varargs.length > 1 ? varargs[1] : null;
if ((startDir == null) || (startDir.equals(""))) {
startDir = "/";
}
List slides = null;
try {
slides = getSlides(startDir, sessionID);
} catch (Exception e) {
if (PMA.debug) {
System.out.println("Unable to examine " + startDir);
if (PMA.logger != null) {
PMA.logger.severe("Unable to examine " + startDir);
}
}
if (!startDir.equals("/")) {
return null;
}
}
if ((slides != null) && (slides.size() > 0)) {
return startDir;
} else {
if (startDir.equals("/")) {
for (String dir : getRootDirectories(sessionID)) {
String nonEmptyDir = getFirstNonEmptyDirectory(dir, sessionID);
if (nonEmptyDir != null) {
return nonEmptyDir;
}
}
} else {
boolean success = true;
List dirs = null;
try {
dirs = getDirectories(startDir, sessionID);
} catch (Exception e) {
System.out.println("Unable to examine " + startDir);
if (PMA.logger != null) {
PMA.logger.severe(
"Debug flag enabled. You will receive extra feedback and messages from the Java SDK (like this one)");
}
success = false;
}
if (success) {
for (String dir : dirs) {
String nonEmptyDir = getFirstNonEmptyDirectory(dir, sessionID);
if (nonEmptyDir != null) {
return nonEmptyDir;
}
}
}
}
return null;
}
}
/**
* This method is used to get a list of slides available to sessionID in the
* start directory following a recursive (or not) approach
*
* @param startDir Start directory
* @param varargs Array of optional arguments
*
* sessionID : First optional argument(String), default
* value(null), session's ID
*
*
* recursivity : Second optional argument(Boolean or Integer),
* default value(Boolean, false), if it's a Boolean if defines
* either no recursivity or a limitless recursivity, if it's an
* Integer it defines a limited in depth recursivity or no
* recursivity at all if this Integer equals 0
*
* @return List of slides available to a session's ID in a start directory
*/
public static List getSlides(String startDir, Object... varargs) {
// setting the default values when arguments' values are omitted
String sessionID = null;
// we can either choose to have a non recursive call, a complete recursive call
// or a recursive call to a certain depth, in the last case we use an integer to
// define
// depth
// the following three variables intend to implement this
String booleanOrInteger = "";
Boolean recursive = false;
Integer integerRecursive = 0;
if (varargs.length > 0) {
if (!(varargs[0] instanceof String) && varargs[0] != null) {
if (PMA.logger != null) {
PMA.logger.severe("getSlides() : Invalid argument");
}
throw new IllegalArgumentException("...");
}
sessionID = (String) varargs[0];
}
if (varargs.length > 1) {
if ((!(varargs[1] instanceof Integer) && !(varargs[1] instanceof Boolean)) && (varargs[1] != null)) {
if (PMA.logger != null) {
PMA.logger.severe("getSlides() : Invalid argument");
}
throw new IllegalArgumentException("...");
}
if (varargs[1] instanceof Boolean) {
recursive = (Boolean) varargs[1];
booleanOrInteger = "boolean";
}
if (varargs[1] instanceof Integer) {
integerRecursive = (Integer) varargs[1];
recursive = ((Integer) varargs[1]) > 0 ? true : false;
booleanOrInteger = "integer";
}
}
// Return a list of slides available to sessionID in the startDir directory
sessionID = sessionId(sessionID);
if (startDir.startsWith("/")) {
startDir = startDir.substring(1);
}
String url = apiUrl(sessionID, false) + "GetFiles?sessionID=" + PMA.pmaQ(sessionID) + "&path="
+ PMA.pmaQ(startDir);
try {
URL urlResource = new URL(url);
HttpURLConnection con;
if (url.startsWith("https")) {
con = (HttpsURLConnection) urlResource.openConnection();
} else {
con = (HttpURLConnection) urlResource.openConnection();
}
con.setRequestMethod("GET");
String jsonString = PMA.getJSONAsStringBuffer(con).toString();
List slides;
if (PMA.isJSONObject(jsonString)) {
JSONObject jsonResponse = PMA.getJSONObjectResponse(jsonString);
pmaAmountOfDataDownloaded.put(sessionID,
pmaAmountOfDataDownloaded.get(sessionID) + jsonResponse.length());
if (jsonResponse.has("Code")) {
if (PMA.logger != null) {
PMA.logger.severe("get_slides from " + startDir + " resulted in: " + jsonResponse.get("Message")
+ " (keep in mind that startDir is case sensitive!)");
}
throw new Exception("get_slides from " + startDir + " resulted in: " + jsonResponse.get("Message")
+ " (keep in mind that startDir is case sensitive!)");
} else if (jsonResponse.has("d")) {
JSONArray array = jsonResponse.getJSONArray("d");
slides = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
slides.add(array.optString(i));
}
// return slides;
} else {
return null;
}
} else {
JSONArray jsonResponse = getJSONArrayResponse(jsonString);
pmaAmountOfDataDownloaded.put(sessionID,
pmaAmountOfDataDownloaded.get(sessionID) + jsonResponse.length());
slides = new ArrayList<>();
for (int i = 0; i < jsonResponse.length(); i++) {
slides.add(jsonResponse.optString(i));
}
// return slides;
}
// we test if call is recursive, and if yes to which depth
if (recursive) {
for (String dir : getDirectories(startDir, sessionID)) {
if (booleanOrInteger.equals("boolean")) {
slides.addAll(getSlides(dir, sessionID, recursive));
}
if (booleanOrInteger.equals("integer")) {
slides.addAll(getSlides(dir, sessionID, integerRecursive - 1));
}
}
}
return slides;
} catch (Exception e) {
e.printStackTrace();
if (PMA.logger != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
PMA.logger.severe(sw.toString());
}
return null;
}
}
/**
* This method is used to determine the file extension for a slide's path
*
* @param slideRef slide's path
* @return File extension extracted from a slide's path
*/
public static String getSlideFileExtension(String slideRef) {
// Determine the file extension for this slide
return FilenameUtils.getExtension(slideRef);
}
/**
* This method is used to determine file name (with extension) for a slide's
* path
*
* @param slideRef slide's path
* @return File name extracted from a slide's path
*/
public static String getSlideFileName(String slideRef) {
// Determine the file name (with extension) for this slide
return FilenameUtils.getName(slideRef);
}
/**
* This method is used to get the UID for a defined slide
*
* @param slideRef slide's path
* @param varargs Array of optional arguments
*
* sessionID : First optional argument(String), default
* value(null), session's ID
*
* @return UID for a defined slide's path
* @throws Exception if PMA.core not found
*/
public static String getUid(String slideRef, String... varargs) throws Exception {
// setting the default value when arguments' value is omitted
String sessionID = varargs.length > 0 ? varargs[0] : null;
// Get the UID for a specific slide
sessionID = sessionId(sessionID);
if (sessionID.equals(pmaCoreLiteSessionID)) {
if (isLite()) {
if (PMA.logger != null) {
PMA.logger.severe(
"PMA.core.lite found running, but doesn't support UID generation. For advanced anonymization, please upgrade to PMA.core.");
}
throw new Exception(
"PMA.core.lite found running, but doesn't support UID generation. For advanced anonymization, please upgrade to PMA.core.");
} else {
if (PMA.logger != null) {
PMA.logger.severe(
"PMA.core.lite not found, and besides; it doesn't support UID generation. For advanced anonymization, please upgrade to PMA.core.");
}
throw new Exception(
"PMA.core.lite not found, and besides; it doesn't support UID generation. For advanced anonymization, please upgrade to PMA.core.");
}
}
String url = apiUrl(sessionID, false) + "GetUID?sessionID=" + PMA.pmaQ(sessionID) + "&path="
+ PMA.pmaQ(slideRef);
try {
String jsonString = PMA.httpGet(url, "application/json");
pmaAmountOfDataDownloaded.put(sessionID, pmaAmountOfDataDownloaded.get(sessionID) + jsonString.length());
if (PMA.isJSONObject(jsonString)) {
JSONObject jsonResponse = PMA.getJSONObjectResponse(jsonString);
if (jsonResponse.has("Code")) {
if (PMA.logger != null) {
PMA.logger.severe("getUid() on " + slideRef + " resulted in: " + jsonResponse.get("Message"));
}
// throw new Exception("getUid() on " + slideRef + " resulted in: " +
// jsonResponse.get("Message"));
}
return null;
} else {
return jsonString;
}
} catch (Exception e) {
// this happens when NO instance of PMA.core is detected
e.printStackTrace();
if (PMA.logger != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
PMA.logger.severe(sw.toString());
}
return null;
}
}
/**
* This method is used to get the fingerprint for a specific slide
*
* @param slideRef slide's path
* @param varargs Array of optional arguments
*
* sessionID : First optional argument(String), default
* value(null), session's ID
*
* @return Fingerprint of the slide
*/
public static String getFingerPrint(String slideRef, String... varargs) {
// setting the default value when arguments' value is omitted
String sessionID = varargs.length > 0 ? varargs[0] : null;
// Get the fingerprint for a specific slide
sessionID = sessionId(sessionID);
String fingerprint;
String url = apiUrl(sessionID, false) + "GetFingerprint?sessionID=" + PMA.pmaQ(sessionID) + "&pathOrUid="
+ PMA.pmaQ(slideRef);
try {
URL urlResource = new URL(url);
HttpURLConnection con;
if (url.startsWith("https")) {
con = (HttpsURLConnection) urlResource.openConnection();
} else {
con = (HttpURLConnection) urlResource.openConnection();
}
con.setRequestMethod("GET");
String jsonString = PMA.getJSONAsStringBuffer(con).toString();
if (PMA.isJSONObject(jsonString)) {
JSONObject jsonResponse = PMA.getJSONObjectResponse(jsonString);
pmaAmountOfDataDownloaded.put(sessionID,
pmaAmountOfDataDownloaded.get(sessionID) + jsonResponse.length());
if (jsonResponse.has("Code")) {
if (PMA.logger != null) {
PMA.logger.severe("get_fingerprint on " + slideRef + " resulted in: "
+ jsonResponse.get("Message") + " (keep in mind that slideRef is case sensitive!)");
}
throw new Exception("get_fingerprint on " + slideRef + " resulted in: "
+ jsonResponse.get("Message") + " (keep in mind that slideRef is case sensitive!)");
} else {
return jsonResponse.getString("d");
}
} else {
pmaAmountOfDataDownloaded.put(sessionID,
pmaAmountOfDataDownloaded.get(sessionID) + jsonString.length());
fingerprint = jsonString.replace("\"", "");
}
} catch (Exception e) {
e.printStackTrace();
if (PMA.logger != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
PMA.logger.severe(sw.toString());
}
return null;
}
return fingerprint;
}
/**
* This method is used to get information about a session
*
* @param varargs Array of optional arguments
*
* sessionID : First optional argument(String), default
* value(null), session's ID
*
* @return Information about a session
*/
public static Map whoAmI(String... varargs) {
// setting the default value when arguments' value is omitted
String sessionID = varargs.length > 0 ? varargs[0] : null;
// Getting information about your Session
sessionID = sessionId(sessionID);
Map retval = null;
if (sessionID.equals(pmaCoreLiteSessionID)) {
retval = new HashMap<>();
retval.put("sessionID", pmaCoreLiteSessionID);
retval.put("username", null);
retval.put("url", pmaCoreLiteURL);
retval.put("amountOfDataDownloaded", pmaAmountOfDataDownloaded.get(pmaCoreLiteSessionID).toString());
} else if (sessionID != null) {
retval = new HashMap<>();
retval.put("sessionID", sessionID);
retval.put("username", pmaUsernames.get(sessionID));
retval.put("amountOfDataDownloaded", pmaAmountOfDataDownloaded.get(sessionID).toString());
try {
retval.put("url", pmaUrl(sessionID));
} catch (Exception e) {
if (PMA.logger != null) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
PMA.logger.severe(sw.toString());
}
}
}
return retval;
}
/**
* This method is used to get tile size information for sessionID
*
* @param varargs Array of optional arguments
*
* sessionID : First optional argument(String), default
* value(null), session's ID
*
* @return A list of two items (duplicated) relative to the tile size
* information for a session's ID
*/
public static List getTileSize(String... varargs) {
// setting the default value when arguments' value is omitted
String sessionID = varargs.length > 0 ? varargs[0] : null;
sessionID = sessionId(sessionID);
Map info;
if (((Map) pmaSlideInfos.get(sessionID)).size() < 1) {
String dir = getFirstNonEmptyDirectory(null, sessionID);
List slides = getSlides(dir, sessionID);
info = getSlideInfo(slides.get(0), sessionID);
} else {
int getLength = ((Map) pmaSlideInfos.get(sessionID)).values().toArray().length;
info = (Map) ((Map) pmaSlideInfos.get(sessionID)).values()
.toArray()[new Random().nextInt(getLength)];
}
List result = new ArrayList<>();
result.add(Integer.parseInt(info.get("TileSize").toString()));
return result;
}
/**
* This method is used to get a raw image in the form of nested maps
*
* @param slideRef slide's path or UID
* @param varargs Array of optional arguments
*
* sessionID : First optional argument(String), default
* value(null), session's ID
*
* @return Nested maps forming a raw image
*/
public static Map getSlideInfo(String slideRef, String... varargs) {
// setting the default value when arguments' value is omitted
String sessionID = varargs.length > 0 ? varargs[0] : null;
// Return raw image information in the form of nested maps
sessionID = sessionId(sessionID);
if (slideRef.startsWith("/")) {
slideRef = slideRef.substring(1);
}
if (!((Map) pmaSlideInfos.get(sessionID)).containsKey(slideRef)) {
try {
String url = apiUrl(sessionID, false) + "GetImageInfo?SessionID=" + PMA.pmaQ(sessionID) + "&pathOrUid="
+ PMA.pmaQ(slideRef);
if (PMA.debug) {
System.out.println(url);
}
URL urlResource = new URL(url);
HttpURLConnection con;
if (url.startsWith("https")) {
con = (HttpsURLConnection) urlResource.openConnection();
} else {
con = (HttpURLConnection) urlResource.openConnection();
}
con.setRequestMethod("GET");
String jsonString = PMA.getJSONAsStringBuffer(con).toString();
if (PMA.isJSONObject(jsonString)) {
JSONObject jsonResponse = PMA.getJSONObjectResponse(jsonString);
pmaAmountOfDataDownloaded.put(sessionID,
pmaAmountOfDataDownloaded.get(sessionID) + jsonResponse.length());
if (jsonResponse.has("Code")) {
if (PMA.logger != null) {
PMA.logger.severe("ImageInfo to " + slideRef + " resulted in: "
+ jsonResponse.get("Message") + " (keep in mind that slideRef is case sensitive!)");
}
throw new Exception("ImageInfo to " + slideRef + " resulted in: " + jsonResponse.get("Message")
+ " (keep in mind that slideRef is case sensitive!)");
} else if (jsonResponse.has("d")) {
// we convert the Json object to a Map
Map jsonMap = objectMapper.readerFor(new TypeReference