obtaining Can’t connect to X11 window server using ‘:0’ as the value of the DISPLAY variable. with sudo or root

I was testing my application on Linux. The Java version is

[joseluisbz@centos ~]$ javac -version
javac 1.8.0_251
[joseluisbz@centos ~]$ java -version
}java version "1.8.0_251"
Java(TM) SE Runtime Environment (build 1.8.0_251-b08)
Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)
[joseluisbz@centos ~]$ 

Checking DISPLAY variable star

[joseluisbz@centos ~]$ printenv | grep DISPLAY
DISPLAY=:0
WAYLAND_DISPLAY=wayland-0
[joseluisbz@centos ~]$ 

[joseluisbz@centos ~]$ sudo printenv | grep DISPLAY
DISPLAY=:0
[joseluisbz@centos ~]$ 

[joseluisbz@centos ~]$ sudo -Hiu root env | grep DISPLAY
DISPLAY=:0
[joseluisbz@centos ~]$ sudo -Hiu joseluisbz env | grep DISPLAY
DISPLAY=:0
[joseluisbz@centos ~]$

hera the code :

  private static final String OS = System.getProperty("os.name").toLowerCase();

  public static Boolean isMacOS() {
    return (OS.contains("mac") || OS.contains("darwin"));
  }

  public static Boolean isLinux() {
    return (OS.contains("nix") || OS.contains("nux") || OS.contains("aix"));
  }

  public static Boolean isWindows() {
    return (OS.contains("windows"));
  }

  public static void main(String args[]) {
    System.out.println("");
    String osName = System.getProperty("os.name");
    String display = System.getenv("DISPLAY");
    System.out.println("System.getProperty(\"os.name\"):" + System.getProperty("os.name"));
    System.out.println("System.getenv(\"DISPLAY\"):" + System.getenv("DISPLAY"));
    
    Boolean headless = ("Linux".equals(osName) ||
                             "SunOS".equals(osName) ||
                             "FreeBSD".equals(osName) ||
                             "NetBSD".equals(osName) ||
                             "OpenBSD".equals(osName) ||
                             "AIX".equals(osName)) &&
                             (display == null || display.trim().isEmpty());
    System.out.println("headless:" + headless);
    System.out.println("");
    
    for (UIManager.LookAndFeelInfo lafInfo : UIManager.getInstalledLookAndFeels()) {
      System.out.println("lafInfo.getName():" + lafInfo.getName()
          + "\tinfo.getClassName():" + lafInfo.getClassName());
    }
    System.out.println("LookAndFeelInfo printed all\n");

    try {

//      UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
//      UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
//      UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");

//      javax.swing.UIManager.setLookAndFeel("com.apple.laf.AquaLookAndFeel");
//      javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
//      javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
      if (isMacOS()) {
        System.setProperty("apple.awt.brushMetalLook", "true");
        System.setProperty("apple.laf.useScreenMenuBar", "true");
        System.setProperty("apple.awt.application.name", "FlexibleFileFinder");
        System.setProperty("apple.awt.graphics.EnableQ2DX", "true");
      }

      System.out.println("OS:" + OS);
      if (isMacOS()) {
        UIManager.setLookAndFeel("com.apple.laf.AquaLookAndFeel");
      } else if (isLinux()) {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
      } else if (isWindows()) {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
      } else {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
      }
      System.out.println("UIManager.getLookAndFeel():" + UIManager.getLookAndFeel() + "\n");
    } catch (ClassNotFoundException | InstantiationException
        | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
      LOGGER.log(Level.SEVERE, null, ex);
    }

    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        RecursiveFolderAndFiles recursiveFolderAndFiles = new RecursiveFolderAndFiles();
        MainMenu mainMenu = new MainMenu(recursiveFolderAndFiles);
        MethodGUI.enableOSXFullscreen(recursiveFolderAndFiles);
        MethodGUI.requestToggleFullScreen(recursiveFolderAndFiles);
        recursiveFolderAndFiles.setJMenuBar(mainMenu.getMainMenuBar());
        recursiveFolderAndFiles.setVisible(true);
      }
    });
  }
}

I was running my Java app in CentOS 8.

[joseluisbz@centos ~]$ java -jar "/home/joseluisbz/Documents/FlexibleFileFinder-Full/dist/FlexibleFileFinder.jar"

System.getProperty("os.name"):Linux
System.getenv("DISPLAY")::0
headless:false

