Commit d8f782d7 by Currell Berry

working calendar recurrence functionality. working "effective calendar" feature…

….  working "week at a glance" screen.
1 parent 8ead3e27
......@@ -41,7 +41,7 @@ Build a standalone jar as follows:
For now, the simplest way to run berryPIM looks like the following:
java -DBERRYPIM_PWFILE=berrypim_passwords.txt -DBERRYPIM_DATA_ROOT=[path/to/data/folder] -jar berrypim-1.0-SNAPSHOT.jar
java -DBERRYPIM_PWFILE=berrypim_passwords.txt -DBERRYPIM_DATA_ROOT=[path/to/data/folder] -jar berry-pim-1.0-SNAPSHOT.jar
More info on how to get started with berryPIM is on its way soon. Right now, it's going to be a pain for anyone
besides me to get started with.
......
......@@ -5,6 +5,7 @@ import org.xml.sax.SAXException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPath;
......@@ -114,7 +115,8 @@ public class AuthenticationFilter implements Filter {
if (basic.equalsIgnoreCase("Basic")) {
try {
String credentials = new String(Base64.getDecoder().decode(st.nextToken()), "UTF-8");
//String credentials = new String(Base64.getDecoder().decode(st.nextToken()), "UTF-8");//java 8
String credentials = new String(DatatypeConverter.parseBase64Binary(st.nextToken()),"UTF-8");//java 7
int p = credentials.indexOf(":");
if (p != -1) {
String login = credentials.substring(0, p).trim();
......
......@@ -180,7 +180,7 @@ public class DataFilesManager {
List<String> fileList = new ArrayList<>(fileContentsMap.keySet());
List<String> outFileList = new ArrayList<>();
for (String s : fileList) {
if (!s.endsWith(".bPIMD")) {
if (!s.endsWith(".bPIMD") && !s.equals(".gitignore")) {
outFileList.add(s);
}
}
......
......@@ -61,7 +61,7 @@ public class DefaultController implements ControllerObject {
for (Map.Entry<String, String> entry : items) {
String key = entry.getKey();
String pathPart = key.split("\\?")[0];
if (pathPart.toLowerCase().equals(selectorPath.toLowerCase())) {
if (pathPart.toLowerCase().startsWith(selectorPath.toLowerCase())) {
out.append("<li class='active'><a href='" + rootPathStr + entry.getKey() + "'>" + entry.getValue() + "</a></li>\n");
} else {
out.append("<li><a href='" + rootPathStr + entry.getKey() + "'>" + entry.getValue() + "</a></li>\n");
......
package com.cvberry.berrypimimpl;
import com.cvberry.berrypim.ControllerObject;
import com.cvberry.util.AuthInfoHolder;
import com.cvberry.util.Utility;
import java.util.List;
......@@ -10,18 +11,38 @@ import java.util.Map;
* Created by vancan1ty on 1/4/2016.
*/
public class CalendarController extends RawController implements ControllerObject {
String controllerBaseGroup;
public CalendarController(String controllerBase) {
public CalendarController(String controllerBase, String controllerBaseGroup) {
super(controllerBase);
this.controllerBaseGroup = controllerBaseGroup;
UNIVERSALFILENAME = "calendar.xml";
}
@Override
public List<Map.Entry<String, String>> getTopTabsItems() {
String[] starter = {
"home", "Calendar Home",
"home", "Raw Calendar",
"effective", "Effective Calendar",
};
return Utility.tupleizeArray(starter);
}
public String fill_topTabsItems(String[] pathComponents, Map<String, String[]> queryParams, String dataBody,
AuthInfoHolder authInfo) {
List<Map.Entry<String, String>> items = getTopTabsItems();
String selectorPath = (pathComponents.length < 2 || pathComponents[1] == null || pathComponents[1].isEmpty()) ?
items.get(0).getKey() : pathComponents[1];
StringBuilder out = new StringBuilder();
for (Map.Entry<String, String> entry : items) {
String key = entry.getKey();
if (key.toLowerCase().equals(selectorPath.toLowerCase())) {
out.append("<li class='active'><a href='" + rootPathStr + controllerBaseGroup + entry.getKey() + "'>" + entry.getValue() + "</a></li>\n");
} else {
out.append("<li><a href='" + rootPathStr + controllerBaseGroup + entry.getKey() + "'>" + entry.getValue() + "</a></li>\n");
}
}
return out.toString();
}
}
package com.cvberry.berrypimimpl;
import com.cvberry.berrypim.ChartingUtil;
import com.cvberry.berrypim.ControllerObject;
import com.cvberry.berrypim.Anchor;
import com.cvberry.berrypim.DataFilesManager;
import com.cvberry.berrypim.calendar.EffectiveCalendarGenerator;
import com.cvberry.util.AuthInfoHolder;
import com.cvberry.util.Utility;
import com.sun.management.OperatingSystemMXBean;
import net.sf.saxon.s9api.XdmSequenceIterator;
import org.w3c.dom.Document;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* Created by vancan1ty on 1/4/2016.
* Created by vancan1ty on 1/29/2016.
*/
public class DashboardController extends PIMDefaultController implements ControllerObject {
public class DashboardController extends PIMDefaultController {
public String virtualFileName = "quickNotes.xml";
private RawController rawController;
private CalendarController calendarController;
private EffectiveCalendarGenerator effectiveCalendarGenerator;
private DataFilesManager filesManager;
public DashboardController(String controllerBase) {
this.controllerBase = controllerBase;
rawController = new RawController(controllerBase);
String controllerBaseGroup = controllerBase.split("/")[0]+"/";
calendarController = new CalendarController(controllerBase,controllerBaseGroup);
filesManager = Anchor.getInstance().getDataFilesManager();
effectiveCalendarGenerator = new EffectiveCalendarGenerator(filesManager);
}
@Override
......@@ -30,47 +42,69 @@ public class DashboardController extends PIMDefaultController implements Control
@Override
public String fill_contentPane(String[] pathComponents, Map<String, String[]> queryParams, String dataBody,
AuthInfoHolder authInfo) {
AuthInfoHolder authInfo) throws Exception {
Document effectiveCalendar = effectiveCalendarGenerator.getEffectiveCalendar();
StringBuilder out = new StringBuilder();
out.append("<p>Welcome to berryPIM. This program is still a work in progress!</p>");
out.append("<h2>System Statistics</h2>");
OperatingSystemMXBean opBean= (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
long totalMemorySize = opBean.getTotalPhysicalMemorySize();
long freeMemory = opBean.getFreePhysicalMemorySize();
long usedMemory = totalMemorySize - freeMemory;
out.append("<h2>Week at a Glance</h2>");
out.append("<div class='twothirdswidth'>");
out.append("<h3>Calendar events this week</h3>");
out.append("<pre>");
String calQuery = "for $t in //vevent " +
"let $mdate := $t//dtstart/date-time " +
"order by $mdate " +
"where $mdate gt string(current-dateTime()) " +
"and $mdate lt string(current-dateTime() + xs:dayTimeDuration('P7D')) " +
"return $t";
// "let $d1 := xs:date('2014-03-02') " +
// "let $d2 := xs:date('2014-04-21') " +
// "let $days:=0 to days-from-duration($d2 - $d1) " +
// "return $days!($d1+ . *xs:dayTimeDuration('P1D'))"
String eCalResults = Utility.runXQueryOnDocument(effectiveCalendar,calQuery);
out.append(Utility.escapeXML(eCalResults));
// XdmSequenceIterator iterator = Utility.runXQueryOnDOMDocument(effectiveCalendar, calQuery);
// while (iterator.hasNext()) {
// out.append(iterator.next().getStringValue());
// }
String todoStr = filesManager.getFileContents("todo.xml");
out.append("</pre>");
out.append("</div>");
out.append("<div class='onethirdwidth'>");
out.append("<h3>Next 10 Todos</h3>");
out.append("<pre>");
String todoQuery = "(for $t in //todo " +
"order by $t/@due ascending " +
"return ($t/@due/string() , ' ', $t/name ,' &#10;')" +
")[position() = 1 to 40]";
//String eCalResults = Utility.runXQueryOnDocument(effectiveCalendar,calQuery);
//out.append(eCalResults);
XdmSequenceIterator iterator2 = Utility.runXQueryOnStringToDS(todoStr, todoQuery);
while (iterator2.hasNext()) {
out.append(Utility.escapeXML(iterator2.next().getStringValue()));
}
out.append("</pre>");
out.append("</div>");
out.append("<div style='clear: both'></div>");
out.append("<span id='fileName' style='display: none'>" + virtualFileName +"</span>");
return out.toString();
}
Double BYTESINGIG = 1000000000.0;
File file = new File("/");
long totalDiskSize = (file.getTotalSpace());
long freeDiskSpace = file.getFreeSpace();
long usedDiskSpace = totalDiskSize-freeDiskSpace;
out.append("<table class='fullspan center'><tr>\n");
out.append("<th><h3>Memory</h3></th>\n");
out.append("<th><h3>Disk</h3></th>\n");
out.append("</tr><tr>\n");
out.append("<td>");
out.append(ChartingUtil.createAndEnqueuePieChart(
ChartingUtil.createPieDatasetFromArrays(new String[]{"Free","Used"},
new Double[]{freeMemory/BYTESINGIG,usedMemory/BYTESINGIG}),
null,rootPathStr,true,true,300,300));
out.append("<br><table>\n");
out.append("<tr><th>Total</th><th>Free</th><th>Used</th></tr>\n");
out.append(String.format("<tr><td>%.1f</td><td>%.1f</td><td>%.1f</td></tr>\n",
totalMemorySize/BYTESINGIG,freeMemory/BYTESINGIG,usedMemory/BYTESINGIG));
out.append("</table>\n");
out.append("</td><td>");
out.append(ChartingUtil.createAndEnqueuePieChart(
ChartingUtil.createPieDatasetFromArrays(new String[]{"Free","Used"},
new Double[]{freeDiskSpace/BYTESINGIG,usedDiskSpace/BYTESINGIG}),
null,rootPathStr,true,true,300,300));
out.append("<br><table>\n");
out.append("<tr><th>Total</th><th>Free</th><th>Used</th></tr>\n");
out.append(String.format("<tr><td>%.1f</td><td>%.1f</td><td>%.1f</td></tr>\n",
totalDiskSize/BYTESINGIG,freeDiskSpace/BYTESINGIG,usedDiskSpace/BYTESINGIG));
out.append("</td>");
out.append("</table>\n");
@Override
public String fill_rightSideList(String[] pathComponents, Map<String, String[]> queryParams, String dataBody,
AuthInfoHolder authInfo) throws Exception {
String fileContents = filesManager.getFileContents(virtualFileName+".bPIMD");
return rawController.buildRightSideGivenContents(fileContents);
}
public String api_save(String[] pathComponents, Map<String, String[]> queryParams, String dataBody,
AuthInfoHolder authInfo) throws IOException, InterruptedException {
String fileNameToSave = Utility.getFirstQParamResult(queryParams, "file");
if(fileNameToSave.endsWith(".bPIMD")) {
String doGITCommitStr = Utility.getFirstQParamResult(queryParams, "doGITCommit");
return rawController.saveFile(fileNameToSave, doGITCommitStr, dataBody);
} else {
return "bypassed save";
}
return out.toString();
}
}
package com.cvberry.berrypimimpl;
import com.cvberry.berrypim.Anchor;
import com.cvberry.berrypim.ControllerObject;
import com.cvberry.berrypim.DataFilesManager;
import com.cvberry.berrypim.DefaultController;
import com.cvberry.berrypim.calendar.EffectiveCalendarGenerator;
import com.cvberry.util.AuthInfoHolder;
import com.cvberry.util.Utility;
import org.w3c.dom.Document;
import javax.xml.datatype.DatatypeConfigurationException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* Created by vancan1ty on 1/29/2016.
*/
public class EffectiveCalendarController extends PIMDefaultController {
public String virtualFileName = "effectiveCalendar.xml";
private RawController rawController;
private CalendarController calendarController;
private EffectiveCalendarGenerator effectiveCalendarGenerator;
private DataFilesManager filesManager;
public EffectiveCalendarController(String controllerBase) {
this.controllerBase = controllerBase;
rawController = new RawController(controllerBase);
String controllerBaseGroup = controllerBase.split("/")[0]+"/";
calendarController = new CalendarController(controllerBase,controllerBaseGroup);
filesManager = Anchor.getInstance().getDataFilesManager();
effectiveCalendarGenerator = new EffectiveCalendarGenerator(filesManager);
}
@Override
public List<Map.Entry<String, String>> getTopTabsItems() {
return calendarController.getTopTabsItems();
}
@Override
public String fill_contentPane(String[] pathComponents, Map<String, String[]> queryParams, String dataBody,
AuthInfoHolder authInfo) throws Exception {
StringBuilder out = new StringBuilder();
String effectiveCalendarStr = effectiveCalendarGenerator.getEffectiveCalendarAsString();
String actionStr = Utility.getFirstQParamResult(queryParams, "action");
String dataStr = Utility.getFirstQParamResult(queryParams, "data");
rawController.displayEditorForFile(out, effectiveCalendarStr, virtualFileName, actionStr, dataStr, true);
return out.toString();
}
@Override
public String fill_topTabsItems(String[] pathComponents, Map<String, String[]> queryParams, String dataBody,
AuthInfoHolder authInfo) {
return calendarController.fill_topTabsItems(pathComponents,queryParams,dataBody,authInfo);
}
@Override
public String fill_rightSideList(String[] pathComponents, Map<String, String[]> queryParams, String dataBody,
AuthInfoHolder authInfo) throws Exception {
String fileContents = filesManager.getFileContents(virtualFileName+".bPIMD");
return rawController.buildRightSideGivenContents(fileContents);
}
public String api_save(String[] pathComponents, Map<String, String[]> queryParams, String dataBody,
AuthInfoHolder authInfo) throws IOException, InterruptedException {
String fileNameToSave = Utility.getFirstQParamResult(queryParams, "file");
if(fileNameToSave.endsWith(".bPIMD")) {
String doGITCommitStr = Utility.getFirstQParamResult(queryParams, "doGITCommit");
return rawController.saveFile(fileNameToSave, doGITCommitStr, dataBody);
} else {
return "bypassed save";
}
}
}
......@@ -71,7 +71,8 @@ public class GraphsController extends RawController implements ControllerObject
filesManager.readInAllFiles();
}
String dataStr = Utility.getFirstQParamResult(queryParams,"data");
displayEditorForFile(out, fileName, actionStr, dataStr);
String fileContents = filesManager.getFileContents(fileName);
displayEditorForFile(out, fileContents, fileName, actionStr, dataStr, false);
return out.toString();
}
......
......@@ -13,16 +13,18 @@ public class PIMConfigurator implements Configurator {
@Override
public void doConfiguration(String rootPath) throws IOException, URISyntaxException {
Anchor myAnchor = Anchor.getInstance();
myAnchor.getDispatcher().addDispatchPath("",new DashboardController("dashboard/"));
myAnchor.getDispatcher().addDispatchPath("dashboard",new DashboardController("dashboard/"));
myAnchor.getDispatcher().addDispatchPath("raw",new RawController("raw/"));
myAnchor.getDispatcher().addDispatchPath("",new DashboardController("dashboard/"));
myAnchor.getDispatcher().addDispatchPath("calendar",new CalendarController("calendar/"));
myAnchor.getDispatcher().addDispatchPath("calendar/home",new CalendarController("calendar/home/","calendar/"));
myAnchor.getDispatcher().addDispatchPath("calendar/effective",new EffectiveCalendarController("calendar/effective"));
myAnchor.getDispatcher().addDispatchPath("contacts",new ContactsController3("contacts/"));
myAnchor.getDispatcher().addDispatchPath("notes",new NotesController("notes/"));
myAnchor.getDispatcher().addDispatchPath("todos",new TodoController("todos/"));
myAnchor.getDispatcher().addDispatchPath("finance",new FinanceController("finance/"));
myAnchor.getDispatcher().addDispatchPath("email",new EmailController("email/"));
myAnchor.getDispatcher().addDispatchPath("graphs",new GraphsController("graphs/"));
myAnchor.getDispatcher().addDispatchPath("systemInfo",new SystemInfoController("systemInfo/"));
//myAnchor.getDispatcher().addDispatchPath("contacts",new ContactsController("contacts/"));
//myAnchor.getDispatcher().addDispatchPath("contacts2",new ContactsController2("contacts2/"));
}
......
......@@ -17,13 +17,14 @@ public class PIMDefaultController extends DefaultController implements Controlle
String[] starter = {
"raw", "Raw",
"dashboard", "Dashboard",
"calendar", "Calendar",
"calendar/home", "Calendar",
"contacts", "Contacts",
"notes", "Notes",
"todos", "Todos",
"finance", "Finance",
"email", "Email",
"graphs?gtype=pie&file=finance.xml", "Graphs"
"graphs?gtype=pie&file=finance.xml", "Graphs",
"systemInfo", "System Info",
};
return Utility.tupleizeArray(starter);
}
......
......@@ -44,7 +44,7 @@ public class RawController extends PIMDefaultController implements ControllerObj
return Utility.tupleizeArray(starter);
}
public String getFileName(String[] pathComponents, Map<String,String[]> queryParams) {
public String getFileName(String[] pathComponents, Map<String, String[]> queryParams) {
return Utility.getPathComponentOrDefault(pathComponents, 1, getTopTabsItems().get(0).getKey());
}
......@@ -58,56 +58,78 @@ public class RawController extends PIMDefaultController implements ControllerObj
StringBuilder out = new StringBuilder();
String fileName;
if (UNIVERSALFILENAME != null) {
fileName = UNIVERSALFILENAME;
fileName = UNIVERSALFILENAME;
} else {
fileName = getFileName(pathComponents,queryParams);
fileName = getFileName(pathComponents, queryParams);
}
String actionStr=Utility.getFirstQParamResult(queryParams,"action");
if (actionStr!=null && actionStr.equals("reload")) {
String actionStr = Utility.getFirstQParamResult(queryParams, "action");
if (actionStr != null && actionStr.equals("reload")) {
filesManager.readInAllFiles();
}
if (actionStr!=null && actionStr.equals("sync")) {
if (actionStr != null && actionStr.equals("sync")) {
GitManager gitManager = filesManager.gitManager;
gitManager.syncToGit(authInfo.truePassword);
filesManager.readInAllFiles();
}
String dataStr = Utility.getFirstQParamResult(queryParams,"data");
displayEditorForFile(out, fileName, actionStr, dataStr);
String dataStr = Utility.getFirstQParamResult(queryParams, "data");
String fileContents = filesManager.getFileContents(fileName);
displayEditorForFile(out, fileContents, fileName, actionStr, dataStr, false);
return out.toString();
}
public String api_save(String[] pathComponents, Map<String, String[]> queryParams, String dataBody,
AuthInfoHolder authInfo) throws IOException, InterruptedException {
String fileNameToSave = Utility.getFirstQParamResult(queryParams,"file");
String doGITCommitStr = Utility.getFirstQParamResult(queryParams,"doGITCommit");
if (fileNameToSave == null) {
throw new RuntimeException("file save failed! -- name of file not specified.");
}
if (fileNameToSave.endsWith(".bPIMD")) {//this is one of our special helper files
//only save if file already exists or if the string is non-empty
String oldContents=filesManager.getFileContents(fileNameToSave);
if(dataBody != null && (oldContents!=null || !dataBody.isEmpty())) {//then we should save
} else {
return "no save necessary for this non-existent helper file.";
}
}
StringBuilder resultsStrb = new StringBuilder();
boolean doGitCommit = (doGITCommitStr != null && doGITCommitStr.equals("true")) ? true : false;
boolean success = filesManager.saveNewContentsToFile(fileNameToSave,dataBody,resultsStrb,false,doGitCommit);
boolean success2= filesManager.readInAllFilesSafe(resultsStrb);
if(success && success2) {
return resultsStrb.toString();
String fileNameToSave = Utility.getFirstQParamResult(queryParams, "file");
String doGITCommitStr = Utility.getFirstQParamResult(queryParams, "doGITCommit");
return saveFile(fileNameToSave, doGITCommitStr, dataBody);
}
public String saveFile(String fileNameToSave, String doGITCommitStr, String dataBody) throws IOException, InterruptedException {
if (fileNameToSave == null) {
throw new RuntimeException("file save failed! -- name of file not specified.");
}
if (fileNameToSave.endsWith(".bPIMD")) {//this is one of our special helper files
//only save if file already exists or if the string is non-empty
String oldContents = filesManager.getFileContents(fileNameToSave);
if (dataBody != null && (oldContents != null || !dataBody.isEmpty())) {//then we should save
} else {
throw new RuntimeException("file save failed! " + resultsStrb.toString());
return "no save necessary for this non-existent helper file.";
}
}
StringBuilder resultsStrb = new StringBuilder();
boolean doGitCommit = (doGITCommitStr != null && doGITCommitStr.equals("true")) ? true : false;
boolean success = filesManager.saveNewContentsToFile(fileNameToSave, dataBody, resultsStrb, false, doGitCommit);
boolean success2 = filesManager.readInAllFilesSafe(resultsStrb);
if (success && success2) {
return resultsStrb.toString();
} else {
throw new RuntimeException("file save failed! " + resultsStrb.toString());
}
}
public void displayEditorForFile(StringBuilder out, String fileName, String action, String dataStr) throws SAXException, TransformerException,
/**
* @param out
* @param fileContents
* @param fileName is kind of a fake "fileName" -- doesn't have to correspond to real file
* @param action
* @param dataStr
* @param readOnly
* @throws SAXException
* @throws TransformerException
* @throws ParserConfigurationException
* @throws XPathExpressionException
* @throws IOException
* @throws XPathFactoryConfigurationException
* @throws SaxonApiException
*/
public void displayEditorForFile(StringBuilder out, String fileContents, String fileName,
String action, String dataStr, boolean readOnly)
throws SAXException, TransformerException,
ParserConfigurationException, XPathExpressionException, IOException, XPathFactoryConfigurationException, SaxonApiException {
String fileContents = filesManager.getFileContents(fileName);
out.append("<span id='fileName' style='display:none'>"+fileName+"</span>");
out.append("<textarea class='fullsize' id='mainEditor'>");
out.append("<span id='fileName' style='display:none'>" + fileName + "</span>");
String readOnlyStr = readOnly ? "readonly='readonly'" : "";
out.append("<textarea class='fullsize' id='mainEditor'" + readOnlyStr + ">");
out.append(fileContents);
out.append("</textarea><br>");
......@@ -135,27 +157,31 @@ public class RawController extends PIMDefaultController implements ControllerObj
AuthInfoHolder authInfo) throws Exception {
String fileName;
if (UNIVERSALFILENAME != null) {
fileName = UNIVERSALFILENAME;
fileName = UNIVERSALFILENAME;
} else {
fileName = getFileName(pathComponents,queryParams);
fileName = getFileName(pathComponents, queryParams);
}
String fileContents = filesManager.getFileContents(fileName+".bPIMD");
String fileContents = filesManager.getFileContents(fileName + ".bPIMD");
return buildRightSideGivenContents(fileContents);
}
public String buildRightSideGivenContents(String fileContents) {
StringBuilder out = new StringBuilder();
out.append("<div id='rsCSSHelper'>");
out.append("<label>Notes / XPath Queries</label>");
boolean helperInitialized = false;
out.append("<ul id='savedQueries' contentEditable='true'>");
if(fileContents!=null) {
if (fileContents != null) {
helperInitialized = true;
String[] lines = fileContents.trim().split("\n");
for (String s : lines) {
out.append("<li>"+Utility.escapeXML(s)+"</li>");
out.append("<li>" + Utility.escapeXML(s) + "</li>");
}
} else {
out.append("<li> </li>");
}
out.append("</ul>");
out.append("<span style='display:none' id='helperInitialized'>"+helperInitialized+"</span>");
out.append("<span style='display:none' id='helperInitialized'>" + helperInitialized + "</span>");
out.append("</div>");
return out.toString();
}
......
package com.cvberry.berrypimimpl;
import com.cvberry.berrypim.ChartingUtil;
import com.cvberry.berrypim.ControllerObject;
import com.cvberry.util.AuthInfoHolder;
import com.cvberry.util.Utility;
import com.sun.management.OperatingSystemMXBean;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.Map;
/**
* Created by vancan1ty on 1/4/2016.
*/
public class SystemInfoController extends PIMDefaultController implements ControllerObject {
public SystemInfoController(String controllerBase) {
this.controllerBase = controllerBase;
}
@Override
public List<Map.Entry<String, String>> getTopTabsItems() {
String[] starter = {
"home", "Home",
};
return Utility.tupleizeArray(starter);
}
@Override
public String fill_contentPane(String[] pathComponents, Map<String, String[]> queryParams, String dataBody,
AuthInfoHolder authInfo) {
StringBuilder out = new StringBuilder();
out.append("<p>Welcome to berryPIM. This program is still a work in progress!</p>");
out.append("<h2>System Statistics</h2>");
OperatingSystemMXBean opBean= (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
long totalMemorySize = opBean.getTotalPhysicalMemorySize();
long freeMemory = opBean.getFreePhysicalMemorySize();
long usedMemory = totalMemorySize - freeMemory;
Double BYTESINGIG = 1000000000.0;
File file = new File("/");
long totalDiskSize = (file.getTotalSpace());
long freeDiskSpace = file.getFreeSpace();
long usedDiskSpace = totalDiskSize-freeDiskSpace;
out.append("<table class='fullspan center'><tr>\n");
out.append("<th><h3>Memory</h3></th>\n");
out.append("<th><h3>Disk</h3></th>\n");
out.append("</tr><tr>\n");
out.append("<td>");
out.append(ChartingUtil.createAndEnqueuePieChart(
ChartingUtil.createPieDatasetFromArrays(new String[]{"Free","Used"},
new Double[]{freeMemory/BYTESINGIG,usedMemory/BYTESINGIG}),
null,rootPathStr,true,true,300,300));
out.append("<br><table>\n");
out.append("<tr><th>Total</th><th>Free</th><th>Used</th></tr>\n");
out.append(String.format("<tr><td>%.1f</td><td>%.1f</td><td>%.1f</td></tr>\n",
totalMemorySize/BYTESINGIG,freeMemory/BYTESINGIG,usedMemory/BYTESINGIG));
out.append("</table>\n");
out.append("</td><td>");
out.append(ChartingUtil.createAndEnqueuePieChart(
ChartingUtil.createPieDatasetFromArrays(new String[]{"Free","Used"},
new Double[]{freeDiskSpace/BYTESINGIG,usedDiskSpace/BYTESINGIG}),
null,rootPathStr,true,true,300,300));
out.append("<br><table>\n");
out.append("<tr><th>Total</th><th>Free</th><th>Used</th></tr>\n");
out.append(String.format("<tr><td>%.1f</td><td>%.1f</td><td>%.1f</td></tr>\n",
totalDiskSize/BYTESINGIG,freeDiskSpace/BYTESINGIG,usedDiskSpace/BYTESINGIG));
out.append("</td>");
out.append("</table>\n");
return out.toString();
}
}
......@@ -4,24 +4,56 @@ import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* Created by vancan1ty on 1/22/2016.
*/
public class DomVisitingHelper {
// public static void domVisitTree(Document doc, Consumer<Node> funcToDo) {
// domVisitTree(doc.getParentNode(), funcToDo);
// }
//
// public static void domVisitTree(Node node, Function<Node,Boolean> funcToDo) {
// boolean recurse = funcToDo.apply(node);
// NodeList children = node.getChildNodes();
// for (int i = 0; i < children.getLength(); i++) {
// Node child = children.item(i);
// funcToDo.accept()
// }
// }
public static int domVisitTree(Document doc, ItemVisitorHelper funcToDo) {
Node firstChild = doc.getFirstChild();
if(firstChild == null) {
System.out.println("empty document!");
return -1;
}
return domVisitTree(firstChild,funcToDo);
}
/**
* returns the count of the number of nodes for which 'funcToDo' returned false.
* @param node
* @param funcToDo
* @return
*/
public static int domVisitTree(Node node, ItemVisitorHelper funcToDo) {
int count = 0;
boolean recurse = funcToDo.apply(node);
if (!recurse) {
count++;
}
if(recurse) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
count += domVisitTree(child,funcToDo);
}
}
return count;
}
public static abstract class ItemVisitorHelper {
/**
* @param node
* @return true IFF the handler should recurse to this node's children.
*/
public abstract Boolean apply(Node node);
/**
* this function is intended to be called after the traversal of the tree has been accomplished
*/
public abstract void doFinalAction();
}
}
......@@ -26,9 +26,9 @@ import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.function.Function;
/**
* Created by vancan1ty on 1/2/2016.
......@@ -124,15 +124,11 @@ public class Utility {
}
public static String runXQueryOnString(String documentStr, String query) throws IOException, SAXException,
ParserConfigurationException, XPathExpressionException, TransformerException, XPathFactoryConfigurationException, SaxonApiException {
public static String runXQueryOnSource(Source source, String query) throws SaxonApiException, UnsupportedEncodingException {
Processor sxProcessor = new Processor(false);
net.sf.saxon.s9api.DocumentBuilder myBuilder = sxProcessor.newDocumentBuilder();
//myBuilder.setLineNumbering(true);
//myBuilder.setWhitespaceStrippingPolicy(WhitespaceStrippingPolicy.ALL); this line doesn't work.
InputStream docStream = new ByteArrayInputStream(documentStr.getBytes("UTF-8"));
Source source = new StreamSource(docStream);
XdmNode parsedDoc = myBuilder.build(source);
XQueryCompiler compiler = sxProcessor.newXQueryCompiler();
XQueryExecutable compQuery = compiler.compile(query);
......@@ -164,6 +160,21 @@ public class Utility {
return out;
}
public static String runXQueryOnDocument(Document document, String query) throws SaxonApiException, UnsupportedEncodingException {
DOMSource domSource = new DOMSource(document);
return runXQueryOnSource(domSource,query);
}
public static String runXQueryOnString(String documentStr, String query) throws IOException, SAXException,
ParserConfigurationException, XPathExpressionException, TransformerException, XPathFactoryConfigurationException, SaxonApiException {
InputStream docStream = new ByteArrayInputStream(documentStr.getBytes("UTF-8"));
StreamSource source = new StreamSource(docStream);
return runXQueryOnSource(source,query);
}
public static XdmSequenceIterator runXQueryOnStringToDS(String documentStr, String query) throws IOException, SAXException,
ParserConfigurationException, XPathExpressionException, TransformerException, XPathFactoryConfigurationException, SaxonApiException {
......@@ -209,14 +220,17 @@ public class Utility {
Processor sxProcessor = new Processor(false);
XdmNode xdmNode = sxProcessor.newDocumentBuilder().wrap(document);
return runXQueryOnXdmItem(xdmNode, query);
return runXQueryOnXdmItem(xdmNode, query,sxProcessor);
}
public static XdmSequenceIterator runXQueryOnXdmItem(XdmItem node, String query) throws IOException, SAXException,
public static XdmSequenceIterator runXQueryOnXdmItem(XdmItem node, String query, Processor sxProcessor) throws IOException, SAXException,
ParserConfigurationException, XPathExpressionException, TransformerException,
XPathFactoryConfigurationException, SaxonApiException {
Processor sxProcessor = new Processor(false);
if(sxProcessor == null) {
sxProcessor = new Processor(false);
}
XQueryCompiler compiler = sxProcessor.newXQueryCompiler();
XQueryExecutable compQuery = compiler.compile(query);
......@@ -234,7 +248,7 @@ public class Utility {
ParserConfigurationException, XPathExpressionException, TransformerException,
XPathFactoryConfigurationException, SaxonApiException {
XdmSequenceIterator iterator = runXQueryOnXdmItem(node, query);
XdmSequenceIterator iterator = runXQueryOnXdmItem(node, query,null);
if (!iterator.hasNext()) {
return null;
} else {
......@@ -257,7 +271,7 @@ public class Utility {
ParserConfigurationException, XPathExpressionException, TransformerException,
XPathFactoryConfigurationException, SaxonApiException {
XdmSequenceIterator iterator = runXQueryOnXdmItem(node,query);
XdmSequenceIterator iterator = runXQueryOnXdmItem(node,query,null);
if(!iterator.hasNext()) {
return null;
} else {
......@@ -269,7 +283,7 @@ public class Utility {
ParserConfigurationException, XPathExpressionException, TransformerException,
XPathFactoryConfigurationException, SaxonApiException {
XdmSequenceIterator iterator = runXQueryOnXdmItem(node,query);
XdmSequenceIterator iterator = runXQueryOnXdmItem(node,query,null);
if(!iterator.hasNext()) {
return null;
} else {
......@@ -301,10 +315,28 @@ public class Utility {
return out.toString();
}
public static String runXPathOnDOMNodeToString(Node node, String query) throws IOException, SAXException,
ParserConfigurationException, XPathExpressionException, TransformerException, XPathFactoryConfigurationException {
DocumentBuilderFactory factory = Utility.getConfiguredDocBuilderFactory();
XPath xPath = XPathFactory.newInstance().newXPath();
//XPath xPath = Anchor.getInstance().getXPF().newXPath();
String oRes = (String) xPath.compile(query).evaluate(node, XPathConstants.STRING);
return oRes;
}
public static NodeList runXPathOnDOMNode(Node node, String query) throws IOException, SAXException,
ParserConfigurationException, XPathExpressionException, TransformerException, XPathFactoryConfigurationException {
DocumentBuilderFactory factory = Utility.getConfiguredDocBuilderFactory();
XPath xPath = XPathFactory.newInstance().newXPath();
//XPath xPath = Anchor.getInstance().getXPF().newXPath();
NodeList oRes = (NodeList) xPath.compile(query).evaluate(node, XPathConstants.NODESET);
return oRes;
}
static Transformer transformer = null;
//http://stackoverflow.com/questions/4412848/xml-node-to-string-in-java
private static String nodeToString(Node node) throws TransformerException {
public static String nodeToString(Node node) throws TransformerException {
StringWriter sw = new StringWriter();
removeEmptyText(node);