Objectio dB database for Java desktop persistance - java

I have been trying out object ox io for Java. It has been working well on Android hence I decided to go with it on Java desktop implementation.
The problem I am facing is that I can save my data at run time but when I restart the app or desktop app the data is gone, is forgotten, which is very strange. I have tried to look for an explanation but haven't found anything on this. Can anyone help or have an idea why this is? In the mean time I have reverted to using SQLite. The app is intended to be very big and have a lot of multi-threads.
here is a sample
import io.objectbox.BoxStore;
import io.objectbox.DebugFlags;
import lombok.SneakyThrows;
import java.io.File;
import java.io.IOException;
public class DBObjectManager {
public static DBObjectManager objectIOAccessInstance ;
private BoxStore store;
private DBObjectManager() {
File tempFile = null;
try {
tempFile = File.createTempFile("objectdb", "");
} catch (IOException e) {
e.printStackTrace();
}
tempFile.delete();
store = MyObjectBox.builder()
.directory(tempFile)
.debugFlags(DebugFlags.LOG_QUERIES | DebugFlags.LOG_QUERY_PARAMETERS)
.build();
}
public static DBObjectManager getinstance() {
if (objectIOAccessInstance == null) {
objectIOAccessInstance = new DBObjectManager();
}
return objectIOAccessInstance;
}
public BoxStore getStore() {
return store;
}
}

You are creating a new temporary file each time when you execute your application. I guess that explains your problem.
From the docs:
creates a new empty file in the specified directory. deleteOnExit()
method is called to delete the file created by this method.

Related

Testing for local or remote path (without sun.awt.shell.ShellFolder class)

I am trying to move from Java 15 to Java 17 but because they now enscapulate the internals and have removed the flag –illegal-access I have a problem.
From https://www.baeldung.com/java-17-new-features
JEP 403 represents one more step toward strongly encapsulating JDK
internals since it removes the flag –illegal-access. The platform will
ignore the flag, and if the flag is present, the console will issue a
message informing the discontinuation of the flag.
I have a class that fails because it references
sun.awt.shell.ShellFolder;
sun.awt.shell.ShellFolderColumnInfo;
The purpose of the class is to identify on a Windows system whether a file is on local fileystem
import com.jthink.songkong.analyse.filename.WindowsFileSystem;
import com.jthink.songkong.ui.MainWindow;
import sun.awt.shell.ShellFolder;
import sun.awt.shell.ShellFolderColumnInfo;
import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Level;
/**
* Only Windows can load these methods because of reliance on sun classes
*
*/
public class WindowsFilesystemType
{
public static final String WINDOWS_SHELL_ATTRIBUTES = "Attributes";
public static final String WINDOWS_SHELL_ITEM_TYPE = "Item type";
public static final String WINDOWS_SHELL_SIZE = "Size";
/**
* Is this a local drive, only works for Windows machine because relies on underlying Windows code
*
* #param newPath
*
* #return true if this a local drive
*/
public static boolean isLocal(String newPath)
{
try
{
Path root = Paths.get(newPath).getRoot();
ShellFolder shellFolder = ShellFolder.getShellFolder(root.toFile());
ShellFolderColumnInfo[] cols = shellFolder.getFolderColumns();
for (int i = 0; i < cols.length; i++)
{
if (cols[i].getTitle().equals(WINDOWS_SHELL_SIZE)
&& ((String) shellFolder.getFolderColumnValue(i)).startsWith(WindowsShellFileSystemType.LOCAL_DISK))
{
return true;
}
else if (cols[i].getTitle().equals(WINDOWS_SHELL_ATTRIBUTES))
{
//Mapped network drive
if(shellFolder.getFolderColumnValue(i)!=null && ((String)shellFolder.getFolderColumnValue(i)).startsWith("\\"))
{
return false;
}
//SONGKONG-2186:Can be null if unmapped network drive
else if(shellFolder.getFolderColumnValue(i)==null)
{
return false;
}
}
}
}
catch (Exception ex)
{
MainWindow.logger.log(Level.SEVERE, ex.getMessage(), ex);
return false;
}
return true;
}
}
Can this be achieved another way, or is there a way I can still access these sun classes ?
The reason I need is isLocal() is my program renames files and there is an option for the user to restrict path length to 259 characters because longer lengths cause problems for Windows Explorer, but if they are modifying a remote drive then not usual to enforce this requirement, I will add more detail to question.
For example the application renames music files if they are eon local drive to be used by Windows then they may want to enforce that limit. But if it is a networked drive they probably will not because quite often the files are stored on a Nas and they are only accessing the files via Windows because my application can run on Windows but not on the Nas.
Note that ShellFolder is the backend of the FileSystemView API which provides most of the functionality to present file information in a UI. Testing whether a file is on a network drive isn’t provided though, but your original code looks more like a heuristic anyway.
The simplest test I’ve found so far, based on NIO only, is for the Volume Serial Number, which is only available for local drives:
public class WindowsFilesystemType {
public static boolean isNTFSOrFAT32(String newPath) {
try {
return switch(Files.getFileStore(Paths.get(newPath)).type()) {
case "NTFS", "FAT", "FAT32", "EXFAT" -> true;
default -> false;
};
} catch (IOException ex) {
MainWindow.logger.log(Level.SEVERE, ex.getMessage(), ex);
return false;
}
}
public static boolean isRemote(String newPath) {
try {
FileStore fileStore = Files.getFileStore(Paths.get(newPath));
return Integer.valueOf(0).equals(fileStore.getAttribute("volume:vsn"));
} catch(Exception ex) {
MainWindow.logger.log(Level.SEVERE, ex.getMessage(), ex);
return false;
}
}
public static boolean isLocal(String newPath) {
try {
FileStore fileStore = Files.getFileStore(Paths.get(newPath));
return !Integer.valueOf(0).equals(fileStore.getAttribute("volume:vsn"));
} catch(Exception ex) {
MainWindow.logger.log(Level.SEVERE, ex.getMessage(), ex);
return false;
}
}
}
This Windows file store attribute has not been documented, but it works since Java 7.

