I want to create files and directories from my java code with required unix permissions. The unix permissions are taken as input from user and are given as octal number(For e.g. 02775). I found the java.nio.file.attribute.PosixFilePermission to be quite handy however it doesn't allow setting the setgid (+s) bit. Following code throws java.lang.IllegalArgumentException: Invalid mode
Set<PosixFilePermission> posixPermissions = PosixFilePermissions.fromString("rwxrwsr-x");
Files.setPosixFilePermissions(someDir, posixPermissions);
Also I want to avoid manually converting the octal number to posix permission string(e.g: "rwxrw-r-x"). Is there any way to do this in java apart from triggering a sub-process with chmod command ?
Related
i have following code i want command line result save in my textfile also how do this. please help
#echo off
set JAVA_HOME=C:\jdk1.5.0_05
set CLI_HOME=c:\projects\utds\applications\cli
set CLI_LIB=%CLI_HOME%\lib
set CLASSPATH=%CLI_LIB%\commons-logging.jar;%CLI_LIB%\commons-logging-api.jar
set CLASSPATH=%CLASSPATH%;%CLI_LIB%\spring.jar;%CLI_LIB%\spring-core.jar;%CLI_LIB%\spring-support.jar;%CLI_LIB%\spring-remoting.jar
set CLASSPATH=%CLASSPATH%;%CLI_LIB%\utds-infra.jar;%CLI_HOME%\src\conf\spring;%CLI_HOME%\src\conf
set CLASSPATH=%CLASSPATH%;%CLI_LIB%\aopalliance.jar
set CLASSPATH=%CLASSPATH%;%CLI_HOME%\dist\cli.jar;%JAVA_HOME%\jre\lib\ext\comm.jar
set path=%JAVA_HOME%\bin;%path%
java -Dport=COM3 -DbaudRate=19200 -Dparser=panasonicCliParser -DappContext=applicationContext-service.xml com.utds.cli.service.comm.CallerIdListener
I would pipe the output of the batch command into a text file by running the following command in the command prompt:
myBatchFile.bat > output.log
Okay it looks like you're trying to put the output of the program into a text file. If that is the case, in your code just add:
java > log.txt
In my opinion, you should better use your logging library. I can see from the script here above that your applications uses Apache's commons-logging and the output shows it is clearly used.
This library is a wrapper indeed. It can use Log4J or JDK's logging library under the hood.
Of course, this requires much more learning and struggling with configuration files but the advantage for you is that you could (following the implementation you chose):
Filter logs following their gravity (debug < info < warning < error...) and/or the classes emitting them. Some libraries are quite verbose .
Create rolling log files : once the the log file reaches a certain size, a new log file can be created and the old one is backup-ed. (It can be possible to limit the number of backups...).
Create a log file per day
Log into databases if you ever need it...
....
add only >mylog.txt Thanks All
java -Dport=COM3 -DbaudRate=19200 -Dparser=panasonicCliParser -DappContext=applicationContext-service.xml com.utds.cli.service.comm.CallerIdListener> mylogs.txt
My application has multiple users and 1 superuser. I am trying to write and store a file in Linux through Java code but i get permission denied error. I used the following code:
Process process = Runtime.getRuntime().exec("/usr/bin/tiff2pdf -o /tmp/tiff_dir/temp.pdf /tmp/tiff_dir/image.tiff");
int returnCode = process.waitFor();
I get following error:
java.io.FileNotFoundException: image.tiff (Permission denied)
From my analysis, it seems that because the user does not have root permissions, i am getting this error. What is the solution to this?
You shouldn't run a command like that as a super user because it poses a security risk (i.e. if someone gained control of your java program, then they have the keys to the kingdom). Instead, you should run with lower permissions.
It looks like the issue is with access to image.tiff not with tiff2pdf. Check the owner and permissions of image.tiff.
Firstly, these two lines will not produce a java.io.FileNotFoundException: image.tiff (Permission denied):
Process process = Runtime.getRuntime().exec("/usr/bin/tiff2pdf -o temp.pdf image.tiff");
int returnCode = process.waitFor();
If for some reason, the command fail, it will return a non-zero return code will produce some output on the process's standard error (that's the convention). You can get that standard error from process.getErrorStream() (it might be worth having a look at the standard output too, just in case). If there's an issue with the file not being found there, it will not throw a FileNotFoundException like this, since Java cannot understand the expected output from your command.
EDIT, following your comment:
It was thrown from this point only and value of returnCode was 1. Also everything worked fine once i manually changed the file permissions from a root user.
That's just not possible. If your application throws an exception at either of these two lines, it will exit the normal control flow: you will not be able to read the returnCode at all.
Secondly, your should run your exec command with each argument in a String[] instead of having it all in one line, this should prevent quotation problems if file names have spaces for example.
I would also suggest using absolute paths in your command, to make sure you're working in the directories you expect. (*EDIT: * Now that you're using absolute paths, make sure your user has rwx permissions on /tmp/tiff_dir .)
To answer your question more directly, you can certainly run sudo with Runtime.exec(new String[] {"/usr/bin/sudo", ... the rest of your command ... }, but this is a bad idea, for security reasons. You'd also need to change the sudoers file to allow it without password, or find a way to pass in a password, either on the command line (definitely a security risk!) or by passing it to the input stream manually, somehow.)
Try this :
File file = new File("/opt/image.tiff");
Runtime runtime = Runtime.getRuntime();
runtime.exec(new String[] { "/bin/chmod", "777",file.getPath()});
This will execute full permission on the file.
I've got a problem with JacORB 3.2 as it seems that it doesn't read the orb.properties file, and especially the ORBInitRef.NameService property.
As stated in the documentation on chapter 3.1, JacORB automatically searches for the orb.properties file in three locations: the "java.home"/lib directory, the "user.home" directory and inside the classpath.
This is the evidence that I'm not totally drunk:
Java command:
System.out.println(System.getProperty("java.home"));
System.out.println(System.getProperty("user.home"));
Output:
/usr/lib/jvm/jdk1.7.0/jre
/home/emanuele
Bash command:
ls /usr/lib/jvm/jdk1.7.0/jre/lib | grep orb.properties ; ls /home/emanuele | grep orb.properties
Output:
jacorb.properties
orb.properties
jacorb.properties
orb.properties
These four .properties file are exactly the same. Please have a look at the URI of the file that contains the reference (IOR) of the NameService:
ORBInitRef.NameService=file:/tmp/CORBA/NS_Ref
The problem is that, when I try to launch the NameService without any parameter (ns) I got these error messages:
giu 05, 2013 9:56:51 PM org.jacorb.naming.NameServer main
SEVERE: unexpected exception
java.io.FileNotFoundException: c:/NS_Ref (No such file or directory)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:104)
at org.jacorb.naming.NameServer.main(NameServer.java:320)
java.lang.RuntimeException: c:/NS_Ref (No such file or directory)
at org.jacorb.naming.NameServer.main(NameServer.java:335)
Of course, if I explicitely pass the URI through console, everything goes fine
ns -Djacorb.naming.ior_filename=/tmp/CORBA/NS_Ref
The very strange thing is that, after the NameService is running, EVERY OTHER OBJECT can correctly and automatically resolve the initial reference of the NameService.
NamingContextExt nc = NamingContextExtHelper.narrow(orb.resolve_initial_references("NameService"));
The previous Java code returns a valid object. That does not make any sense for me.
And why does the NameService try to write its IOR inside a random file like C:\NS_Ref while I'm on Linux?
Any idea?
I thing you mixed up some different things in your question.
The location of the NS's IOR
The ability to read and use this IOR by other programs
First. Starting the NamingService is not affected by option ORBInitRef.NameService or any related commandline option. If you want the NamingService to drop it's IOR in a file, use
# The file where the name server drops its IOR
jacorb.naming.ior_filename=file:///tmp/CORBA/NS_Ref
as you already did. If this behaves different when using this as cmdline option, see 2.
Second. JacORB its config files are not OS specific - there is a mix of both Linux and Windows style. Don't rely on that.
Your call to ns will call the jaco script in JacORBs bin directory. Activate the verbosity stuff at the end of the file, then start ns again and see which jre and jacorb.home are really used. Look for configs. Remove ALL other configs you do not need.
Retry.
This
ns -Djacorb.naming.ior_filename=/tmp/CORBA/NS_Ref
looks fine, but shouldn't that
ORBInitRef.NameService=file:/tmp/CORBA/NS_Ref
read file:///tmp/CORBA/NS_Ref?
And this
c:/NS_Ref
is strange on Linux; that looks very windowzy to me; are you sure you've not mixed Win and Linux config files?
I need to set the permission to read a file to a specific user of the operating system, how can I do this in Java?
Edit:
The file will be created with permissions just to the user running the application, than it needs to set read permission to a single user, other users will not have the permissions to read the file.
Use the methods setExecutable, setReadable, and setWritable in java.io.File. You can use these to change any permission bit of a file you own. Direct link: http://download.oracle.com/javase/6/docs/api/java/io/File.html#setReadable%28boolean%29.
Testing this on MacOSX revels that only the user read value is changed. When program
import java.io.File;
public class Test
{
public static void main(String[] args)
{
File f = new File("test.txt");
f.setReadable(true);
}
}
the folloiwng happens.
$ touch test.txt
$ chmod 000 test.txt
$ javac Test.java
$ java Test
$ ls -l test.txt
-r-------- 1 morrison staff 0 Jun 7 13:28 test.txt
If you're targetting Windows Vista/7, build your JAR as EXE and embed a manifest requesting for Admin rights.
If it's just an I/O problem, use the default File methods setReadable, setWritable, setExecutable :)
In regards to making the permissions for a single user, start with using ncmathsadist's code to add read permissions, then change the owner of the file to whoever needs access.
I found in the Ant source code they use for the change-owner task. For unix this can be found in the Ant source tree at org/apache/tools/ant/taskdefs/optional/unix/Chown.java. You might be able to include this and use it as an API call to change the user programmatically.
if you want to change file permissions on old Java versions like Java 5, you can use this:
Runtime.getRuntime().exec("chmod 000 " + PATH + fileName);
on windows you'll have to replace chmod with the appropriate CACLS.exe command syntax
i try to check the permission granted to a directory in linux, i mean i have a directory with permission 755
berty#berty-laptop:~$ ls -l / |grep directory
drwxr-xr-x 3 root root 4096 2011-01-10 12:33 directory
how can i read that permission with java? I've tried using FilePermission but though i have a directory with all the permissions (777) the FilePermission class always returns an exception
java.security.AccessControlException: Access denied (java.io.FilePermission /home/directory read)
at java.security.AccessController.checkPermission(AccessController.java:103)
at com.snippets.Check4DirectoryPermission.checker(Check4DirectoryPermission.java:50)
at com.snippets.Check4DirectoryPermission.main(Check4DirectoryPermission.java:70)
is there another way to do this?
java.io.File.canRead(), where the file instance is the one representing the dir
Returns:
true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise
I think you made a mistake: The ls command shows the existence of /directory, but the Java code complaints about /home/directory - which does not exist unless you have a user called directory.
From your stack trace, I assume that you are creating a FilePermission object yourself and hand it over to AccessController.checkPermission(). This is not how it is used - the FilePermission class does NOT represent the filesystem permissions and does NOT check them. It is used by Java's SecurityManager only, e.g. it looks whether the policy file contains rules that allow the application to access the file. Whether the local file system supports permissions or not is not its concern.
As Bozho suggest, you create a java.io.File() object and use the canXXX() methods to check whether you can access the folder or file.
If you need more detailed information about filesystem-level permissions on a file, you need to wait for Java 7. See the Java NIO.2 Tutorial especially the java.nio.file.attributepackage.