How can I write System preferences with Java? Can I invoke UAC? - java

How can I write system preferences with Java, using Preferences.systemRoot()?
I tried with:
Preferences preferences = Preferences.systemRoot();
preferences.put("/myapplication/databasepath", pathToDatabase);
But I got this error message:
2010-maj-29 19:02:50 java.util.prefs.WindowsPreferences openKey
VARNING: Could not open windows registry node Software\JavaSoft\Prefs at root 0x80000002. Windows RegOpenKey(...) returned error code 5.
Exception in thread "AWT-EventQueue-0" java.lang.SecurityException: Could not open windows registry node Software\JavaSoft\Prefs at root 0x80000002: Access denied
at java.util.prefs.WindowsPreferences.openKey(Unknown Source)
at java.util.prefs.WindowsPreferences.openKey(Unknown Source)
at java.util.prefs.WindowsPreferences.openKey(Unknown Source)
at java.util.prefs.WindowsPreferences.putSpi(Unknown Source)
at java.util.prefs.AbstractPreferences.put(Unknown Source)
at org.example.install.Setup$2.actionPerformed(Setup.java:43)
I would like to do this, because I want to install an embedded JavaDB database, and let multiple users on the computer to use the same database with the application.
How to solve this? Can I invoke UAC and do this as Administrator from Java? And if I log in as Administrator when writing, can I read the values with my Java application if I'm logged in as a User?

You cannot write to any arbitrary registry location from java preferences - all preferences are stored under a subkey Software\Javasoft\Prefs. With user preferences mapping to the HKEY_CURRENT_USER hive, and system mapping to the HKEY_LOCAL_MACHINE hive.
To write to the registry, you could use the windows "REG" command line tool. This page details other ways of modifying the registry. including use of .reg files.
I had the same need - to write to the registry from java - I solved it by writing a small .NET command line utility to do it.
The Sun Windows JDK does ship with generic code to write to arbitrary portions of the registry (WindowsPreferences), but it's not public. This article describes how to access this class using reflection.

You can't edit Preferences.systemRoot() if User Account Control is turned on. Seems like Microsoft went and broke it. There is a workaround here, but it's not straightforward.

So I had this same issue, so I opened an issue with Oracle:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7043176
I was able to work around it myself, by writing a custom implementation of AbstractPreferences and a corresponding PreferencesFactory. What I did was on Windows have the system preferences write to the application data directory defined in the registry by:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Common AppData
I used Runtime.getRuntime().exec("reg query \""+key+ "\" /v \""+value+"\"") to get that (works even with UAC turned on).
That evaluates to "C:\ProgramData" on Windows 7 and "C:\Documents and Settings\All Users\Application Data" on XP. I added a subdirectory called "JavaPreferences" and wrote an implementation that uses a properties file as the backend.
As a side note, I had a similar issue with system preferences on Linux because the installer for the JRE was not run by root so I didn't have access to "/etc/.java". A ended up picking another custom directory and granting permissions for that.

Related

How do I create a symlink

On an NTFS volume on Windows 10 Version 1803 build 17134.523 with Developer Mode enabled, I have a file myfile. I can make symbolic links to this file with mklink. However, if I call Files.createSymbolicLink on java jre 1.8.0_201, if throws:
java.nio.file.FileSystemException: linkname: A required privilege is not held by the client.
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.createSymbolicLink(Unknown Source)
at java.nio.file.Files.createSymbolicLink(Unknown Source)
at CreateLinks.main(CreateLinks.java:15)
The same works without problems on the Windows Subsystem for Linux (WSL) with jre 1.8.0_191-8u191-b12-0ubuntu0.18.10.1-b12
How can I make this work on windows without going into WSL? And where is this exception thrown exactly?
Creating symbolic links requires SeCreateSymbolicLinkPrivilege, unless the system is in developer mode and WinAPI CreateSymbolicLink is called with the flag SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE (*). CMD's mklink command uses this flag in Windows 10. Apparently Java JRE version 1.8.0_201 does not.
As to WSL, it inherits the security context from which it is run. If run from a logon that has SeCreateSymbolicLinkPrivilege, recent versions of WSL will create normal Windows symlinks on a drvfs (e.g. NTFS) volume. Otherwise WSL uses a custom symlink type, which is based on an IO_REPARSE_TAG_LX_SYMLINK (0xA000001D) reparse point instead of the normal IO_REPARSE_TAG_SYMLINK (0xA000000C) reparse point. You can query the type of reparse point via the command fsutil reparsepoint query <filename>.
(*) The docs say "[s]pecify this flag to allow creation of symbolic links when the process is not elevated". More precisely, this flag allows creating symlinks without SeCreateSymbolicLinkPrivilege, which is only related to being "elevated" with the default system settings. Personally, I grant this privilege to the "Authenticated Users" group, in which case creating symlinks doesn't require elevating to full admin access.
it's not related to your Java, it's just related to your os. please see the following link:
How to create Soft symbolic Link using java.nio.Files
Win10 with UAC turned off - I had to set Local Policies > Security Options > User Account Control: Run all administrators in Admin Approval Mode = Disabled - otherwise - same FileSystemException: A required privilege is not held by the client