Project Stops working after compiling to jar

I currently want to try to create a .jar file that pinpoints to a .bat file to start a gaming server,
the Forge Modloader for the current version switched from a server startup via jar file to .bat file, and my server provider currently has no solution for it. -Small disclaimer, I haven't touched java for 6 years, which is why I may not see the obvious
For this, I found some code from Pavan.
Though, there are two problems, where I hope you may have a solution or some other workaround.
First of all, while in Intellij, "everything" works fine. main() is running, and the "Hallo World" Test .bat is opening. After compiling it to a jar, nothing happens, even with a set File Path.
Second Problem. I've tried several spots, but System.exit(0) does not work, after
int returnCode = CommandLineUtils.executeCommandLine(commandLine, systemOut, systemErr);
The code basically stops, and the process stays inactive, which could end up bad for a gaming server where I have 0 access to the needed tools to clean this up by myself... and I don't want to explain to Customer Support why there are 1000 instances of java running in the background ;)
But regardless, Thanks for your time and hopefully help as well
import java.io.File;
import java.io.OutputStreamWriter;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import org.codehaus.plexus.util.cli.WriterStreamConsumer;
public class BatRunner {
public BatRunner() {
String batfile = "run.bat";
String directory = "C:\\Users\\User\\IdeaProjects";
try {
runProcess(batfile, directory);
} catch (CommandLineException e) {
e.printStackTrace();
}
}
public void runProcess(String batfile, String directory) throws CommandLineException {
Commandline commandLine = new Commandline();
File executable = new File(directory + "/" +batfile);
commandLine.setExecutable(executable.getAbsolutePath());
WriterStreamConsumer systemOut = new WriterStreamConsumer(
new OutputStreamWriter(System.out));
WriterStreamConsumer systemErr = new WriterStreamConsumer(
new OutputStreamWriter(System.out));
int returnCode = CommandLineUtils.executeCommandLine(commandLine, systemOut, systemErr);
System.exit(0);
if (returnCode != 0) {
System.out.println("Something Bad Happened!");
} else {
System.out.println("Taaa!! ddaaaaa!!");
}
}
public static void main(String[] args) {
new BatRunner();
}
}
Source: https://www.opencodez.com/java/how-to-execute-bat-file-from-java.htm/

find and call web service from uddi java