lafInfo.getName():Metal info.getClassName():javax.swing.plaf.metal.MetalLookAndFeel
lafInfo.getName():Nimbus    info.getClassName():javax.swing.plaf.nimbus.NimbusLookAndFeel
lafInfo.getName():CDE/Motif info.getClassName():com.sun.java.swing.plaf.motif.MotifLookAndFeel
lafInfo.getName():GTK+  info.getClassName():com.sun.java.swing.plaf.gtk.GTKLookAndFeel
LookAndFeelInfo printed all

OS:linux
UIManager.getLookAndFeel():[GTK look and feel - com.sun.java.swing.plaf.gtk.GTKLookAndFeel]

Running with sudo

[joseluisbz@centos ~]$ sudo java -jar "/home/joseluisbz/Documents/FlexibleFileFinder-Full/dist/FlexibleFileFinder.jar"

System.getProperty("os.name"):Linux
System.getenv("DISPLAY")::0
headless:false

No protocol specified
Exception in thread "main" java.awt.AWTError: Can't connect to X11 window server using ':0' as the value of the DISPLAY variable.
    at sun.awt.X11GraphicsEnvironment.initDisplay(Native Method)
    at sun.awt.X11GraphicsEnvironment.access$200(X11GraphicsEnvironment.java:65)
    at sun.awt.X11GraphicsEnvironment$1.run(X11GraphicsEnvironment.java:115)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.awt.X11GraphicsEnvironment.(X11GraphicsEnvironment.java:74)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at java.awt.GraphicsEnvironment.createGE(GraphicsEnvironment.java:103)
    at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:82)
    at sun.awt.X11.XToolkit.(XToolkit.java:132)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at java.awt.Toolkit$2.run(Toolkit.java:860)
    at java.awt.Toolkit$2.run(Toolkit.java:855)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.Toolkit.getDefaultToolkit(Toolkit.java:854)
    at sun.swing.SwingUtilities2.getSystemMnemonicKeyMask(SwingUtilities2.java:2031)
    at javax.swing.plaf.basic.BasicLookAndFeel.initComponentDefaults(BasicLookAndFeel.java:1158)
    at javax.swing.plaf.metal.MetalLookAndFeel.initComponentDefaults(MetalLookAndFeel.java:431)
    at javax.swing.plaf.basic.BasicLookAndFeel.getDefaults(BasicLookAndFeel.java:148)
    at javax.swing.plaf.metal.MetalLookAndFeel.getDefaults(MetalLookAndFeel.java:1577)
    at javax.swing.UIManager.setLookAndFeel(UIManager.java:539)
    at javax.swing.UIManager.setLookAndFeel(UIManager.java:579)
    at javax.swing.UIManager.initializeDefaultLAF(UIManager.java:1349)
    at javax.swing.UIManager.initialize(UIManager.java:1459)
    at javax.swing.UIManager.maybeInitialize(UIManager.java:1426)
    at javax.swing.UIManager.getInstalledLookAndFeels(UIManager.java:419)
    at org.bz.filefinder.MainClass.main(MainClass.java:56)
[joseluisbz@centos ~]$ 

The line 56 is

for (UIManager.LookAndFeelInfo lafInfo : UIManager.getInstalledLookAndFeels()) {

Trying again with sudo and -Djava.awt.headless=true

[joseluisbz@centos ~]$ sudo java -Djava.awt.headless=true -jar "/home/joseluisbz/Documents/FlexibleFileFinder-Full/dist/FlexibleFileFinder.jar"

System.getProperty("os.name"):Linux
System.getenv("DISPLAY")::0
headless:false

lafInfo.getName():Metal info.getClassName():javax.swing.plaf.metal.MetalLookAndFeel
lafInfo.getName():Nimbus    info.getClassName():javax.swing.plaf.nimbus.NimbusLookAndFeel
lafInfo.getName():CDE/Motif info.getClassName():com.sun.java.swing.plaf.motif.MotifLookAndFeel
lafInfo.getName():GTK+  info.getClassName():com.sun.java.swing.plaf.gtk.GTKLookAndFeel
LookAndFeelInfo printed all

OS:linux
Jul 04, 2020 5:08:17 PM org.bz.filefinder.MainClass main
SEVERE: null
javax.swing.UnsupportedLookAndFeelException: [GTK look and feel - com.sun.java.swing.plaf.gtk.GTKLookAndFeel] not supported on this platform
    at javax.swing.UIManager.setLookAndFeel(UIManager.java:526)
    at javax.swing.UIManager.setLookAndFeel(UIManager.java:583)
    at org.bz.filefinder.MainClass.main(MainClass.java:82)

Exception in thread "AWT-EventQueue-0" java.awt.HeadlessException
    at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:204)
    at java.awt.Window.(Window.java:536)
    at java.awt.Frame.(Frame.java:420)
    at java.awt.Frame.(Frame.java:385)
    at javax.swing.JFrame.(JFrame.java:189)
    at org.bz.filefinder.RecursiveFolderAndFiles.(RecursiveFolderAndFiles.java:43)
    at org.bz.filefinder.MainClass$1.run(MainClass.java:97)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
