Search code examples
javalinuxjspfile-permissionsjna

Could not initialize class com.sun.jna.Native


I was trying to change the file permission of programmically uploaded files on linux server using JNA. My references are this and this. And my code is given below. And am getting a Operation not permitted exception. Is there any way to resolve this problem? Is there any other way to programmicaly change the permission of the uploaded file? Or is there any way to upload the file with a specified file permission. I am using java 1.5. I have put jna.jar in /public_html/WEB-INF/lib, can anyone suggest a good JNA tutorial for beginners?

JSP code (for testing)

<%@page import="cc.FileModifierLinux"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%

try
{


    FileModifierLinux flx=new FileModifierLinux();
    String pathX = getServletContext().getRealPath("/testpage.jsp");
    flx.Update(pathX);
    out.println("No Exception");
}
catch(Exception exp)
{
    out.println("exp :"+exp);
}
%>
</body>
</html>

Class Used

package cc;
import com.sun.jna.Library;
import com.sun.jna.Native;

public class FileModifierLinux {
     CLibrary libc = (CLibrary) Native.loadLibrary("c", CLibrary.class);
    public void Update(String pth) {
        libc.chmod(pth, 0755);
    }
}

interface CLibrary extends Library {
    public int chmod(String path, int mode);
}

Exception

for full exception details refer this

 org.apache.jasper.JasperException: Exception in JSP: /index_check.jsp:23

20: {
21:     
22:     
23:     FileModifierLinux flx=new FileModifierLinux();
24:     String pathX = getServletContext().getRealPath("/testpage.jsp");
25:     flx.Update(pathX);
26:     out.println("No Exception");


Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:491)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:395)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:308)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:259)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

root cause

javax.servlet.ServletException: Could not initialize class com.sun.jna.Native

Solution

  • You likely need to install libjnidispatch.so on your server such that it is available in java.library.path so that JNA can load it. The exception thrown is due to JNA not finding that library and attempting to unpack it from its own jar file.

    Based on the original exception, your servlet won't be allowed to load native libraries except from designated, protected locations. Check your servlet container documentation for how to install and make available for loading JNI libraries.