Java NIO FIle path Issue 2 [duplicate] - java

I am using Java 7 File API. I wrote a class that is working fine on Ubuntu creating directories perfectly, but when I run same code on Windows then it is throwing error:
Exception in thread "main" java.lang.UnsupportedOperationException: 'posix:permissions' not supported as initial attribute
at sun.nio.fs.WindowsSecurityDescriptor.fromAttribute(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.createDirectory(Unknown Source)
at java.nio.file.Files.createDirectory(Unknown Source)
at java.nio.file.Files.createAndCheckIsDirectory(Unknown Source)
at java.nio.file.Files.createDirectories(Unknown Source)
at com.cloudspoke.folder_permission.Folder.createFolder(Folder.java:27)
at com.cloudspoke.folder_permission.Main.main(Main.java:139)
My Folder class code is
package com.cloudspoke.folder_permission;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.UserPrincipal;
import java.util.Set;
public class Folder{
// attributes required for creating a Folder
private UserPrincipal owner;
private Path folder_name;
private FileAttribute<Set<PosixFilePermission>> attr;
public Folder(UserPrincipal owner,Path folder_name,FileAttribute<Set<PosixFilePermission>> attr){
this.owner=owner;
this.folder_name=folder_name;
this.attr=attr;
}
//invoking this method will create folders
public void createFolder(){
try {
//createDirectories function is used for overwriting existing folder instead of createDirectory() method
Files.createDirectories(folder_name, attr);
Files.setOwner(folder_name, owner);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("created Folder "+this.folder_name);
}
}
The error is coming from createFolder method of Folder.
How do I resolve this error?

You use PosixFilePermission which can be used only with operating systems which are compatibile with POSIX:
A file attribute view that provides a view of the file attributes commonly associated with files on file systems used by operating systems that implement the Portable Operating System Interface (POSIX) family of standards.
Operating systems that implement the POSIX family of standards commonly use file systems that have a file owner, group-owner, and related access permissions. This file attribute view provides read and write access to these attributes`
Windows unfortunatelly doesn't support POSIX file systems so this is why your code doesn't work. In order to create a directory in Windows you should use:
new File("/path/to/folder").mkdir();
The / will be automatically changed to \ in Windows. If you want to create the whole path at once you have to use mkdirs() method. More info: http://docs.oracle.com/javase/6/docs/api/java/io/File.html
In order to set file permissions in Windows you have to use setReadable(), setWritable() and setExecutable(). That are File class methods and set only file owner's permissions. Note that mentioned methods were added in Java 1.6. In older versions you would have to use (Windows version):
Runtime.getRuntime().exec("attrib -r myFile");

Related

Could not load JIntellitype.dll from local file system or from inside JAR

I am trying to use JIntellitype to listen to global hotkeys but I get this error:
Exception in thread "main"
com.melloware.jintellitype.JIntellitypeException: Could not load
JIntellitype.dll from local file system or from inside JAR at
com.melloware.jintellitype.JIntellitype.(JIntellitype.java:114)
at
com.melloware.jintellitype.JIntellitype.getInstance(JIntellitype.java:177)
at utils.HotKey.(HotKey.java:19) at
ui.Main.Catch_Hotkeys(Main.java:78) at ui.Main.(Main.java:20)
at ui.Main.main(Main.java:15) Caused by: java.io.IOException:
FromJarToFileSystem could not load DLL:
com/melloware/jintellitype/JIntellitype.dll at
com.melloware.jintellitype.JIntellitype.fromJarToFs(JIntellitype.java:150)
at
com.melloware.jintellitype.JIntellitype.(JIntellitype.java:105)
... 5 more Caused by: java.lang.NullPointerException at
com.melloware.jintellitype.JIntellitype.fromJarToFs(JIntellitype.java:146)
... 6 more
I have loaded the jar file and I also pointed to the folder where the dlls are located through Referenced Libraries.
Here is the code I am trying to run:
import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.IntellitypeListener;
import com.melloware.jintellitype.JIntellitype;
public class HotKey extends Thread implements HotkeyListener, IntellitypeListener {
private final int CTRL_C_SHIFT = 10;
public HotKey()
{
JIntellitype.getInstance().unregisterHotKey(CTRL_C_SHIFT);
JIntellitype.getInstance().registerHotKey(CTRL_C_SHIFT, JIntellitype.MOD_CONTROL + (int)'C', JIntellitype.MOD_SHIFT);
if (!JIntellitype.isJIntellitypeSupported())
{
System.exit(1);
}
}
#Override
public void onIntellitype(int arg0)
{
}
#Override
public void onHotKey(int key)
{
if (key == CTRL_C_SHIFT)
{
System.out.println("smg");
}
}
}
Any idea how to fix this?
Your problem will occur because of a version problem between that OS version and the JRE version.
You should check:
Whether an appropriate dll file is installed in your OS system folder.
JIntellitype package has two dll files, one is for 32bit OSs and the other is for 64bit OSs, they have different names.
Check your Java Platform version in the properties of the projects.
You can try to change the Java Platform, if there are more than one types of JDKs.
Make sure about which one is for 64bit or 32bit version.
Have good luck!
I recommend you do something like this:
try
{
JIntellitype.getInstance().unregisterHotKey(CTRL_C_SHIFT);
MyHotKeyListener hotKeyListener = new MyHotKeyListener();
hotKeyListener.addObserver(new MyEventListener());
JIntellitype.getInstance().addHotKeyListener(hotKeyListener);
JIntellitype.getInstance().registerHotKey(CTRL_C_SHIFT, JIntellitype.MOD_CONTROL + (int)'C', JIntellitype.MOD_SHIFT);
}
catch (JIntellitypeException je)
{
logger.warn("JIntellitype initialization failed.");
// DO WHATEVER (NOTIFY USERS?)
}
I can point to other threads, including one where the creator of this library himself denies problems with the library. However, many users such as myself encounter these sort of problems from time to time where JIntellitype fails to initialize and the only solution is to reboot the computer. Because of this, you should catch the JIntellitype exception (the only exception thrown by the library) and warn users (via dialog window) that the hotkey failed to register. You should give them the option to continue without them, or to reboot the computer and trying again.
Trust me.... unless this is a constant problem (which means you configured it incorrectly), it is your best alternative. This WILL happen from time to time at random.

Java HttpServer Error: Access restriction: The type 'HttpServer' is not API

I was trying to do something with the java HttpServer class.
This is the minimal example from the documentation:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpServer;
class MyHandler implements HttpHandler
{
public void handle(HttpExchange t) throws IOException
{
InputStream is = t.getRequestBody();
read(is); // .. read the request body
String response = "This is the response";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
public class Main
{
HttpServer server = HttpServer.create(new InetSocketAddress(8000));
server.createContext("/applications/myapp", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
But i get this error message:
Description Resource Path Location Type
Access restriction: The type 'HttpServer' is not API (restriction on required library '/Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/rt.jar') Main.java /test/src/test line 7 Java Problem
What does this even mean? According to the Oracle documentation this should work. Or am i getting this wrong?
The error message wants to say that you are accessing code that is not part of the official API for that library. More specifically, com.sun.net.httpserver.HttpServer is a class which is not guaranteed to be included in all Java 8 runtime implementations. Therefore, code using that class may fail in some Java installations.
In order to still be able to use this class, look into the answers to this question: Access restriction on class due to restriction on required library rt.jar?.
Don't think so that you should use Sun's internal packages but still you can try disabling the error :
Go to Project properties -> Java Compiler -> Errors/Warnings -> Deprecated and restricted API
Also this post may help you.
If still the problem remains you can go with Christian Hujer's answer who says Eclipse has a mechanism called access restrictions to prevent you from accidentally using classes which Eclipse thinks are not part of the public API.
Remove the JRE System Library from the build path and add it back.
Select "Add Library" and select the JRE System Library. The default one should work.
BuildPath >> Libraries

Unable to load library 'libtesseract302':Module cannot be found (Windows10)

We are trying to make software for a car parking system using image processing. We used OCR. We intend to use a webcam to obtain images of the license plate when the vehicle leaves and enters. We will then use the number to calculate the time spent inside the park and price tickets based on that.
This is my code:
import java.io.File;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract1;
import net.sourceforge.tess4j.TesseractException;
public class TestOCR {
public static void main(String[] args) {
File imageFile = new File("C:"+File.separator+"projects"+File.separator+"plate.tif");
//ITesseract instance = new Tesseract(); // JNA Interface Mapping
ITesseract instance = new Tesseract1(); // JNA Direct Mapping
try {
//String result = instance.doOCR(imageFile);
//stem.out.println(result);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
When I run this, I get this error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'libtesseract302': The specified module could not be found.
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:145)
at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:188)
at com.sun.jna.Library$Handler.<init>(Library.java:123)
at com.sun.jna.Native.loadLibrary(Native.java:255)
at com.sun.jna.Native.loadLibrary(Native.java:241)
at net.sourceforge.tess4j.TessAPI.<clinit>(Unknown Source)
at net.sourceforge.tess4j.Tesseract.doOCR(Unknown Source)
at net.sourceforge.tess4j.Tesseract.doOCR(Unknown Source)
at net.sourceforge.tess4j.Tesseract.doOCR(Unknown Source)
at net.sourceforge.tess4j.Tesseract.doOCR(Unknown Source)
at com.nadeem.app.ocr.TesseractExample.main(TesseractExample.java:16)
Initially we had a NoSuchFieldError and after using Maven to fix that we encountered this problem.
Basically this error would come either of below reasons
dll path are not specified properly. You can add in vm argument as below. -Djna.library.path=<folder_contains_dll>, This folder should have three dll files gsdll64.dll,liblept168.dll and libtesseract302.dll
You should have Visual C++ Redistributable for VS2012 installed. Windows 10 doesn't have this installed by default.
You may do below steps to start with
Install Visual C++ Redistributable for VS2012 if its not installed
Clone the project from https://github.com/mnadeem/ocr-tess4j-example
Import the maven project in eclipse
Run the Java class TesseractExample.java

UnsatsifiedLinkError on JSSC Serial Interface (Processing)

I'm using Proclipsing (processing in Eclipse) but am getting an error when I try and open a port (printing the serial list works fine). I have a feeling some sort of native library is not connected but I'm baffled as to how to do so in Eclipse (and where it link to).
Here's my code:
import processing.core.PApplet;
import processing.serial.Serial;
public class visualization extends PApplet {
public Serial usb = null;
public void setup() {
println(Serial.list());
println(Serial.list()[5]);
usb = new Serial(this, Serial.list()[5], 115200);
}
public void draw() {
}
}
and the error it throws is:
Exception in thread "Animation Thread" java.lang.UnsatisfiedLinkError: jssc.SerialNativeInterface.openPort(Ljava/lang/String;Z)J
at jssc.SerialNativeInterface.openPort(Native Method)
at jssc.SerialPort.openPort(SerialPort.java:158)
at processing.serial.Serial.<init>(Unknown Source)
at processing.serial.Serial.<init>(Unknown Source)
at bioauthvisualization3.BioauthVisualization3.setup(BioauthVisualization3.java:15)
at processing.core.PApplet.handleDraw(PApplet.java:2361)
at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:240)
at processing.core.PApplet.run(PApplet.java:2256)
at java.lang.Thread.run(Thread.java:745)
I ran into the same issue while setting up IntelliJ IDEA for development with Processing. But I imagine you can apply the same method in Proclipsing. The solution that worked for me was threefold.
I created a global library that contained the Processing and Serial libraries. In OS X the required jar files can be found in the directory /Applications/Processing.app/Contents/Java/ and /Applications/Processing.app/Contents/Java/modes/libraries/serial/library/. I added the following libraries: core.jar, serial.jarand jssc.jar.
Next I had to add the global library to my module dependencies.
The last step was to add the path to the native libraries to the VM options for the appletviewer: -Djava.library.path="/Applications/Processing.app/Contents/Java/modes/java/libraries/serial/library/macosx"
My guess is that Proclipsing does the first two steps for you but you have to add the native libraries to the vm options manually since these depend on the system you're working on. Hope that helps.
I derived the solution for step 3 from this forum entry.

java.lang.UnsupportedOperationException: 'posix:permissions' not supported as initial attribute on Windows

I am using Java 7 File API. I wrote a class that is working fine on Ubuntu creating directories perfectly, but when I run same code on Windows then it is throwing error:
Exception in thread "main" java.lang.UnsupportedOperationException: 'posix:permissions' not supported as initial attribute
at sun.nio.fs.WindowsSecurityDescriptor.fromAttribute(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.createDirectory(Unknown Source)
at java.nio.file.Files.createDirectory(Unknown Source)
at java.nio.file.Files.createAndCheckIsDirectory(Unknown Source)
at java.nio.file.Files.createDirectories(Unknown Source)
at com.cloudspoke.folder_permission.Folder.createFolder(Folder.java:27)
at com.cloudspoke.folder_permission.Main.main(Main.java:139)
My Folder class code is
package com.cloudspoke.folder_permission;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.UserPrincipal;
import java.util.Set;
public class Folder{
// attributes required for creating a Folder
private UserPrincipal owner;
private Path folder_name;
private FileAttribute<Set<PosixFilePermission>> attr;
public Folder(UserPrincipal owner,Path folder_name,FileAttribute<Set<PosixFilePermission>> attr){
this.owner=owner;
this.folder_name=folder_name;
this.attr=attr;
}
//invoking this method will create folders
public void createFolder(){
try {
//createDirectories function is used for overwriting existing folder instead of createDirectory() method
Files.createDirectories(folder_name, attr);
Files.setOwner(folder_name, owner);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("created Folder "+this.folder_name);
}
}
The error is coming from createFolder method of Folder.
How do I resolve this error?
You use PosixFilePermission which can be used only with operating systems which are compatibile with POSIX:
A file attribute view that provides a view of the file attributes commonly associated with files on file systems used by operating systems that implement the Portable Operating System Interface (POSIX) family of standards.
Operating systems that implement the POSIX family of standards commonly use file systems that have a file owner, group-owner, and related access permissions. This file attribute view provides read and write access to these attributes`
Windows unfortunatelly doesn't support POSIX file systems so this is why your code doesn't work. In order to create a directory in Windows you should use:
new File("/path/to/folder").mkdir();
The / will be automatically changed to \ in Windows. If you want to create the whole path at once you have to use mkdirs() method. More info: http://docs.oracle.com/javase/6/docs/api/java/io/File.html
In order to set file permissions in Windows you have to use setReadable(), setWritable() and setExecutable(). That are File class methods and set only file owner's permissions. Note that mentioned methods were added in Java 1.6. In older versions you would have to use (Windows version):
Runtime.getRuntime().exec("attrib -r myFile");

Categories