[joseluisbz@centos ~]$ 

The line 82 is

UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");

I was testing with

UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");

and they failed vitamin a well. !

Why works for non root or sudo user, but it fails with sudo or root?
note :
code of java.awt.GraphicsEnvironment

static void checkHeadless() throws HeadlessException {
    if (isHeadless()) { //LINE 203!!!
        throw new HeadlessException();
    }
}


public static boolean isHeadless() {
    return getHeadlessProperty();
}


private static boolean getHeadlessProperty() {
    if (headless == null) {
        AccessController.doPrivileged((PrivilegedAction) () -> {
            String nm = System.getProperty("java.awt.headless");

            if (nm == null) {
                /* No need to ask for DISPLAY when run in a browser */
                if (System.getProperty("javaplugin.version") != null) {
                    headless = defaultHeadless = Boolean.FALSE;
                } else {
                    String osName = System.getProperty("os.name");
                    if (osName.contains("OS X") && "sun.awt.HToolkit".equals(
                            System.getProperty("awt.toolkit")))
                    {
                        headless = defaultHeadless = Boolean.TRUE;
                    } else {
                        final String display = System.getenv("DISPLAY");
                        headless = defaultHeadless =
                            ("Linux".equals(osName) ||
                             "SunOS".equals(osName) ||
                             "FreeBSD".equals(osName) ||
                             "NetBSD".equals(osName) ||
                             "OpenBSD".equals(osName) ||
                             "AIX".equals(osName)) &&
                             (display == null || display.trim().isEmpty());
                    }
                }
            } else {
                headless = Boolean.valueOf(nm);
            }
            return null;
        });
    }
    return headless;
}

NOTE 1 :

[joseluisbz@centos ~]$ sudo xterm
[sudo] password for joseluisbz: 
sudo: xterm: command not found
[joseluisbz@centos ~]$ xterm
bash: xterm: command not found...
Install package 'xterm' to provide command 'xterm'? [N/y] y


 * Waiting in queue... 
 * Loading list of packages.... 
The following packages have to be installed:
 xorg-x11-fonts-misc-7.5-19.el8.noarch  misc bitmap fonts for the X Window System
 xterm-331-1.el8.x86_64 Terminal emulator for the X Window System
 xterm-resize-331-1.el8.x86_64  Set environment and terminal settings to current window size
Proceed with changes? [N/y] y


 * Waiting in queue... 
 * Waiting for authentication... 
 * Waiting in queue... 
 * Downloading packages... 
 * Requesting data... 
 * Testing changes... 
 * Installing packages... 

[joseluisbz@centos ~]$

NOTE 2 # candle /etc/X11/ & & Xorg -configure # X -config -retro /root/xorg.conf.new # X -config -retro /etc/X11/xorg.conf # startx
Working with root exploiter.

[joseluisbz@centos ~]$ sudo startx
xauth:  file /root/.serverauth.3620 does not exist


X.Org X Server 1.20.6
X Protocol Version 11, Revision 0
Build Operating System:  4.19.34-300.el7.x86_64 
Current Operating System: Linux centos.joseluisbz 4.18.0-193.6.3.el8_2.x86_64 #1 SMP Wed Jun 10 11:09:32 UTC 2020 x86_64
Kernel command line: BOOT_IMAGE=(hd1,gpt7)/vmlinuz-4.18.0-193.6.3.el8_2.x86_64 root=UUID=8e22004f-7639-4530-a2db-df80df04aa6d ro crashkernel=auto resume=UUID=8c61ca21-ec17-4aed-b695-c83c373f7ff0 rhgb quiet
Build Date: 24 April 2020  02:49:29AM
Build ID: xorg-x11-server 1.20.6-3.el8 
Current version of pixman: 0.38.4
    Before reporting problems, check http://wiki.x.org
    to make sure that you have the latest version.