Install DB2 Connect under Linux - error occured: "AWT-EventQueue-0" java.lang.NullPointerException

I am trying to install db2 connect (Version 10.1) under Linux (Debian 9.5). After calling db2setup the user interface freezes at point 5 (language selection) of the menu. The problem occurs only with the installation type CUSTOM.
This error message is triggered in the /tmp/db2setup.err log when the Next button is pressed.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.ibm.db2.install.util.MessageHandler.handleMessage(Unknown Source)
at com.ibm.db2.install.util.MessageHandler.handleMessage(Unknown Source)
at com.ibm.db2.install.util.MessageHandler.handleError(Unknown Source)
at com.ibm.db2.install.gui.panels.FeaturePage.preValidate(Unknown Source)
at com.ibm.db2.install.gui.wizard.SetupWizardPanel.preValidatePage(Unknown Source)
at com.ibm.db2.install.gui.wizard.SetupWizardPanel.actionPerformed(Unknown Source)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2029)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2352)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:413)
at javax.swing.JToggleButton$ToggleButtonModel.setPressed(JToggleButton.java:319)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:263)
at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:300)
at java.awt.Component.processMouseEvent(Component.java:6515)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3332)
at com.ibm.db2.tools.common.sg.CustomToggleButton.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Component.java:6280)
at java.awt.Container.processEvent(Container.java:2240)
at java.awt.Component.dispatchEventImpl(Component.java:4871)
at java.awt.Container.dispatchEventImpl(Container.java:2298)
at java.awt.Component.dispatchEvent(Component.java:4697)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4843)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4503)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4433)
at java.awt.Container.dispatchEventImpl(Container.java:2284)
at java.awt.Window.dispatchEventImpl(Window.java:2724)
at java.awt.Component.dispatchEvent(Component.java:4697)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:718)
at java.awt.EventQueue.access$000(EventQueue.java:112)
at java.awt.EventQueue$3.run(EventQueue.java:677)
at java.awt.EventQueue$3.run(EventQueue.java:675)
at java.security.AccessController.doPrivileged(AccessController.java:226)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:98)
at java.awt.EventQueue$4.run(EventQueue.java:691)
at java.awt.EventQueue$4.run(EventQueue.java:689)
at java.security.AccessController.doPrivileged(AccessController.java:226)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:688)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:222)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:124)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:101)
This message appears in db2setup.log:
"TSAMP" is needed but cannot be found on the media.
What am I doing wrong? I also tried to make the selection with the keyboard only - with the same result.
Is it possible to install db2 connect without GUI?
Stackoverflow is for programming issues, you might try dba.stackexchange.com for non-programming matters.
According to IBM SPCR, the v10.1 of Db2-connect was supported on RHEL 5.6 & 6, also SLES 10 and 11 , and Ubuntu 10.04LTS , 12.04LTS.
It might work (or might not) on later versions of Linux, or Debian 9.5 , or might have issues that need workaraounds. You might not get official support via the IBM formal channels. If you intend to use for production, ensure your business formally accepts the risks of running an out-of-support product on operating-system for which it was not tested.
If possible, use a currently supported version of a Db2-connect edition. Check end of support dates with IBM.
Ensure you try with the final fixpack of V10.1 which is FP6 (free download from IBM - get the 'server fixpack' build fixpack, not the universal one,
the server fixpack is installable without needing the base product to be installed already).
Install as root, because non-root installs are troublesome.
Carefully verify all of the prerequisites especially the required packages, SElinux settings, kernel-parameters and all others mentioned in documentation.
To install without a GUI you have 2 options, either use db2setup with response-files, or use the command-line db2_install tool (deprecated, but still works). Both tools support additional detailed logging (tracing) which can help, refer to documentation for details.
If you already have a different working Db2-connect server, you can use its db2rspgn tool to generate a text response-file (which you can then edit as needed) and supply the modified response file to db2setup.
If you get installation/run issues, try dba.stackexchange.com.
To avoid the exception, the TSAMP option must be deselected (installation type: CUSTOM).

Accessing HDFS on Cloudera with Java and Kerberos Keytab from Windows

