use of com.laytonsmith.persistence.DataSourceException in project CommandHelper by EngineHub.
the class PNViewer method loadFromLocal.
private void loadFromLocal(final String path) {
localPath = path;
new Thread(new Runnable() {
@Override
public void run() {
setStatus("Loading from local file system", true);
setProgress(null);
try {
final PersistenceNetwork pn = getPersistenceNetwork(path);
VirtualPersistenceNetwork vpn = new VirtualPersistenceNetwork() {
@Override
public Map<String[], String> getAllData() throws DataSourceException {
return pn.getNamespace(ArrayUtils.EMPTY_STRING_ARRAY);
}
@Override
public URI getKeySource(String[] key) {
return pn.getKeySource(key);
}
};
displayData(vpn);
} catch (URISyntaxException | IOException | DataSourceException ex) {
Logger.getLogger(PNViewer.class.getName()).log(Level.SEVERE, null, ex);
showError(ex.getMessage());
}
}
}).start();
}
use of com.laytonsmith.persistence.DataSourceException in project CommandHelper by EngineHub.
the class PNViewer method startServer.
public static void startServer(int port, final String password) throws IOException {
ServerSocket socket = new ServerSocket(port);
log("Server started on port " + port + ". Type Ctrl+C to kill the server.");
log("Process info: " + ManagementFactory.getRuntimeMXBean().getName());
log("Server version: " + PROTOCOL_VERSION);
connection: while (true) {
log("Persistence Network Viewers may now connect to this server.");
final Socket s = socket.accept();
log("A client has connected from " + s.getInetAddress().toString());
new Thread(new Runnable() {
@Override
public void run() {
Thread waitThread = null;
try {
final AtomicBoolean dataReceieved = new AtomicBoolean(false);
final AtomicBoolean longTimeout = new AtomicBoolean(false);
waitThread = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
synchronized (dataReceieved) {
dataReceieved.wait(longTimeout.get() ? 10 * 60 * 1000 : 10 * 1000);
}
if (dataReceieved.get() == false) {
log("No response from client in too long, forcibly closing connection.");
try {
s.close();
} catch (IOException ex) {
//
}
break;
}
dataReceieved.set(false);
}
} catch (InterruptedException ex) {
//
}
}
});
waitThread.start();
ObjectInputStream is = new ObjectInputStream(s.getInputStream());
ObjectOutputStream os = new AutoFlushObjectOutputStream(s.getOutputStream());
int protocolVersion = is.readInt();
if (protocolVersion != PROTOCOL_VERSION) {
log("Client version unsupported: " + protocolVersion);
os.writeUTF("VERSION-MISMATCH");
return;
} else {
log("Client version supported: " + protocolVersion);
os.writeUTF("VERSION-OK");
}
String clientPassword = is.readUTF();
if (!password.equals(clientPassword)) {
log("Client supplied the wrong password, disconnecting.");
os.writeUTF("PASSWORD-BAD");
os.writeUTF("DISCONNECT");
return;
} else {
if (!"".equals(password)) {
log("Client supplied the correct password");
}
os.writeUTF("PASSWORD-OK");
}
// They have now authed correctly, so we can up the idle time.
longTimeout.set(true);
// Now we need to create instance variables for the remainder of
// the connection, that is, the meat of the connection.
String remoteFile = null;
PersistenceNetwork pn = null;
connected: while (s.isConnected()) {
String command = is.readUTF();
log("Command received from client: " + command);
dataReceieved.set(true);
synchronized (dataReceieved) {
dataReceieved.notifyAll();
}
switch(command) {
case "DISCONNECT":
// Write the disconnect out to the client as well, so
// the client will gracefully disconnect.
os.writeUTF("DISCONNECT");
break connected;
case "SET-REMOTE-FILE":
remoteFile = is.readUTF();
log("File set to " + remoteFile);
if (new File(remoteFile).exists()) {
log("File accepted.");
os.writeUTF("FILE-OK");
} else {
log("File not accepted.");
os.writeUTF("FILE-BAD");
os.writeUTF("DISCONNECT");
}
break;
case "LOAD-DATA":
os.writeUTF("LOAD-DATA");
try {
// Load the data from the PN, and send it on
pn = getPersistenceNetwork(remoteFile);
Map<String[], String> data = pn.getNamespace(ArrayUtils.EMPTY_STRING_ARRAY);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(data);
oos.flush();
byte[] output = baos.toByteArray();
os.writeInt(output.length);
os.write(output);
} catch (URISyntaxException | DataSourceException ex) {
os.writeUTF("LOAD-ERROR");
os.writeUTF(ex.getMessage());
log("Load error!");
log(ex);
}
break;
case "KEY-SOURCE":
os.writeUTF("KEY-SOURCE");
String key = is.readUTF();
if (pn == null) {
log("pn is null, can't get key source");
os.writeUTF("DISCONNECT");
} else {
log("Requested source for key: " + key);
URI uri = pn.getKeySource(key.split("\\."));
log("Responding with: " + uri);
os.writeObject(uri);
}
break;
default:
// Bad command, disconnect them.
os.writeUTF("DISCONNECT");
break connected;
}
}
} catch (IOException ex) {
// Disconnected
} finally {
try {
s.close();
} catch (IOException ex) {
//
}
log("Client has disconnected.");
if (waitThread != null) {
waitThread.interrupt();
}
}
}
}).start();
}
}
use of com.laytonsmith.persistence.DataSourceException in project CommandHelper by EngineHub.
the class SiteDeploy method generateFunctionDocs.
private void generateFunctionDocs(Function f, DocGen.DocInfo docs) {
StringBuilder page = new StringBuilder();
page.append("== ").append(f.getName()).append(" ==\n");
page.append("<div>").append(docs.desc).append("</div>\n");
page.append("=== Vital Info ===\n");
page.append("{| style=\"width: 40%;\" cellspacing=\"1\" cellpadding=\"1\" border=\"1\" class=\"wikitable\"\n");
page.append("|-\n" + "! scope=\"col\" width=\"20%\" | \n" + "! scope=\"col\" width=\"80%\" | \n" + "|-\n" + "! scope=\"row\" | Name\n" + "| ").append(f.getName()).append("\n" + "|-\n" + "! scope=\"row\" | Returns\n" + "| ").append(docs.ret).append("\n" + "|-\n" + "! scope=\"row\" | Usages\n" + "| ").append(docs.args).append("\n" + "|-\n" + "! scope=\"row\" | Throws\n" + "| ");
List<String> exceptions = new ArrayList<>();
for (Class<? extends CREThrowable> c : f.thrown()) {
String t = c.getAnnotation(typeof.class).value();
exceptions.add("[[../objects/" + t + "|" + t + "]]");
}
page.append(StringUtils.Join(exceptions, "<br>"));
page.append("\n" + "|-\n" + "! scope=\"row\" | Since\n" + "| ").append(f.since()).append("\n" + "|-\n" + "! scope=\"row\" | Restricted\n");
page.append("| <div style=\"background-color: ");
page.append(f.isRestricted() ? "red" : "green");
page.append("; font-weight: bold; text-align: center;\">").append(f.isRestricted() ? "Yes" : "No").append("</div>\n" + "|-\n" + "! scope=\"row\" | Optimizations\n" + "| ");
String optimizationMessage = "None";
if (f instanceof Optimizable) {
Set<Optimizable.OptimizationOption> options = ((Optimizable) f).optimizationOptions();
List<String> list = new ArrayList<>();
for (Optimizable.OptimizationOption option : options) {
list.add("[[../../Optimizer#" + option.name() + "|" + option.name() + "]]");
}
optimizationMessage = StringUtils.Join(list, " <br /> ");
}
page.append(optimizationMessage);
page.append("\n|}");
if (docs.extendedDesc != null) {
page.append("<div>").append(docs.extendedDesc).append("</div>");
}
String[] usages = docs.originalArgs.split("\\|");
StringBuilder usageBuilder = new StringBuilder();
for (String usage : usages) {
usageBuilder.append("<pre>\n").append(f.getName()).append("(").append(usage.trim()).append(")\n</pre>");
}
page.append("\n=== Usages ===\n");
page.append(usageBuilder.toString());
StringBuilder exampleBuilder = new StringBuilder();
try {
if (f.examples() != null && f.examples().length > 0) {
int count = 1;
// If the output was automatically generated, change the color of the pre
for (ExampleScript es : f.examples()) {
exampleBuilder.append("====Example ").append(count).append("====\n").append(HTMLUtils.escapeHTML(es.getDescription())).append("\n\n" + "Given the following code:\n");
exampleBuilder.append(SimpleSyntaxHighlighter.Highlight(es.getScript(), true)).append("\n");
String style = "";
exampleBuilder.append("\n\nThe output ");
if (es.isAutomatic()) {
style = " background-color: #BDC7E9;";
exampleBuilder.append("would");
} else {
exampleBuilder.append("might");
}
exampleBuilder.append(" be:\n<pre class=\"pre\" style=\"border-top: 1px solid blue; border-bottom: 1px solid blue;").append(style).append("\"");
exampleBuilder.append(">%%NOWIKI|").append(es.getOutput()).append("%%").append("</pre>\n");
count++;
}
} else {
exampleBuilder.append("Sorry, there are no examples for this function! :(\n");
}
} catch (ConfigCompileException | IOException | DataSourceException | URISyntaxException ex) {
exampleBuilder.append("Error while compiling the examples for ").append(f.getName());
}
page.append("\n=== Examples ===\n");
page.append(exampleBuilder.toString());
Class<?>[] seeAlso = f.seeAlso();
String seeAlsoText = "";
if (seeAlso != null && seeAlso.length > 0) {
seeAlsoText += "===See Also===\n";
boolean first = true;
for (Class<?> c : seeAlso) {
if (!first) {
seeAlsoText += ", ";
}
first = false;
if (Function.class.isAssignableFrom(c)) {
Function f2 = (Function) ReflectionUtils.newInstance(c);
seeAlsoText += "<code>[[" + f2.getName() + "|" + f2.getName() + "]]</code>";
} else if (Template.class.isAssignableFrom(c)) {
Template t = (Template) ReflectionUtils.newInstance(c);
seeAlsoText += "[[" + t.getName() + "|Learning Trail: " + t.getDisplayName() + "]]";
} else {
throw new Error("Unsupported class found in @seealso annotation: " + c.getName());
}
}
}
page.append(seeAlsoText);
Class<?> container = f.getClass();
while (container.getEnclosingClass() != null) {
container = container.getEnclosingClass();
}
String bW = "<p id=\"edit_this_page\">" + EDIT_THIS_PAGE_PREAMBLE + String.format(githubBaseUrl, "java/" + container.getName().replace(".", "/")) + ".java" + EDIT_THIS_PAGE_POSTAMBLE + " (Note this page is automatically generated from the documentation in the source code.)</p>";
page.append(bW);
String description = "";
writePage(f.getName(), page.toString(), "API/functions/" + f.getName(), Arrays.asList(new String[] { f.getName(), f.getName() + " api", f.getName() + " example", f.getName() + " description" }), description);
}
use of com.laytonsmith.persistence.DataSourceException in project CommandHelper by EngineHub.
the class Manager method merge.
public static void merge() {
cls();
pl(GREEN + "Transferring a database takes all the keys from a database connection, and puts\n" + "them straight into another database. If there are key conflicts, this tool will prompt\n" + "you for an action.");
ConnectionMixinFactory.ConnectionMixinOptions mixinOptions = new ConnectionMixinFactory.ConnectionMixinOptions();
mixinOptions.setWorkingDirectory(chDirectory);
DataSource source;
DataSource destination;
do {
// the exact same value.
do {
// Get the source connection set up
pl(YELLOW + "What is the source connection you would like to read the keys from?\n" + "(Type the connection exactly as you would in the persistence configuration,\n" + "aliases are not supported)");
String ssource = prompt();
try {
source = DataSourceFactory.GetDataSource(ssource, mixinOptions);
break;
} catch (DataSourceException | URISyntaxException ex) {
pl(RED + ex.getMessage());
}
} while (true);
do {
// Get the destination connection set up
pl(YELLOW + "What is the destination connection?");
String sdestination = prompt();
try {
destination = DataSourceFactory.GetDataSource(sdestination, mixinOptions);
break;
} catch (DataSourceException | URISyntaxException ex) {
pl(RED + ex.getMessage());
}
} while (true);
try {
// Run through all the source's keys, and check to see that either the
// destination's key doesn't exist, or the value at that key is the
// exact same as the source's value
boolean acceptAllDestination = false;
boolean acceptAllSource = false;
DaemonManager dm = new DaemonManager();
for (String[] key : source.keySet(ArrayUtils.EMPTY_STRING_ARRAY)) {
if (destination.hasKey(key)) {
if (!source.get(key).equals(destination.get(key))) {
String data;
// ask.
if (destination.get(key) != null) {
boolean useSource = false;
boolean useDestination = false;
if (acceptAllDestination || acceptAllSource) {
p(RED + "Conflict found for " + StringUtils.Join(key, ".") + ", using ");
if (useSource) {
useSource = true;
p("source");
} else {
useDestination = true;
p("destination");
}
pl(" value.");
} else {
pl(BG_RED + BRIGHT_WHITE + "The key " + StringUtils.Join(key, ".") + " has a different value" + " in the source and the destination: " + reset());
pl(WHITE + "Source: " + source.get(key));
pl(WHITE + "Destination: " + destination.get(key));
do {
pl(YELLOW + "Would you like to keep " + CYAN + "S" + YELLOW + "ource, " + "keep " + GREEN + "D" + YELLOW + "estination, keep " + MAGENTA + "A" + YELLOW + "ll " + MAGENTA + "S" + YELLOW + "ource, or keep " + BLUE + "A" + YELLOW + "ll " + BLUE + "D" + YELLOW + "estination?");
pl(WHITE + "[" + CYAN + "S" + WHITE + "/" + GREEN + "D" + WHITE + "/" + MAGENTA + "AS" + WHITE + "/" + BLUE + "AD" + WHITE + "]");
String response = prompt();
if ("AS".equalsIgnoreCase(response)) {
acceptAllSource = true;
useSource = true;
} else if ("AD".equalsIgnoreCase(response)) {
acceptAllDestination = true;
useDestination = true;
} else if ("S".equalsIgnoreCase(response)) {
useSource = true;
} else if ("D".equalsIgnoreCase(response)) {
useDestination = true;
} else {
continue;
}
break;
} while (true);
}
if (useSource) {
data = source.get(key);
} else if (useDestination) {
data = destination.get(key);
} else {
throw new RuntimeException("Invalid state, both useSource and useDestination are false");
}
// Ok, now put the data in the destination
} else {
// Otherwise, just use the data in the source
data = source.get(key);
}
destination.set(dm, key, data);
}
} else {
// Else there is no conflict, it's not in the destination.
destination.set(dm, key, source.get(key));
}
}
try {
dm.waitForThreads();
} catch (InterruptedException ex) {
//
}
break;
} catch (DataSourceException | ReadOnlyException | IOException ex) {
pl(RED + ex.getMessage());
}
} while (true);
pl(GREEN + "Done merging!");
}
use of com.laytonsmith.persistence.DataSourceException in project CommandHelper by EngineHub.
the class PNViewer method loadFromRemote.
private void loadFromRemote(final String host, final int port, final String password, final String remoteFile) {
remoteSocketThread = new Thread(new Runnable() {
@Override
public void run() {
try {
try (Socket s = new Socket()) {
s.connect(new InetSocketAddress(host, port), 30000);
remoteSocket = s;
setStatus("Connected to remote server", true);
setProgress(null);
try {
final ObjectOutputStream os = new AutoFlushObjectOutputStream(s.getOutputStream());
final ObjectInputStream is = new ObjectInputStream(s.getInputStream());
remoteOutput = os;
remoteInput = is;
// Set up our initial data
log("Writing client version: " + PROTOCOL_VERSION);
os.writeInt(PROTOCOL_VERSION);
switch(is.readUTF()) {
case "VERSION-OK":
break;
default:
showError("The server does not support this client's version.");
return;
}
os.writeUTF(password);
switch(is.readUTF()) {
case "PASSWORD-OK":
log("Password accepted by server.");
break;
default:
showError("Server rejected our password. Check the password and try again.");
return;
}
os.writeUTF("SET-REMOTE-FILE");
os.writeUTF(remoteFile);
final MutableObject<Map<String[], String>> data = new MutableObject<>();
final MutableObject<URI> sourceURI = new MutableObject<>();
VirtualPersistenceNetwork vpn = null;
connection: while (!Thread.currentThread().isInterrupted() && s.isConnected()) {
String serverCommand = is.readUTF();
switch(serverCommand) {
case "DISCONNECT":
break connection;
case "FILE-OK":
os.writeUTF("LOAD-DATA");
reloadButton.setEnabled(false);
break;
case "FILE-BAD":
showError("Remote file doesn't exist, disconnecting.");
break;
case "LOAD-DATA":
int size = is.readInt();
setStatus("Downloading data from server...", true);
setProgress(0);
byte[] bdata = new byte[size];
for (int i = 0; i < size; i++) {
bdata[i] = is.readByte();
setProgress((int) ((((double) i) / ((double) size)) * 100));
}
setStatus("Processing data from server", true);
setProgress(null);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bdata));
try {
Map<String[], String> d = (Map<String[], String>) ois.readObject();
data.setObject(d);
vpn = new VirtualPersistenceNetwork() {
Map<String, URI> sources = new HashMap<>();
@Override
public Map<String[], String> getAllData() throws DataSourceException {
return data.getObject();
}
@Override
public URI getKeySource(String[] key) {
String kk = join(key);
if (!sources.containsKey(kk)) {
try {
sourceURI.setObject(null);
os.writeUTF("KEY-SOURCE");
os.writeUTF(kk);
synchronized (sourceURI) {
if (sourceURI.getObject() == null) {
try {
sourceURI.wait();
} catch (InterruptedException ex) {
//
}
}
}
URI uri = sourceURI.getObject();
sources.put(kk, uri);
} catch (IOException ex) {
showError(ex.getMessage());
log(ex);
}
}
return sources.get(kk);
}
};
try {
displayData(vpn);
setStatus("Done.", false);
} catch (DataSourceException ex) {
log(ex);
showError(ex.getMessage());
}
} catch (ClassNotFoundException ex) {
log(ex);
showError(ex.getMessage());
}
reloadButton.setEnabled(true);
break;
case "KEY-SOURCE":
try {
URI uri = (URI) is.readObject();
sourceURI.setObject(uri);
synchronized (sourceURI) {
sourceURI.notifyAll();
}
} catch (ClassNotFoundException ex) {
log(ex);
}
break;
case "LOAD-ERROR":
String message = is.readUTF();
setStatus(message, false);
showError(message);
reloadButton.setEnabled(true);
break;
default:
showError("Server sent unrecognized command, disconnecting.");
log("Unrecognized command: " + serverCommand);
break connection;
}
}
log("Closing connection.");
} catch (EOFException ex) {
log(ex);
showError("The server closed the connection unexpectedly.");
}
} catch (SocketTimeoutException ex) {
showError("Connection timed out, check your settings and try again.");
} finally {
setStatus("Connection to remote server closed.", false);
remoteOutput = null;
remoteInput = null;
reloadButton.setEnabled(true);
}
} catch (IOException ex) {
showError(ex.getMessage());
Logger.getLogger(PNViewer.class.getName()).log(Level.SEVERE, null, ex);
}
remoteSocketThread = null;
}
});
remoteSocketThread.start();
}
Aggregations