Could anybody help me, please? I have this code:
Process a;
try {
a = Runtime.getRuntime().exec("su");
DataOutputStream swp = new DataOutputStream(a.getOutputStream());
swp.writeBytes("cat /proc/sys/vm/blabla\n");
swp.writeBytes("exit\n");
swp.flush();
try {
a.waitFor();
if (a.exitValue() != 255) {
// TODO Code to run on success
toastMessage("root");
}
else {
// TODO Code to run on unsuccessful
toastMessage("not root");
}
} catch (InterruptedException e) {
// TODO Code to run in interrupted exception
toastMessage("not root");
}
} catch (IOException e) {
// TODO Code to run in input/output exception
toastMessage("not root");
}
This code swp.writeBytes("cat /proc/sys/vm/blabla\n"); copies text (string) from system file called "blabla". And then I need to put this text (String) to my SharedPreferences. How can I achieve it?
If this was your code, you should know. In case you don't, you can follow the Tutorial.
In your case, you'll want to use the putString()-method.
To get what cat printed out, you'll need the output of your Process-object. Use the getInputStream()-method.
Related
I'm designing JMeter scenario which implies executing a certain .jar file via OS Process Sampler element. My Java code has while loop which basically checks a certain mailbox for a letter with a certain subject. Loop waits until finds one (emails are always delivered with roughly 3 minutes delay), parses it and writes some data to .txt file.
If I run this .jar directly from cmd then the code works as expected. But if I run it via JMeter OS Process Sampler then it never creates a file for me. I do see that email is delivered to inbox, so expect it to be parsed and .txt created.
At first I suspected that JMeter finishes Java scenario without waiting for while loop to execute. Then I put OS Process Sampler in a separate Thread and added a huge delay for this thread in order to wait and make 100% sure that email is delivered and Java only need to parse it but it does not help.
View Results Tree never shows any errors.
Here is my OS Process Sampler: https://www.screencast.com/t/LomYGShJHAkS
This is what I execute via cmd and it works as expected: java -jar mailosaurJavaRun.jar email533.druzey1a#mailosaur.in
And here is my code (it does not looks good but it works):
public class Run {
public static void main(String[] args) {
MailosaurHelper ms = new MailosaurHelper();
String arg1 = ms.getFirstLinkInEmail(args[0]);
BufferedWriter output = null;
try {
File file = new File("url.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(arg1);
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( output != null ) {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class MailosaurHelper {
protected final String API_KEY = "b3e4d2b193b5eb2";
protected final String MAILBOX_ID = "d1uzey1a";
public MailboxApi getEmailBox() {
return new MailboxApi(MAILBOX_ID, API_KEY);
}
public String getFirstLinkInEmail(String email) {
MailosaurHelper ms = new MailosaurHelper();
String link = "";
if (link.equals("") || link.isEmpty()) {
try {
Thread.sleep(3000);
link = ms.getAllEmailsByReceipent(email)[0].html.links[0]
.toString();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return link;
}
public Email[] getAllEmailsByReceipent(String recepient) {
try {
int ifArrayIsEmpty = getEmailBox().getEmailsByRecipient(recepient).length;
while (ifArrayIsEmpty == 0) {
try {
Thread.sleep(3000);
ifArrayIsEmpty = getEmailBox().getEmailsByRecipient(
recepient).length;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (MailosaurException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Email[] listOfEmails = null;
try {
listOfEmails = getEmailBox().getEmailsByRecipient(recepient);
} catch (MailosaurException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listOfEmails;
}
The bottom line is that I need to parse Mailosaur email, retrieve URL from it and use it further. Any other suggestion on how to do that using Jmeter/Java/Mailosaur are appreciated.
You don't need cmd in here, but if you're adamant to stick with it - use /C key when you call it.
Then, are your sure you're looking for your file in the right place?
According to documentation:
By default the classes in the java.io package always resolve relative
pathnames against the current user directory. This directory is named
by the system property user.dir, and is typically the directory in
which the Java virtual machine was invoked.
Check it thoroughly, BTW - you should see it in your sampler result.
This question already has answers here:
java.io.FileNotFoundException when creating FileInputStream
(2 answers)
Closed 6 years ago.
For my application I want to use a Map to act as a database. To save and load a map, I am writing/reading it to/from database.ser using this 2 methods:
private synchronized void saveDB() {
try {
fileOut = new FileOutputStream(db);
out = new ObjectOutputStream(fileOut);
out.writeObject(accounts);
fileOut.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private void loadDB() {
try {
fileIn = new FileInputStream(db);
in = new ObjectInputStream(fileIn); // that is where error is produced if fileIn is empty
accounts = (Map<String, Client>) in.readObject();
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I want to load into Map when application starts, so I invoke method in constructor like this:
protected DriveatorImpl() {
accounts = new ConcurrentHashMap<String, Client>();
db = new File("C:/Users/eduar/git/Multy-Threaded-Bank-System/Bank-Services/database.ser");
// also, any suggestions how can I make path to a file more flexible in case I want to run Server side of an app on different machine?
if (!db.exists()) {
try {
db.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
loadDB(); // loads database when server start
}
I am aware of what causing an error, but I don't know what should I change in my design to avoid ObjectInputStream constructor receiving empty stream!
Any suggestions on what I can do differently?
Edit: I want to note that in fresh application run database.ser is empty since there was no entries made into Map yet.
Thank You!
First why the EOFExcpetion occur?
There are no contents in file or file is empty and you tried to read file.
You can avoid the EOFException for an empty file by checking file content length if it is less than or equal to zero means file is empty. another way to check if file is empty
Some code change and it worked for me.
#SuppressWarnings("unchecked")
private void loadDB() {
try {
if (db.length() <= 0) {
// if statement evaluates to true even if file doesn't exists
saveDB(); // save to a file an empty map
// if file doesn't exist, it creates a new one
// call loadDB inside constructor
}
FileInputStream fileIn = new FileInputStream(db);
ObjectInputStream in = new ObjectInputStream(fileIn); // that is where error is produced if fileIn is empty
in.readObject();
in.close();
fileIn.close();
System.out.println(accounts);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Get rid of the file.exists()/file.createNewFile() crap. All it is doing for you is masking the original FileNotFoundException problem, and turning into a thoroughly predictable EOFException because of trying to construct an ObjectInputStream around an empty stream. Handle the original problem. Don't just move it, or turn it into something else.
I have this code
root = new Root();
root.checkRootMethod2();
TextView=(TextView)view.findViewById(R.id.textView4);
if(root.checkRootMethod2()) {
TextView.setText(Html.fromHtml("<b>TEXT 01</b><br>"));
} else {
TextView.setText(Html.fromHtml("<b>TEXT 02</b><br>"));
}
try {
if (root.RootAvailibility() && (root.checkRootMethod3())) {
try {
Process process = Runtime.getRuntime().exec("su");
OutputStream stdin = process.getOutputStream();
stdin.flush();
stdin.close();
} catch(Exception e) {
}
TextView.append(Html.fromHtml(
"<b><font color=\"green\">TEXT 03</b></font>"));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
root.busybox();
TextView.append(Html.fromHtml(
"<br><b><font color=\"green\">TEXT 04</b></font>"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e) {
TextView.append(Html.fromHtml(
"<br><b><font color=\"red\">TEXT05</b></font>"));
}
I wish that if if (root.RootAvailibility() && (root.checkRootMethod3())) return true Viewing a TextView that says something.If return false, another TextView that displays something else. As happens for root.checkRootMethod2 (); Same goes for root.busybox (); Do you have any idea on how I can do? Now visualize always Text04
try {
if (root.RootAvailibility() && (root.checkRootMethod3()))
{
try
{
/// your code ...
}
catch(Exception e){ }
TextView.append(Html.fromHtml("<b><font color=\"green\">TEXT 03</b></font>"));
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Codes here runs always regardless of if clause.
the code (try block in your case) runs regardless of the if condition as the try block clears the scope of if block.
Either put try completely inside if block or surround both if,else statement by a single try block.
I don't know what is the need of multiple try/catch here :
try {
if (root.RootAvailibility() && (root.checkRootMethod3()))
{
try
{
You can add one more catch(Exception e) to the upper try/catch block and that will serve the same purpose.
Secondly there is no else part to this if (root.RootAvailibility() && (root.checkRootMethod3())). So, if it is false the program will simply move forward.
Well you're always going to see Text04 because there's no conditional that excludes it. The try catch block it's in is at the top level.
It would help if you could provide a short, self-contained, compilable example of your code. There's clearly other potentially relevant code missing. For example, the try that goes with that last catch block. Also, it might help you to comment the beginning and end of your code blocks so that you can tell what's included in the if else statements.
Okay, I got the following code from the web, and it does work:
#Override
public void fileTransferRequest(FileTransferRequest request) {
// Check to see if the request should be accepted
final IncomingFileTransfer transfer = request.accept();
runnningFileTransfer = transfer;
try
{
final File file = new File("/Users/Akku/Downloads/in2" + request.getFileName());
transfer.recieveFile(file);
t = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
transfer.recieveFile(file);
System.out.println("DONE?");
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.run();
This code runs, and in the case of my 10MB test file it takes quite a lot of time. Sadly, I need to know if the transfer is finished or what the progress is. Funnily, I also got this part (which just sleeps and checks for progress) from the web, when I append it, the file transfer does not work anymore:
while(!transfer.isDone())
{
if(transfer.getStatus().equals(Status.error))
{
System.out.println("ERROR"+transfer.getError() + " EX: " + transfer.getException());
}
else
{
System.out.println("Written: "+transfer.getAmountWritten());
System.out.println("STATUS"+transfer.getStatus());
System.out.println("PROGRESS"+transfer.getProgress());
}
try
{
Thread.sleep(10000);
System.out.println("Waiting...");
}
catch (Exception e)
{
e.printStackTrace();
}
}
Any hint why this might happen? I guess it's something Java, because the above snippet works flawlessly.
The case that works should be throwing an exception. You call receive twice on the transfer object. The second call should produce an exception when it tries to create the file again. The second call, along with the thread creation is not necessary in this case as the transfer() method is asynchronous and has it's own internal threading.
It is hard to say why it doesn't work with your status check, since you don't show where you are doing this check. My suspicion is that you are calling it on the read thread and thus blocking the reading of new packets. Your loop checking for the transfer status should be running in its own thread.
I know this site isn't made for questions like this but I've been searching for the answer to this I haven't found anything and I need a confirmations.
I have a singleton class which is the centre of my program, in some situations I try to save its state, however it seems it doesn't save properly, and I don't see why because It's not the first time I do this, however It is the first time I try to save a singleton, so is it possible to save a singleton object?
Here are my loading and saving codes of this object
public void Loading(String name) {
ObjectInputStream is = null;
//ignore this variable
game_loaded = 1;
try {
is = new ObjectInputStream(new FileInputStream(name + ".dat"));
//Logica is the singleton class,
//logi is the name of the variable where it is
logi = (Logica) is.readObject();
} catch (FileNotFoundException e1) {
JOptionPane.showOptionDialog(frame, "Game Invalid", "Load",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, new String[] { "Ok" }, "Ok");
return;
} catch (IOException e1) {
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
JOptionPane.showOptionDialog(frame, "Game Loaded Sucessfully", "Load",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, new String[] { "Ok" }, "Ok");
}
Save:
public void saving(String nome){
ObjectOutputStream os = null;
try {
os = new ObjectOutputStream(new FileOutputStream(nome+".dat"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return;
} catch (IOException e) {
// TODO Auto-generated catch block
return;
}
try {
os.writeObject(Logica.getLogica(null));
} catch (IOException e) {
// TODO Auto-generated catch block
return;
}
JOptionPane.showOptionDialog(frame, "Game Saved sucessfully", "Load",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, new String[] { "Ok" }, "Ok");
if (os != null)
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
EDIT
Ok I may have explained corretcly, it doesn't give me any error loading, however it doesn't load the state I saved, it loads an new "Logica" as if I had created a new one
There's nothing about Singleton per se that says it can't be serialized; you can write incorrect serialization code for any class. It's not clear what's wrong, and I'm not willing to pore over your code to figure it out, but it should be possible to do.
You have an empty catch block for IOException. That's always a bad idea. You've swallowed the exception that might explain everything. Print the stack trace.
The situation you have described is not possible. Ergo you haven't described it correctly. Probably there is something wrong with your observations.
I strongly suspect an IOException or FileNotFoundException, despite your comment in another answer. You have posted code that ignores exceptions in at least four separate places. The presumption is overwhelming.
In fact your exception handling needs a lot of work. You aren't closing the file in case of exceptions for example. There are no finally blocks. You have multiple try/catch blocks where you should have one try and several catches.
Further questions along other lines of enquiry. Is the file being created? With non-zero length? Or else maybe the singleton class only has transient fields?