I'm trying to retrieve the output of commandOutput in order to pass it to another function, but commandCompleted is never ran. Any help?
Command command = new Command(0, "cat " + file){
private String output;
#Override
public void commandCompleted(int id, int exitCode) {
Log.d("Commands.Completed", output);
Log.d("Commands.Completed", "ID: " + id + " & exitCode: " + exitCode);
saveData(output);
}
#Override
public void commandOutput(int id, String line) {
output += line + "\n";
}
#Override
public void commandTerminated(int id, String reason) {
}
};
try {
RootTools.getShell(true).add(command);
} catch (IOException | RootDeniedException | TimeoutException e) {
e.printStackTrace();
}
Your commandCompleted(int id, int exitCode) implementation is missing
super.commandCompleted(id, exitCode);
could it be the problem?
If you imported RootTools as
import com.stericson.RootTools.*;
you could also be using RootTools.Log which is muted by default. Maybe try to use
android.util.Log.d("Commands.Completed", output);
just to exclude the case.
Related
I make a plugin for my Minecraft Server and everything works well.
I use a users.yml file to store some data for every user like the groups and uuid.
Something weird is happening now, and I don't know how to solve it:
My users.yml is generating fine, no problems. All data is saved in there and I can access it.
BUT when I try to edit for example the group of the user from the default (this is the group that's assigned to every new user) to admin in the file itself and the user is joining again, the file overwrites the group to default.
What do I not see in the codes below to prevent the overwrite or did I do something wrong?
This is the function that creates the users.yml file:
public class UserList {
private static File usersFile;
private static FileConfiguration usersConf;
public static void Setup(){
usersFile = new File(Main.getInstance().getDataFolder(), "users.yml");
if(!usersFile.exists()){
try {
usersFile.createNewFile();
} catch (Exception e){
System.out.println("Error creating Usersfile: " + e);
}
}
usersConf = YamlConfiguration.loadConfiguration(usersFile);
}
public static FileConfiguration get(){
return usersConf;
}
public static void Save(){
try {
usersConf.save(usersFile);
} catch (Exception e){
System.out.println("Error saving Usersfile: " + e);
}
}
public static void reload(){
usersConf = YamlConfiguration.loadConfiguration(usersFile);
}
}
This is the code in the onEnabled() function:
#Override
public void onEnable() {
instance = this;
if (!getDataFolder().exists()) getDataFolder().mkdir();
//Erstelle users.yml mit Standardwerten
UserList.Setup();
UserList.get().addDefault("groups.admin.prefix", "§c");
UserList.get().addDefault("groups.vip.prefix", "§6");
UserList.get().addDefault("groups.default.prefix", "§7");
UserList.get().options().copyDefaults(false);
UserList.Save();
//Hole alle Usergruppen
Set<String> groups = UserList.get().getConfigurationSection("groups").getKeys(false);
//Events Registrieren
getServer().getPluginManager().registerEvents(this, this);
}
And here is the code that executes when a player is joining on the server:
#EventHandler
public void onJoin(PlayerJoinEvent e){
Player p = e.getPlayer();
if (UserList.get().get("users." + p.getName() + ".group") == null){ //<- I tried to prevent it with this if-statement but the problem must be elsewhere
UserList.get().set("users." + p.getName() + ".group", "default");
}
UserList.get().set("users." + p.getName() + ".uuid", p.getUniqueId().toString());
UserList.Save();
if (!p.hasPlayedBefore()) e.setJoinMessage(ChatColor.YELLOW + p.getName() + ChatColor.WHITE + " is new on this Server!");
else e.setJoinMessage(ChatColor.YELLOW + p.getName() + ChatColor.WHITE + " is " + ChatColor.GREEN + "Online");
}
It's thie line that create the issue:
UserList.get().options().copyDefaults(false);
You should use saveDefaultConfig() which will write the config if (and only if) the config file doesn't exist.
This method should be call with your plugin instance, and will works with your config.yml file.
If you want to copy a file when it doesn't exist, you should do like that :
File usersFile = new File(Main.getInstance().getDataFolder(), "users.yml");
if(!usersFile.exists()){
try (InputStream in = pl.getResource("users.yml");
OutputStream out = new FileOutputStream(usersFile)) {
ByteStreams.copy(in, out);
} catch (Exception e) {
e.printStackTrace();
}
}
config = YamlConfiguration.loadConfiguration(usersFile);
I have written a small program in Java (eclipse) to run R using JRI (rjava). All paths are set. The problem is that while I can run numeric functions (like add), I can't run a string function like cat. (please excuse any errors; I did Java coding for the first time yesterday).
package com.trial.ss;
import org.rosuda.JRI.Rengine;
public class RScriptConnection {
public Rengine getRScriptEngine() throws Exception {
Rengine engine = null;
try {
engine = Rengine.getMainEngine();
if (engine == null) engine = new Rengine(new String[] {
"--vanilla"
},
false, null);
/* if (!engine.waitForR()) {
System.out.println("Unable to load R");
return null;
} else*/
System.out.println("Connected to R");
String rScriptSourceFile = "source('" + RScriptConstant.RS_FILE_LOCATION + "',verbose=TRUE)";
engine.eval(rScriptSourceFile);
System.out.println("loading RScript file || completed");
//return engine;
} catch(Exception ex) {
System.out.println("Exeption while connecting to REngine " + ex.getMessage());
//throw new Exception("Error while creating REngine in RScriptConnection:getRScriptEngine()");
}
return engine;
}
public static void main(String[] args) {
String libpath = System.getProperty("java.library.path");
System.out.println("##############libpath=" + libpath);
// System.out.println("Method to be called in RScript=" + "Add(x1 = " + 10 + ", x2 = " + 20 + ", x3 = " + 30 + ", x4 = " + 50 + ")");
RScriptConnection rScriptConnection = new RScriptConnection();
try {
Rengine rEngine = rScriptConnection.getRScriptEngine();
String Value1 = "\"Advisory\"";
String Value2 = "\"Assurance\"";
double svalue = rEngine.eval("(1+2)").asDouble();
System.out.println("mvalue=" + svalue);
System.out.println("method to be called in RScript is " + "cat(" + Value1 + "," + Value2 + ")");
String value = rEngine.eval("cat(" + Value1 + "," + Value2 + ")").asString();
System.out.println(value);
rEngine.end();
} catch(Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please help me understand why my string function like cat doesn't work.
Here is the output I am currently getting:
##############libpath=C:\Users\myname\Documents\R\win-library\3.3\rJava\jri\x64
Connected to R
loading RScript file || completed
mvalue=3.0
method to be called in RScript is cat("Advisory","Assurance")
null
Why am I getting null in the end? I should get Advisory Assurance
Bellow is an example of how to show R output into Java. You basically have to implement RMainLoopCallbacks.
import org.rosuda.JRI.RMainLoopCallbacks;
import org.rosuda.JRI.Rengine;
import java.util.logging.Logger;
public class Runner {
private static Logger log = Logger.getLogger("Runner");
static class LoggingConsole implements RMainLoopCallbacks {
private Logger log;
LoggingConsole(Logger log) {
this.log = log;
}
public void rWriteConsole(Rengine re, String text, int oType) {
log.info(String.format("rWriteConsole: %s", text));
}
public void rBusy(Rengine re, int which) {
log.info(String.format("rBusy: %s", which));
}
public void rShowMessage(Rengine re, String message) {
log.info(String.format("rShowMessage: %s", message));
}
public String rReadConsole(Rengine re, String prompt, int addToHistory) {
return null;
}
public String rChooseFile(Rengine re, int newFile) {
return null;
}
public void rFlushConsole(Rengine re) {
}
public void rLoadHistory(Rengine re, String filename) {
}
public void rSaveHistory(Rengine re, String filename) {
}
}
Rengine engine = new Rengine(new String[] {"--no-save"}, false, new LoggingConsole(log));
...
// Use the engine somewhere to evaluate a R method and see the output
engine.eval(rScriptSourceFile);
}
I am attempting to use the Omegle Java API found here: https://github.com/nikkiii/omegle-api-java. However, the following code:
package me.nrubin29.pollmegle;
import org.nikki.omegle.Omegle;
import org.nikki.omegle.core.OmegleMode;
import org.nikki.omegle.core.OmegleSession;
import org.nikki.omegle.core.OmegleSpyStranger;
import org.nikki.omegle.event.OmegleEventAdaptor;
import java.util.Map;
public class Pollmegle {
public static void main(String[] args) {
Omegle omegle = new Omegle();
final String question = "Yes or no?";
System.out.println(question);
try {
OmegleSession session = omegle.openSession(OmegleMode.SPY_QUESTION, question, new OmegleEventAdaptor() {
#Override
public void chatWaiting(OmegleSession session) {
System.out.println("Waiting for chat...");
}
#Override
public void chatConnected(OmegleSession session) {
System.out.println("You are now watching two strangers talk about \"" + question + "\"!");
}
#Override
public void spyMessage(OmegleSession session, OmegleSpyStranger stranger, String message) {
System.out.println(stranger + ": " + message);
}
#Override
public void spyDisconnected(OmegleSession session, OmegleSpyStranger stranger) {
System.out.println("Stranger "+stranger+" disconnected, goodbye!");
System.exit(0);
}
#Override
public void question(OmegleSession session, String question) {
System.out.println("Question: "+question);
}
#Override
public void omegleError(OmegleSession session, String string) {
System.out.println("ERROR! " + string);
System.exit(1);
}
#Override
public void recaptchaRequired(OmegleSession session, Map<String, Object> variables) {
System.out.print("Required // ");
for (String var : variables.keySet()) {
System.out.println(var + " // " + variables.get(var));
}
}
#Override
public void recaptchaRejected(OmegleSession session, Map<String, Object> variables) {
System.out.println("Rejected // ");
for (String var : variables.keySet()) {
System.out.println(var + " // " + variables.get(var));
}
}
});
System.out.println("Session " + session.getId() + " created.");
omegle.setEventParseDelay(1000);
omegle.run();
}
catch (Exception e) { e.printStackTrace(); }
}
}
Yields this result:
Yes or no?
Required // 6Led7gkAAAAAAEAyh-Kt7HTb_oC0chDvQIZ8VtQb // null
Session central1:znv479i7a5sh2u60z5sg6s2nzm6jpb created.
What am I doing wrong? Do I need to pass a captcha?
no, its supposed to output this. but when i ran the code i kept getting "enum not found errors" so i went into org.nikki.omegle.core.OmegleEvent and added the lines
,statusInfo,identDigests
to the bottom and it worked like a charm. Are you getting the same enum not found errors?
Turns out the problem isn't the API, it's that my IP address was flagged and I needed to enter a reCAPTCHA every time I started a chat. It works.
In my app I need to add string vallues to the file(.property file, if it is important). and user enter this values in gwt GUI. Here is it's important part:
final Button submit = new Button("Submit");
addButton(submit);
submit.addSelectionListener(new SelectionListener<ButtonEvent>() {
#Override
public void componentSelected(ButtonEvent ce) {
keyWord.selectAll();
regexp.selectAll();
if (keyWord.getValue() != null){
setKeyWord(customerId, keyWord.getValue());
keyWord.setValue("");
}
if (regexp.getValue() != null){
setRegExp(customerId, regexp.getValue());
regexp.setValue("");
}
}
});
}
private void setKeyWord(final String customerId, final String keyword){
final AsyncCallback<String> callbackItems = new AsyncCallback<String>() {
public void onFailure(final Throwable caught) {
Window.alert("unable to add " + caught.toString());
}
public void onSuccess(final String x) {
Window.alert(x);
}
};
serverManagementSvc.setKeyWords(customerId, keyword, callbackItems);
}
private void setRegExp(final String customerId, final String regexp){
final AsyncCallback<String> calbackItems = new AsyncCallback<String>() {
#Override
public void onFailure(Throwable throwable) {
Window.alert("unable to add " + throwable.toString());
}
#Override
public void onSuccess(String s) {
Window.alert(s);
}
};
serverManagementSvc.setRegExp(customerId, regexp, calbackItems);
}
So I need to use Asunccallback to call methods which are in the "server part".
here are these methods:
//adds a new keyword to customers properties
public String setKeyWords(String customer, String word){
try{
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newKeyWord = new String(props.getString("users." + customer + ".keywords" + "," + word));
props.setProperty("users." + customer + ".keywords", newKeyWord);
props.save();
}catch (ConfigurationException e){
e.printStackTrace();
}
return "keyword " + word + " added";
}
// adds a new regexp to customer properties
public String setRegExp(String customer, String regexp){
try {
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newRegValue = new String(props.getString("users." + customer + ".regexps" + "," + regexp));
props.setProperty("users." + customer + ".regexps", newRegValue);
props.save();
} catch (ConfigurationException e){
e.printStackTrace();
}
return "regexp " + regexp + " added to " + customer + "'s config";
}
all interfaces are present.
when I run my code And press "submit" button in gui I see that both asynccallback failured(Window.alert, as you can see, shows "null pointer exception" despite of the fact that values which I send to methods are not null). why can it be? can you suggest me something?
UPD here is error which is shown by firebug:
uncaught exception: java.lang.ClassCastException
function W8(){try{null.a()}catch(a){return a}}
the problem is solved: there were a simple mistake in the code. I've closed brackets at the wrong place:
//adds a new keyword to customers properties
public String setKeyWords(String customer, String word){
try{
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newKeyWord = new String(props.getString("users." + customer + ".keywords") + "," + word);
props.setProperty("users." + customer + ".keywords", newKeyWord);
props.save();
}catch (ConfigurationException e){
e.printStackTrace();
}
return "keyword " + word + " added";
}
// adds a new regexp to customer properties
public String setRegExp(String customer, String regexp){
try {
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newRegValue = new String(props.getString("users." + customer + ".regexps") + "," + regexp);
props.setProperty("users." + customer + ".regexps", newRegValue);
props.save();
} catch (ConfigurationException e){
e.printStackTrace();
}
return "regexp " + regexp + " added to " + customer + "'s config";
}
I recommend that you recompile the GWT code using
-style PRETTY
and then check that firebug output again; it may give you a better clue, compared to your updated uncaught exception.
Next, I suggest you run it in the eclipse debugger, and set breakpoints in both the client and server code, and then you can inspect the variables and step through the code.
I am new to cryptography. I have to develop project based on cryptography..In part of my project I have to insert a key to the registry and afterwards I have to retrieve the same key for decryption.. I done until getting the path of the registry ..
Here I am showing my code:
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
public final class Project {
public static final String readRegistry(String location, String key) {
try {
// Run reg query, then read output with StreamReader (internal class)
Process process = Runtime.getRuntime().exec("reg query " +
'"' + location + "\" /v " + key);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String output = reader.getResult();
// Output has the following format:
// \n<Version information>\n\n<key>\t<registry type>\t<value>
if (!output.contains("\t")) {
return null;
}
// Parse out the value
String[] parsed = output.split("\t");
return parsed[parsed.length - 1];
} catch (Exception e) {
return null;
}
}
static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw = new StringWriter();
public StreamReader(InputStream is) {
this.is = is;
}
public void run() {
try {
int c;
while ((c = is.read()) != -1) {
System.out.println("Reading" + c);
sw.write(c);
}
} catch (IOException e) {
System.out.println("Exception in run() " + e);
}
}
public String getResult() {
System.out.println("Content " + sw.toString());
return sw.toString();
}
}
public static boolean addValue(String key, String valName, String val) {
try {
// Run reg query, then read output with StreamReader (internal class)
Process process = Runtime.getRuntime().exec("reg add \"" + key + "\" /v \"" + valName + "\" /d \"\\\"" + val + "\\\"\" /f");
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String output = reader.getResult();
System.out.println("Processing........ggggggggggggggggggggg." + output);
// Output has the following format:
// \n<Version information>\n\n<key>\t<registry type>\t<value>
return output.contains("The operation completed successfully");
} catch (Exception e) {
System.out.println("Exception in addValue() " + e);
}
return false;
}
public static void main(String[] args) {
// Sample usage
JAXRDeleteConcept hc = new JAXRDeleteConcept();
System.out.println("Before Insertion");
if (JAXRDeleteConcept.addValue("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU", "REG_SZ", "Muthus")) {
System.out.println("Inserted Successfully");
}
String value = JAXRDeleteConcept.readRegistry("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU" , "Project_Key");
System.out.println(value);
}
}
But i dont know how to insert a key in a registry and read the particular key which i inserted..Please help me..
Thanks in advance..
It would be a lot easier to use the JRegistry library to edit the registry, rather than execute commands.