I'm trying to connect to my HDFS instance running on Cloudera. My first step was enabling Kerberos and creating Keytabs (as shown here).
In the next step i would like to authenticate with a keytab.
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://cloudera:8020");
conf.set("hadoop.security.authentication", "kerberos");
UserGroupInformation.setConfiguration(conf);
UserGroupInformation.loginUserFromKeytab("hdfs#CLOUDERA", "/etc/hadoop/conf/hdfs.keytab");
FileSystem fs = FileSystem.get(conf);
FileStatus[] fsStatus = fs.listStatus(new Path("/"));
for (int i = 0; i < fsStatus.length; i++) {
System.out.println(fsStatus[i].getPath().toString());
}
It fails with the following error
java.io.IOException: Login failure for hdfs#CLOUDERA from keytab
/etc/hadoop/conf/hdfs.keytab:
javax.security.auth.login.LoginException: Unable to obtain password
from user
The question is: how do I correctly handle the keytab? Do i have to copy it to my local machine?
When running a Hadoop client on Windows to reach a kerberized cluster, you need a specific "native library" (i.e. DLL).
As far as I can tell there is no good reason for that, because that lib is not actually used outside of some automated regression tests (!?!) so it's a pain inflicted to Hadoop users by Hadoop committers.
To add extra pain, there is no official build of that DLL (and of the Windows "stub" that enable its use from Java). You must either (a) build it yourself from source code -- good luck -- or (b) search the internet for a downloadable Hadoop-for-Windows runtime, and pray that is does not contain any malware.
The best option (for 64-bit Windows) is here: https://github.com/steveloughran/winutils
...and the ReadMe explains why you can reasonably trust that run-time. But if you are stuck with an older 32-bit Windows, then you are on your own.
Now let's assume you deployed that run-time on your Windows box under
C:\Some Dir\hadoop\bin\(the final bin is required; the embedded space is just extra fun)
You must point the Hadoop client to that run-time with a couple of Java properties:
"-Dhadoop.home.dir=C:/Some Dir/hadoop" "-Djava.library.path=C:/Some Dir/hadoop/bin"
(note the double quotes around Windows args as a whole, to protect embedded spaces in the paths, which have been translated to Java style for extra fun)(in Eclipse, just stuff these props under "VM Arguments", quotes included)
Now, there's the Kerberos config. If your KDC is your corporate Active Directory server, then Java should find the config parameters automatically. But if your KDC is a standalone "MIT Kerberos" install on Linux, then you have to find a valid /etc/krb5.conf file on the cluster, copy it on your Windows box, and have Java use it with an additional property...
"-Djava.security.krb5.conf=C:/Some Other Dir/krb5.conf"
Then let's assume you have created your keytab file on a Linux box, using ktutil (or an Active Directory admin created it for you with some AD command) and you dropped the file under C:\Some Other Dir\foo.keytab
Before anything else, if the keytab is for a real Windows account -- i.e. your own account -- or a Prod service account, then make sure that keytab is secure!! Use the Windows Security dialog box to restrict access to your account only (and maybe System, for backups). Because that file could enable anyone, on any machine, to authenticate on the cluster (and any Kerberos-enabled system, including Windows).
Now you can try to authenticate using
UserGroupInformation.loginUserFromKeytab("foo#BAR.ORG", "C:/Some Other Dir/foo.keytab");
If it does not work, enable the Kerberos debug traces with both an environment variable
set HADOOP_JAAS_DEBUG=true
...and a Java property
-Dsun.security.krb5.debug=true
(in Eclipse, set these in "Environment" and "VM Arguments" respectively)
Do you have set proper permissions?
chown hdfs:hadoop /etc/hadoop/conf/hdfs.keytab
chmod 440 /etc/hadoop/conf/hdfs.keytab

JAVA EE 7 First cup tutorial, can't install Glassfish 4 update center