Markers: (--) probed, (**) from config file, (==) default setting,
    (++) from command line, (!!) notice, (II) informational,
    (WW) warning, (EE) error, (NI) not implemented, (??) unknown.
(==) Log file: "/var/log/Xorg.2.log", Time: Sat Jul  4 18:03:05 2020
(==) Using config directory: "/etc/X11/xorg.conf.d"
(==) Using system config directory "/usr/share/X11/xorg.conf.d"
(II) modeset(0): Initializing kms color map for depth 24, 8 bpc.
The XKEYBOARD keymap compiler (xkbcomp) reports:
> Internal error:   Could not resolve keysym XF86MonBrightnessCycle
> Internal error:   Could not resolve keysym XF86RotationLockToggle
Errors from xkbcomp are not fatal to the X server
The XKEYBOARD keymap compiler (xkbcomp) reports:
> Internal error:   Could not resolve keysym XF86MonBrightnessCycle
> Internal error:   Could not resolve keysym XF86RotationLockToggle
Errors from xkbcomp are not fatal to the X server
Failed to import environment: Process org.freedesktop.systemd1 exited with status 1
The XKEYBOARD keymap compiler (xkbcomp) reports:
> Internal error:   Could not resolve keysym XF86MonBrightnessCycle
> Internal error:   Could not resolve keysym XF86RotationLockToggle
Errors from xkbcomp are not fatal to the X server
xinit: connection to X server lost

waiting for X server to shut down (II) Server terminated successfully (0). Closing log file.

[joseluisbz@centos ~]$ 

When beginning is logged

[root@centos ~]# whoami
root
[root@centos ~]# pwd
/root
[root@centos ~]# java -jar "/home/joseluisbz/Documents/FlexibleFileFinder-Full/dist/FlexibleFileFinder.jar"

System.getProperty("os.name"):Linux
System.getenv("DISPLAY")::2
System.getProperty("java.awt.headless"):null
headless:false

lafInfo.getName():Metal info.getClassName():javax.swing.plaf.metal.MetalLookAndFeel
lafInfo.getName():Nimbus    info.getClassName():javax.swing.plaf.nimbus.NimbusLookAndFeel
lafInfo.getName():CDE/Motif info.getClassName():com.sun.java.swing.plaf.motif.MotifLookAndFeel
lafInfo.getName():GTK+  info.getClassName():com.sun.java.swing.plaf.gtk.GTKLookAndFeel
LookAndFeelInfo printed all

OS:linux
UIManager.getLookAndFeel():[GTK look and feel - com.sun.java.swing.plaf.gtk.GTKLookAndFeel]

JFrame.class.isAssignableFrom(RecursiveFolderAndFiles.class):true
RecursiveFolderAndFiles.class.isAssignableFrom(OneSearch.class):false
RulerPanel.class.isAssignableFrom(OneSearch.class):false
RulerPanel.class.isAssignableFrom(JPanel.class):false
JPanel.class.isAssignableFrom(RulerPanel.class):true
Jul 04, 2020 6:41:10 PM org.bz.filefinder.RecursiveFolderAndFiles 
INFO: System.getProperty("user.dir"): /root
Jul 04, 2020 6:41:10 PM org.bz.filefinder.RecursiveFolderAndFiles 
INFO: System.getProperty("user.home"): /root

NOTE 3

[joseluisbz@centos ~]$ sudo xterm
No protocol specified
Warning: This program is an suid-root program or is being run by the root user.
The full text of the error or warning message cannot be safely formatted
in this environment. You may get a more descriptive message by running the
program as a non-root user or by removing the suid bit on the executable.
xterm: Xt error: Can't open display: %s
[joseluisbz@centos ~]$ 

NOTE 4:

sudo dnf install xterm
sudo dnf install xorg-x11-server-utils
sudo dnf install xorg-x11-apps
sudo dnf groupinstall "legacy-x"
informant : https://thefartiste.com
Category : Tech

About admin

I am the owner of the website thefartiste.com, my purpose is to bring all the most useful information to users.

Check Also

articlewriting1

Manage participants in a zoom meeting webinar

Call the people who attend the meet as follows Alternate host host Who scheduled the …

Leave a Reply

Your email address will not be published.