So I have been looking around for days and I still can't find a simple working method. This is what I am trying to do:
1 - Search and find web services registered in UDDI based on keywords
2 - Decide which service fits and use/call it
All this using Java (Eclipse).
I don't want to create my own uddi nor do I want to publish services, just find existing services stored in the public UDDI (I believe there's one, right?). I thought that these two tasks (find WS, call WS) would be easy and that it would be possible to find sample code to use, but I can't find any.
I came across Juddi while searching, but not sure if it works for my case and if it's worth installing.
Any tutorials? suggestions ? I found the following code, but can't find the jar file to use its libraries:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package uddi.createbulk;
import javax.xml.bind.JAXB;
import org.apache.juddi.v3.client.config.UDDIClient;
import org.apache.juddi.v3.client.config.UDDIClientContainer;
import org.apache.juddi.v3.client.transport.Transport;
import org.apache.juddi.v3_service.JUDDIApiPortType;
import org.uddi.api_v3.*;
import org.uddi.v3_service.UDDIInquiryPortType;
import org.uddi.v3_service.UDDIPublicationPortType;
import org.uddi.v3_service.UDDISecurityPortType;
/**
*
* #author Alex
*/
public class UddiFindService {
private static UDDISecurityPortType security = null;
private static JUDDIApiPortType juddiApi = null;
private static UDDIPublicationPortType publish = null;
private static UDDIInquiryPortType inquiry = null;
public UddiFindService() {
try {
// create a manager and read the config in the archive;
// you can use your config file name
UDDIClient clerkManager = new UDDIClient("META-INF/simple-publish-uddi.xml");
// register the clerkManager with the client side container
UDDIClientContainer.addClient(clerkManager);
// a ClerkManager can be a client to multiple UDDI nodes, so
// supply the nodeName (defined in your uddi.xml.
// The transport can be WS, inVM, RMI etc which is defined in the uddi.xml
Transport transport = clerkManager.getTransport("default");
// Now you create a reference to the UDDI API
security = transport.getUDDISecurityService();
juddiApi = transport.getJUDDIApiService();
publish = transport.getUDDIPublishService();
inquiry = transport.getUDDIInquiryService();
} catch (Exception e) {
e.printStackTrace();
}
}
public void find() {
try {
// Setting up the values to get an authentication token for the 'root' user ('root' user has admin privileges
// and can save other publishers).
GetAuthToken getAuthTokenRoot = new GetAuthToken();
getAuthTokenRoot.setUserID("root");
getAuthTokenRoot.setCred("root");
// Making API call that retrieves the authentication token for the 'root' user.
AuthToken rootAuthToken = security.getAuthToken(getAuthTokenRoot);
System.out.println("root AUTHTOKEN = " + rootAuthToken.getAuthInfo());
GetServiceDetail fs = new GetServiceDetail();
fs.setAuthInfo(rootAuthToken.getAuthInfo());
fs.getServiceKey().add("mykey");
ServiceDetail serviceDetail = inquiry.getServiceDetail(fs);
if (serviceDetail == null || serviceDetail.getBusinessService().isEmpty()) {
System.out.println("mykey is not registered");
} else {
JAXB.marshal(serviceDetail, System.out);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
UddiFindService sp = new UddiFindService();
sp.find();
}
}

Reading NFC Tag using JAVA Smart Card API not working on MAC OS

I am developing an application to read a NFC Tag UID from NFC Reader (ACR122U-A9) device.
I used JAVA and javax.smartcardio API to detect the NFC Reader and Reading NFC Tag.
The functionality of the application is to display notification when the NFC Reader device is connect or disconnect from PC. Then if the device is connected and NFC Tag is presented then display the notification that NFC Tag is presented.
I tried to find the Event based api to implement above functionality but I cannot find so I used Java Timer and Polling for the NFC Reader Device and NFC Tag.
Following is my sample JAVA code that used for Polling for NFC device and Tag.
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.smartcardio.CardTerminal;
import javax.smartcardio.TerminalFactory;
/**
*
* #author sa
*/
public class NFC_Test {
/**
* #param args the command line arguments
*/
static Timer timer;
public static void main(String[] args) {
try {
timer = new Timer(); //At this line a new Thread will be created
timer.scheduleAtFixedRate(new NFC_Test.MyTask(), 0, 1000);
} catch (Exception ex) {
Logger.getLogger(NFC_Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
static class MyTask extends TimerTask {
public void run() {
///////////////////This fix applied after reading thread at http://stackoverflow.com/a/16987873/1411888
try {
Class pcscterminal =
Class.forName("sun.security.smartcardio.PCSCTerminals");
Field contextId = pcscterminal.getDeclaredField("contextId");
contextId.setAccessible(true);
if (contextId.getLong(pcscterminal) != 0L) {
Class pcsc =
Class.forName("sun.security.smartcardio.PCSC");
Method SCardEstablishContext = pcsc.getDeclaredMethod(
"SCardEstablishContext", new Class[]{Integer.TYPE});
SCardEstablishContext.setAccessible(true);
Field SCARD_SCOPE_USER =
pcsc.getDeclaredField("SCARD_SCOPE_USER");
SCARD_SCOPE_USER.setAccessible(true);
long newId = ((Long) SCardEstablishContext.invoke(pcsc, new Object[]{Integer.valueOf(SCARD_SCOPE_USER.getInt(pcsc))})).longValue();
contextId.setLong(pcscterminal, newId);
}
} catch (Exception ex) {
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
TerminalFactory factory = null;
List<CardTerminal> terminals = null;
try {
factory = TerminalFactory.getDefault();
terminals = factory.terminals().list();
} catch (Exception ex) { //
Logger.getLogger(NFC_Test.class.getName()).log(Level.SEVERE,null, ex);
}
if (factory != null && factory.terminals() != null && terminals
!= null && terminals.size() > 0) {
try {
CardTerminal terminal = terminals.get(0);
if (terminal != null) {
System.out.println(terminal);
if (terminal.isCardPresent()) {
System.out.println("Card");
} else {
System.out.println("No Card");
}
} else {
System.out.println("No terminal");
}
terminal = null;
} catch (Exception e) {
Logger.getLogger(NFC_Test.class.getName()).log(Level.SEVERE,null, e);
}
factory = null;
terminals = null;
Runtime.getRuntime().gc();
} else {
System.out.println("No terminal");
}
}
}
}
Above code is working fine in Windows OS but when I run it on MAC OS then application runs for 5-10 seconds perfectly but then it suddenly crash with the following memory error.
java(921,0x10b0c3000) malloc: *** mmap(size=140350941302784) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Java Result: 139
I searched on internet and cannot find anything regarding above memory error. Also I included the code for memory management to release the object when it is used in timer by assigning NULL value to it.
I have used http://ludovicrousseau.blogspot.com/2010/06/pcsc-sample-in-java.html for reference
I believe this was one of the errors I was getting when trying to track down the bugs with libj2pcsc.dylib on 64-bit Java on OS X. See also smartcardio thread on discussions.apple.com and my email to security-dev. Basically, the problem is that DWORD* should be a pointer to a 32-bit number on OS X, but Sun’s library assumed that it was a pointer to a 64-bit number. Then it dereferences that value and tries to malloc a buffer of that size, which can contain junk in the upper 32 bits. See Java_sun_security_smartcardio_PCSC_SCardListReaders in the source of pcsc.c
Potential workarounds:
Be very conservative with calls to Terminals.list() (which crashes intermittently), and don’t trust the results of Terminal.isCardPresent(), Terminals.waitForChange(long), or CardTerminal.waitForCard(boolean, long). My co-worker realized that he could call TerminalImpl.SCardGetStatusChange(long, long, int[], String[]) using reflection to get the right results. This is what we used to do. Very painful!
Fix the header files for libj2pcsc.dylib and recompile OpenJDK. This is what we do at my company right now.
Switch to a different implementation of javax.smartcardio. I know of two: my own jnasmartcardio and intarsys/smartcard-io. I have not tried my own library on NFC cards, however, but I welcome any bug reports and patches.

want to copy a file from a server to a client

i want to copy a file from a server to a client in java.this is my code up to now
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class Copy {
private ListDirectory dir = new ListDirectory();
public Copy() {
}
public String getCopyPath(String file) throws Exception {
String path = dir.getCurrentPath();
path += "\\" + file;
return path;
}
public void copyFile(String file) {
try {
File inputFile = new File(dir.getCurrentPath());
URL copyurl;
InputStream outputFile;
copyurl = new URL(getCopyPath(file));
outputFile = copyurl.openStream();
FileOutputStream out = new FileOutputStream(inputFile);
int c;
while ((c = outputFile.read()) != -1)
out.write(c);
outputFile.close();
out.close();
} catch (Exception e) {
System.out.println("Failed to Copy File from server");
e.printStackTrace();
}
}
public static void main(String args[]) {
String a = "put martin";
String b = a.substring(0, 3);
String c = a.substring(4);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
Problem is , the server is not uploadded online , but it is on my local drive, and the URL thing doesnt work. is there any other way? is this way correct? thanks
If you're expecting to access your file from the local file system (whether that be via network drive or a local disk), you'll need to treat this as if it is a straight file copy.
If you're expecting to access your file as if it is available for download from an HTTP server, you will need to treat it as an HTTP download (which is what it looks like you're trying to do with the URL).
If you want to test the HTTP download functionality using a file on your local system, just set up a simple HTTP server on your dev machine with a directory on your local system, and give your HTTP-downloading code a URL pointing to that local server (on http://localhost, or using your IP address).
Unfortunately, HTTP is a very different animal from a file system, and I don't think there's any way to use the same code to handle both scenarios. If you want your program to ultimately support both protocols, you should build methods/classes to handle both situations, and then have your program detect and use the appropriate protocol for a given path. You'll need to do the same for any other protocol you wish to support (FTP, SFTP, etc).

Categories