javanetbeansantsudogksudo

Get netbeans to run my project with sudo?


I am working on a project in netbeans that requires the running project to have root privileges.

I would like it so that each time I push "Run Project" (F6) my project is run as root, so with the equivalent of "gksudo javac Main", as it is has a GUI.

One option is to start netbeans with root privileges, easily done by editing the shortcut to "gksudo netbeans". But as I have multiple projects in netbeans this has meant that for each project I must run netbeans with root privileges, this is not what I want.

Another option, of course, is to simply run my project from the shell, but this is not ideal either.

I think this is possible by altering this projects build.xml file but am having trouble figuring out how.

After some research it would be seem that this is rather an Apache Ant question, I have access to build.xml which I can modify so I need to know how to get Ant to run my project with sudo/gksudo. However, I can't figure out how to do this or if it is possible.


Solution

  • Assuming this is a "Java SE" project (as opposed to, say, a web app or a Ruby program). First, turn off Compile on Save under Compiling in project properties.

    Second, add to build.xml:

    <target name="-init-macrodef-java">
        <macrodef name="java" uri="http://www.netbeans.org/ns/j2se-project/1">
            <attribute default="${main.class}" name="classname"/>
            <attribute default="${run.classpath}" name="classpath"/>
            <element name="customize" optional="true"/>
            <sequential>
                <exec executable="gksudo" failonerror="true">
                    <arg value="--"/>
                    <arg value="java"/>
                    <arg value="-classpath"/>
                    <arg path="@{classpath}"/>
                    <arg line="${run.jvmargs}"/>
                    <arg value="@{classname}"/>
                </exec>
            </sequential>
        </macrodef>
    </target>
    

    There are other things you can fine-tune but this should be enough to get you started.