Well I was trying to follow the first cup tutorial, but I'm stuck with a Glassfish error.
I'm supposed to this:
1.2.4 Getting the Latest Updates to the Tutorial
Check for any updates to this tutorial by using the Update Center
included with the Java EE 7 SDK.
1.2.4.1 Update the Tutorial Through the Update Center Open the Update Center and check for any updates to the tutorial.
In NetBeans IDE, select the Services tab and expand the Servers node.
Right-click the GlassFish Server instance and select View Update
Center to display the Update Tool. In the tree, select Available
Updates to display a list of updated packages. Look for updates to the
First Cup for Java EE 7 (javaee-firstcup-tutorial) package. If there
is an updated version of First Cup, select First Cup 7.0 for Java EE 7
(javaee-firstcup-tutorial) and click Install.
The thing is, when I try to open the Update Center, this is what I get:
The software needed for this command (updatetool) is not installed.
If you choose to install Update Tool, your system will be automatically
configured to periodically check for software updates. If you would like
to configure the tool to not check for updates, you can override the
default behavior via the tool's Preferences facility.
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:196)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:687)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:633)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:658)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1323)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
at com.sun.pkg.client.Image.checkRepositoryConnection(Image.java:1225)
at com.sun.pkg.client.Catalog.refresh(Catalog.java:132)
at com.sun.pkg.client.Image.refreshCatalogs(Image.java:1627)
at com.sun.pkg.client.Client.main(Client.java:109)
When this tool interacts with package repositories, some system information
such as your system's IP address and operating system type and version
is sent to the repository server. For more information please see:
http://wikis.oracle.com/display/updatecenter/UsageMetricsUC2
Once installation is complete you may re-run this command.
Would you like to install Update Tool now (y/n):
C:\Program Files\glassfish-4.0>"C:\Program Files\Java\jdk1.7.0_40\bin\java" -Dimage.path="C:\Program Files\glassfish-4.0\bin\\.." -jar "C:\Program Files\glassfish-4.0\bin\\..\pkg/lib/pkg-client.jar" refresh
C:\Program Files\glassfish-4.0>"C:\Program Files\Java\jdk1.7.0_40\bin\java" -Dimage.path="C:\Program Files\glassfish-4.0\bin\\.." -jar "C:\Program Files\glassfish-4.0\bin\\..\pkg/lib/pkg-bootstrap.jar" "C:\Users\Fabio\AppData\Local\Temp\pkg-bootstrap11073.props"
Proxy: Using system proxy settings.
Input/output error: Connection reset
Could not download application packages. This could be because:
- a proxy server is needed to access the internet. Please ensure that
the system proxy server settings in your Internet Options control panel
(under Connections:LAN Settings) are correct, or set the HTTP_PROXY
environment variable to the full URL of the proxy server.
- the package server or network connection is slow.
If you are getting time out errors you can try setting the
PKG_CLIENT_CONNECT_TIMEOUT and PKG_CLIENT_READ_TIMEOUT
environment variables and try again. For example to increase
the timeouts to 300 seconds set them to 300
- the package server is down or otherwise inaccessible or it is
generating invalid data. Please contact the provider of the package
server.
This may be a problem with the slow GlassFish update server. Here are some steps you can try:
You should retry first to see if the error occurs again. You can start a cmd, navigate to the \glassfish\bin directory and run updatetool.bat so you can see the output which is printed after the one you posted.
If you are behind a proxy you should make sure it is setup correctly in the system settings.
You can also try to install the updates through the GlassFish admin console. Start your GlassFish instance and navigate to http:\\localhost:4848. On the bottom of the left menu click on Updatetool. There you can choose and install the desired updates.
Another option is to change the timeouts of the pkg tool. To set the timeout to 300 seconds do the following in a cmd (on Windows):
set PKG_CLIENT_CONNECT_TIMEOUT=300
set PKG_CLIENT_READ_TIMEOUT=300
Your last (ok, there may be other ones) option is to just skip the update process and do the tutorial with the current version. It should work anyway and I can see in my GlassFish update center that there is only an update for the tutorial documentation at the moment.
Just set this line into cmd (like administrator):
set PKG_CLIENT_CONNECT_TIMEOUT=300
set PKG_CLIENT_READ_TIMEOUT=300
Maybe the firstcup example is already existed in the install directory. Try to find it in the directory_install_glassfish/glassfish4/docs. The mine contain even javaee-tutorial and firstcup. For the next part, you maybe continue after guide in firstcup.pdf with the part of : Creating Your First Java by create archetype of java project. Good luck !
For the lazy of you the pkg Unix command is:
export PKG_CLIENT_CONNECT_TIMEOUT=300
export PKG_CLIENT_READ_TIMEOUT=300
After being stuck for a while on the installation of GlassFish update server from Netbeans (in my company network, proxy issues), I got it this way:
- Advanced System Settings > System Properties window > Advanced tab, New System Variable: http_proxy, http://username:password#your_proxy:your_port
- Netbeans (running as admin just in case), Services > Server > Glassfish Server > Right button View Domain Update Center, then install
It worked for me, Hope it helps!

Internal path mapping in windows 7

I have a windows7 machine in which i am creating a file through java code in following path
C:\Users\123\Application Data\XYZ
but physically it is getting created here
C:\Users\123\AppData\Roaming\XYZ
please tell me why?
Because one is a legacy path, and the other is the current preferred folder path. Both lead to the same location.
See e.g. Application Compatibility: Junction Points and Backup Applications:
In Windows Vista® and Windows Server® 2008, the default location of user data has changed. An example of this change is the Documents and Settings directory, which has been moved from %systemdrive%\Documents and Settings to %systemdrive%\Users.
and:
..\Documents and Settings\\Application Data\ [is mapped to] ..\Users\\AppData\Roaming

Categories