How to change permissions to file with Runtime.getRuntime().exec - android-ndk

I am writing code on android and I need change permissions of some files, I have installed Busybox to have many commands, but when executing code does nothing.
Process p = Runtime.getRuntime().exec("chmod 777 /data/app/XXX");
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}

private boolean isSu() throws IOException, InterruptedException {
Process p;
try {
// Preform su to get root privledges
p = Runtime.getRuntime().exec("su");
// Attempt to write a file to a root-only
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes("echo \"Do I have root?\" >/system/sd/temporary.txt\n");
// Close the terminal
os.writeBytes("exit\n");
os.flush();
try {
p.waitFor();
if (p.exitValue() != 255) {
toastMessage("root");
return true;
} else {
toastMessage("not root");
}
} catch (InterruptedException e) {
toastMessage("not root");
}
} catch (IOException e) {
toastMessage("not root");
}
return false;
}

Related

FileOutputStream prints weird latin characters at the end in java

when I try copy a java file to txt file ,It works fine but it prints some additional lating character at end of output file(Note: there is no such latin character in input file).
please refer the code
import java.io.*;
public class File1 {
public static void main(String[] args) throws IOException {
FileInputStream fin = null;
FileOutputStream fout = null;
int c;
String input = "F:\\Java Intellij\\src\\testprint.java";
String output = "F:\\Java Intellij\\src\\new23.txt";
File infile = new File(input);
File outfile = new File(output);
infile.createNewFile();
outfile.createNewFile();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
fin = new FileInputStream(infile);
fout = new FileOutputStream(outfile);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("enter :");
if (fin != null && fout != null)
try {
do {
c = fin.read();
fout.write(c);
} while (c != -1);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fin != null) {
fin.close();
}
if (fout != null) {
fout.close();
}
}
}
}
can anyone shred some light on the question, why this happens??? and suggest a remedy

This program is not being stop after pressing c

This program is not being stop after pressing c.
This program should stop after pressing c but it is not.
I am searching .dll file in given directory. After that I am searching given method name and property
by user.
class Program
{
static void Main(string[] args)
{
char choice;
Console.WriteLine(AppConst.Messages.UserChoice);
Console.WriteLine(AppConst.Messages.Star);
choice = GetResponse();
string name = string.Empty;
if (choice == 'M')
{
Console.WriteLine(AppConst.Messages.InputMethodName);
name = Console.ReadLine();
}
if (choice == 'P')
{
Console.WriteLine(AppConst.Messages.InputPropertyName);
name = Console.ReadLine();
}
CancellationTokenSource cancellationToken = new CancellationTokenSource();
// Use ParallelOptions instance to store the CancellationToken.
ParallelOptions parallelOption = new ParallelOptions();
parallelOption.CancellationToken = cancellationToken.Token;
parallelOption.MaxDegreeOfParallelism = 10;
Console.WriteLine(AppConst.Messages.StartSearchingMessage);
Console.ReadKey();
//Console.WriteLine();
// Run a task so that we can cancel another thread.
Task.Factory.StartNew(() =>
{
while (Console.ReadKey().Key != ConsoleKey.C) ;
cancellationToken.Cancel();
});
int countClass = 0;
string[] files = Directory.GetFiles(#"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5", "*.dll");
try
{
Parallel.ForEach(files, parallelOption, (file) =>
{
parallelOption.CancellationToken.ThrowIfCancellationRequested();
try
{
var asm = Assembly.LoadFile(file);
foreach (var type in asm.GetTypes())
{
if (choice == 'M')
{
try
{
MethodInfo methodInfo = type.GetMethod(name);
if (methodInfo != null)
{
countClass++;
Console.WriteLine(AppConst.Messages.Star);
Console.WriteLine(AppConst.Messages.
PrintFileName, Path.GetFileName(file));
Console.WriteLine(AppConst.Messages.
PrintCalssName, type.Name);
}
}
catch (AmbiguousMatchException ex)
{
Console.WriteLine("\n{0}\n{1}", ex.GetType().
FullName, ex.Message);
}
}
if (choice == 'P')
{
try
{
PropertyInfo propertyInfo = type.GetProperty(name);
if (propertyInfo != null)
{
countClass++;
Console.WriteLine(AppConst.Messages.Star);
Console.WriteLine(AppConst.Messages.
PrintFileName, Path.GetFileName(file));
Console.WriteLine(AppConst.Messages.
PrintCalssName, type.Name);
}
}
catch (NullReferenceException e)
{
Console.WriteLine(AppConst.Messages.
PropertyNotExist + e.Message);
}
}
}
}
catch (BadImageFormatException e)
{
Console.WriteLine(AppConst.Messages.UnableTOLoad,
Path.GetFileName(file));
Console.WriteLine(e.Message.Substring(0, e.Message.IndexOf(".") + 1));
}
//parallelOption.CancellationToken.ThrowIfCancellationRequested();
});
}
catch (OperationCanceledException e)
{
Console.WriteLine(e.Message);
}
catch (Exception e)
{
Console.WriteLine();
Console.ReadLine();
}
if (countClass == 0)
{
Console.WriteLine(AppConst.Messages.NotExistMessage);
}
Console.ReadKey();
}
private static char GetResponse()
{
char response;
while (true)
{
//Checking for entered input is M or P.
if (Char.TryParse(Console.ReadLine().ToUpper(), out response)
&& (response == 'M' || response == 'P'))
break;
//AppConst.Messages.InvalidChoice is string message.
Console.WriteLine(AppConst.Messages.InvalidChoice);
}
return response;
}
}
It seems to me that the main problem in your code is that you only check for cancellation once, right when a thread starts. If you want an exception, or any other type of cancellation for that matter, you need to actually check the CancellationToken somehow while you're running the task.
It looks to me as though you would want to put the parallelOption.CancellationToken.ThrowIfCancellationRequested(); line in the loop block for the foreach (var type in asm.GetTypes()) loop, probably as the first statement in the block.
Here is a simple example demonstrating correct use of CancellationToken in a way that is similar to what you seem to want:
CancellationTokenSource tokenSource = new CancellationTokenSource();
Thread thread = new Thread(() =>
{
while (Console.ReadKey().Key != ConsoleKey.C) { }
tokenSource.Cancel();
});
thread.IsBackground = true;
thread.Start();
TimeSpan[] timeSpans = new TimeSpan[10];
int completedCount = 0;
timeSpans[0] = TimeSpan.FromSeconds(4);
for (int i = 1; i < timeSpans.Length; i++)
{
timeSpans[i] = timeSpans[i - 1] + TimeSpan.FromSeconds(2);
}
try
{
Parallel.ForEach(timeSpans, timeSpan =>
{
Stopwatch sw = Stopwatch.StartNew();
while (sw.Elapsed < timeSpan)
{
Thread.Sleep(100);
tokenSource.Token.ThrowIfCancellationRequested();
}
Console.WriteLine("Completed {0} threads (thread time: {1})",
Interlocked.Increment(ref completedCount), sw.Elapsed);
});
}
catch (AggregateException e)
{
Console.WriteLine("Exception: " + e);
}
Console.WriteLine("All threads completed");
Note that the exception actually seen in the main thread is an AggregateException. This contains the individual exception information for each thread that was cancelled.

Reading a file in Blackberry

I am trying to read content from file in blackberry and i read the file content to result object and when i am trying to print the result object it gives error and the file is in res folder,and this is code that i got problem
private String readTextFile(String fName) {
String result = null;
FileConnection fconn = null;
DataInputStream is = null;
try {
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
is = fconn.openDataInputStream();
byte[] data = IOUtilities.streamToBytes(is);
result = new String(data);
System.out.println("result data is ...... "+result);
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (null != is)
is.close();
if (null != fconn)
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
return result;
}
what is fName here ?
The file name or the path could cause similar problem.

Not able to get DirContext ctx using Spring Ldap

Hi i am using Spring ldap , after execution below program It display I am here only and after that nothing is happening, program is in continue execution mode.
public class SimpleLDAPClient {
public static void main(String[] args) {
Hashtable env = new Hashtable();
System.out.println("I am here");
String principal = "uid="+"a502455"+", ou=People, o=ao, dc=com";
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "MYURL");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, principal);
env.put(Context.SECURITY_CREDENTIALS,"PASSWORD");
DirContext ctx = null;
NamingEnumeration results = null;
try {
ctx = new InitialDirContext(env);
System.out.println(" Context" + ctx);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
results = ctx.search("", "(objectclass=aoPerson)", controls);
while (results.hasMore()) {
SearchResult searchResult = (SearchResult) results.next();
Attributes attributes = searchResult.getAttributes();
Attribute attr = attributes.get("cn");
String cn = (String) attr.get();
System.out.println(" Person Common Name = " + cn);
}
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
if (results != null) {
try {
results.close();
} catch (Exception e) {
}
}
if (ctx != null) {
try {
ctx.close();
} catch (Exception e) {
}
}
}
}
}
Try fixing the below lines, i removed "ao" and it works fine.
results = ctx.search("", "(objectclass=Person)", controls);
You need to give search base as well
env.put(Context.PROVIDER_URL, "ldap://xx:389/DC=test,DC=enterprise,DC=xx,DC=com");
Refer this link as well http://www.adamretter.org.uk/blog/entries/LDAPTest.java

how to store the data in a file in j2me..?

please can anyone tell me how to store the RMS data to file and how to modify it?
You can use this code for write the data in a file.
private void writeTextFile(String fName, String text) {
DataOutputStream dos = null;
FileConnection fconn = null;
try {
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
if (!fconn.exists())
fconn.create();
dos = fconn.openDataOutputStream();
dos.write(text.getBytes());
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (dos != null)
dos.close();
if (fconn != null)
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}

Resources