com.sun.jersey.server.impl.application.RootResourceUriRules。<init> ResourceConfig实例不包含任何根资源类

时间:2017-05-13 18:49:48

标签: java maven amazon-web-services tomcat jersey

将war文件上传到AWS Tomcat8 Server时,我遇到了一些问题。

项目类型:动态Web项目; Tomcat:版本 - 8; Java:版本1.8

在我使用Java向AWS S3 Instance添加文件上载和下载操作的代码之前,它的工作正常。

  

2017年5月13日19:29:55.770 INFO [http-nio-8088-exec-3]   org.apache.jasper.servlet.TldScanner.scanJars至少有一个JAR   扫描TLD但尚未包含TLD。为此启用调试日志记录   记录器获取已扫描但没有TLD的JAR的完整列表   发现在他们身上。在扫描期间跳过不需要的JAR可以改善   启动时间和JSP编译时间。 2017年5月13日19:29:55.784信息   [HTTP-NIO-8088-EXEC-3]   com.sun.jersey.api.core.PackagesResourceConfig.init扫描root   包中的资源和提供者类:
  com.harsha.app.services 13-May-2017 19:29:55.881 INFO   [HTTP-NIO-8088-EXEC-3]   com.sun.jersey.server.impl.application.WebApplicationImpl._initiate   启动Jersey应用程序,版本'Jersey:1.19.1 03/11/2016   02:08 PM'13-May-2017 19:29:56.304 SEVERE [http-nio-8088-exec-3]   com.sun.jersey.server.impl.application.RootResourceUriRules。该   ResourceConfig实例不包含任何根资源类。   2017年5月13日19:29:56.313 INFO [http-nio-8088-exec-3]   org.apache.catalina.startup.HostConfig.deployWAR部署web   应用程序归档C:\ Program Files \ Apache Software Foundation \ Tomcat   8.0 \ webapps \ harsha.war已经完成了6,475毫秒

AmazonS3Operation Class:

package com.harsha.app.servlet.file;

import java.io.File;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.harsha.app.constant.Constant;

public class AmazonS3DriveOperation {

    AWSCredentials credentials;
    AmazonS3 s3Client;

    public AmazonS3DriveOperation() {
        s3Authorization();
    }

    public void s3Authorization() {
        credentials = new BasicAWSCredentials(Constant.ACCESS_KEY_ID, Constant.SECRET_ACCESS_KEY);
        s3Client = new AmazonS3Client(credentials);
    }

    public void s3FileUpload(String bucketName, String fileName, File file) {
        s3Client.putObject(bucketName, fileName, file);
    }

    public S3Object s3FileDownload(String bucketName, String fileName) {
        GetObjectRequest request = new GetObjectRequest(bucketName, fileName);
        S3Object s3Object = s3Client.getObject(request);
        return s3Object;
    }

    public boolean s3FileDelete(String bucketName, String fileName) {
        try {
            DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucketName, fileName);
            s3Client.deleteObject(deleteObjectRequest);
            return true;
        }
        catch (AmazonClientException e) {
            e.printStackTrace();
            return false;
        }
    }

}

DataDeleteServlet类:

package com.harsha.app.servlet.file;

import java.io.File;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.harsha.app.constant.Constant;
import com.harsha.app.database.DBManager;
import com.harsha.app.database.DataUpload;

/**
 * Servlet implementation class DataFileDelete
 */
@WebServlet("/DataFileDelete")
public class DataFileDelete extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public DataFileDelete() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String fileName = request.getParameter("fileName");
        String filePath = Constant.DATA_DRIVE + fileName;
        String serverDocumentsId = request.getParameter("serverDocumentsId");

        fileName = Constant.BASE_UPLOAD_FOLDER + Constant.SUFFIX + fileName;

        DBManager dbManager = new DBManager();
        System.out.println(filePath);
        RequestDispatcher rd = request.getRequestDispatcher("adminUploadExcel.jsp");
        AmazonS3DriveOperation amazon = new AmazonS3DriveOperation();
        if(amazon.s3FileDelete(Constant.BUCKET_NAME, fileName)) {
            DataUpload.deleteFileFromServer(serverDocumentsId, dbManager);
            System.out.println("Done");
            request.setAttribute("msg", "Data Delete Successful");
        }
        else {
            request.setAttribute("msg", "Data Delete Unsuccessful");
            System.out.println("Not Done");
        }
        dbManager.close();
        rd.forward(request, response);

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

DataFileUploadDownload Servlet类:

package com.harsha.app.servlet.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.codehaus.jettison.json.JSONArray;

import com.amazonaws.services.s3.model.S3Object;
import com.harsha.app.constant.Constant;
import com.harsha.app.database.DBManager;
import com.harsha.app.database.DataUpload;
import com.harsha.app.util.ExcelRead;

@WebServlet(name = "DataFileUploadDownload",urlPatterns = {"/DataFileUploadDownload/*"})
public class DataFileUploadDownload extends HttpServlet {
    private static final long serialVersionUID = 1L;
    int BUFFER_LENGTH = 4096;

    String fileNameAssigned = "";
    String fileNameGiven = "";
    String excelType = "";



    public DataFileUploadDownload() {
        super();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filePath = request.getRequestURI();

        String fileName = filePath.replace(Constant.REPLACE_URL,"");                
        AmazonS3DriveOperation amazon = new AmazonS3DriveOperation();

        fileName = Constant.BASE_UPLOAD_FOLDER + Constant.SUFFIX + fileName;

        S3Object s3Object = amazon.s3FileDownload(Constant.BUCKET_NAME, fileName);
        InputStream input = s3Object.getObjectContent();

        response.setContentLength((int) s3Object.getObjectMetadata().getContentLength());
        response.setContentType(new MimetypesFileTypeMap().getContentType(s3Object.getObjectMetadata().getContentType()));

        OutputStream output = response.getOutputStream();
        byte[] bytes = new byte[BUFFER_LENGTH];
        int read = 0;
        while ((read = input.read(bytes, 0, BUFFER_LENGTH)) != -1) {
            output.write(bytes, 0, read);
            output.flush();
        }

        input.close();
        output.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        DBManager dbManager = new DBManager();
        out.println("Hello<br/>");

        boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
        if (!isMultipartContent) {
            out.println("You are not trying to upload<br/>");
            return;
        }
        out.println("You are trying to upload<br/>");

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> fields = upload.parseRequest(request);
            out.println("Number of fields: " + fields.size() + "<br/><br/>");
            Iterator<FileItem> it = fields.iterator();
            if (!it.hasNext()) {
                out.println("No fields found");
                return;
            }
            out.println("<table border=\"1\">");
            while (it.hasNext()) {
                out.println("<tr>");
                FileItem fileItem = it.next();
                boolean isFormField = fileItem.isFormField();
                if (isFormField) {
                    out.println("<td>regular form field</td><td>FIELD NAME: " + fileItem.getFieldName() + 
                            "<br/>STRING: " + fileItem.getString()
                            );
                    out.println("</td>");
                    if(fileItem.getFieldName().equals("fileName"))
                        excelType = fileItem.getString();
                } else {
                    out.println("<td>file form field</td><td>FIELD NAME: " + fileItem.getFieldName() +
                            //"<br/>STRING: " + fileItem.getString() +
                            "<br/>NAME: " + fileItem.getName() +
                            "<br/>CONTENT TYPE: " + fileItem.getContentType() +
                            "<br/>SIZE (BYTES): " + fileItem.getSize() +
                            "<br/>TO STRING: " + fileItem.toString()
                            );
                      fileNameGiven = fileItem.getName();
                     fileNameAssigned = DataUpload.getCurrentTime() + "" + getFileName(fileNameGiven);
                    String path = Constant.DATA_DRIVE + ""+ fileNameAssigned;
                    System.out.println(path);

                    //File fileUpload = new File(path);

                    fileNameAssigned = Constant.BASE_UPLOAD_FOLDER + Constant.SUFFIX + fileNameAssigned;

                    File file = new File(fileNameAssigned);
                    fileItem.write(file);
                    AmazonS3DriveOperation amazon = new AmazonS3DriveOperation();
                    amazon.s3FileUpload(Constant.BUCKET_NAME, fileNameAssigned, file);
                    out.println("</td>");
                }
                out.println("</tr>");
            }
            out.println("</table>");
            DataUpload.insertNewUploadFileDetails(fileNameGiven, fileNameAssigned, dbManager);
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        uploadExcelData(fileNameAssigned, excelType, dbManager);
        dbManager.close();
        RequestDispatcher rd = request.getRequestDispatcher("adminUploadExcel.jsp");
        request.setAttribute("msg", "Data Upload Successful");
        rd.forward(request, response);
    }

    private String getFileName(String fileName) {
        return fileName.substring(fileName.indexOf('.')).trim();
    }

    private void uploadExcelData(String fileNameAssigned, String excelType, DBManager dbManager) throws IOException {
        ExcelRead er = new ExcelRead();
        if(excelType.equals("Family")) {
            JSONArray jArray = er.readBooksFromExcelFile(fileNameAssigned, excelType);
            DataUpload.uploadFamilyArchieve(jArray, dbManager);
        }           
        else if(excelType.equals("Member")) {
            JSONArray jArray = er.readBooksFromExcelFile(fileNameAssigned, excelType);
            DataUpload.uploadMemberArchieve(jArray, dbManager);
        }           
    }

}

ExcelFileCreating并下载Servlet类:

package com.harsha.app.servlet.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jettison.json.JSONArray;

import com.amazonaws.services.s3.model.S3Object;
import com.harsha.app.constant.Constant;
import com.harsha.app.database.DBHandler;
import com.harsha.app.database.DBManager;
import com.harsha.app.util.ExcelRead;

/**
 * Servlet implementation class TableDataDownload
 */
@WebServlet(name = "TableDataDownload",urlPatterns = {"/TableDataDownload/*"})
public class TableDataDownload extends HttpServlet {
    private static final long serialVersionUID = 1L;
int BUFFER_LENGTH = 4096;

String fileNameAssigned = "";
String fileNameGiven = "";
String excelType = "";


    /**
     * @see HttpServlet#HttpServlet()
     */
    public TableDataDownload() {
        super();
    }

    public JSONArray agricultureImpactReport() {
        DBManager dbManager=new DBManager();
        JSONArray jsonArray = DBHandler.getAgricultureImpactReport(0, new Date().getTime()/1000, dbManager);
        dbManager.close();
        return jsonArray;
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filePath = request.getRequestURI();
        System.out.println(filePath);

        String impactName = filePath.replace(Constant.REPLACE_URL2,"");
        System.out.println(impactName);

        JSONArray jsonArray = new JSONArray();

        if(impactName.equals("agriculture.xls")) {
            jsonArray = agricultureImpactReport();
            filePath = ExcelRead.generateExcelReport(jsonArray, impactName);
        }           
        System.out.println(jsonArray.toString());
        System.out.println("filepath=" + filePath);
        String path = Constant.DATA_DRIVE + filePath;
        System.out.println("path=" + path);

        String fileName = filePath;
        /*File file = new File(path);
        InputStream input = new FileInputStream(file);

        response.setContentLength((int) file.length());
        response.setContentType(new MimetypesFileTypeMap().getContentType(file));
        */

        fileName = Constant.BASE_UPLOAD_FOLDER + Constant.SUFFIX + fileName;
        AmazonS3DriveOperation amazon = new AmazonS3DriveOperation();

        S3Object s3Object = amazon.s3FileDownload(Constant.BUCKET_NAME, fileName);
        InputStream input = s3Object.getObjectContent();

        response.setContentLength((int) s3Object.getObjectMetadata().getContentLength());
        response.setContentType(new MimetypesFileTypeMap().getContentType(s3Object.getObjectMetadata().getContentType()));

        OutputStream output = response.getOutputStream();
        byte[] bytes = new byte[BUFFER_LENGTH];
        int read = 0;
        while ((read = input.read(bytes, 0, BUFFER_LENGTH)) != -1) {
            output.write(bytes, 0, read);
            output.flush();
        }

        input.close();
        output.close();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

Web.xml中:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Yushu</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>com.harsha.app.services</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/api/*</url-pattern>
  </servlet-mapping>
</web-app>

List of Jar Configured in Project. All present in lib folder under WEB-INF

我的pom.ml中的依赖项:

<dependencies>

    <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk -->
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk</artifactId>
        <version>1.11.127</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-core -->
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-core</artifactId>
        <version>1.11.127</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-collections4</artifactId>
        <version>4.1</version>
    </dependency>       
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.16</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.16</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.5</version>
    </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.25</version>
        </dependency>     
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>
          <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20141113</version>
          </dependency>
          <dependency>
              <groupId>com.sun.mail</groupId>
              <artifactId>javax.mail</artifactId>
              <version>1.4.5</version>
            </dependency>
    <dependency>
      <groupId>com.lowagie</groupId>
      <artifactId>itext</artifactId>
      <version>2.1.7</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-core-asl</artifactId>
      <version>1.9.2</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-jaxrs</artifactId>
      <version>1.9.2</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.2</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-xc</artifactId>
      <version>1.9.2</version>
    </dependency>
    <dependency>
      <groupId>javax.el</groupId>
      <artifactId>javax.el-api</artifactId>
      <version>2.2.4</version>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-client</artifactId>
      <version>1.19.1</version>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-core</artifactId>
      <version>1.19.1</version>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-json</artifactId>
      <version>1.19.1</version>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-server</artifactId>
      <version>1.19.1</version>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-servlet</artifactId>
      <version>1.19.1</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jettison</groupId>
      <artifactId>jettison</artifactId>
      <version>1.1</version>
    </dependency>
    <dependency>
      <groupId>javax.ws.rs</groupId>
      <artifactId>jsr311-api</artifactId>
      <version>1.1.1</version>
    </dependency>

我尝试了许多解决方案,如:

  • 包含每个API的Jar文件。
  • 在pom中包含maven的依赖项。
  • 检查Jersey Servlet容器和服务根目录的Web.xml packkage。
  • 检查创建的多个服务的similr URL 歧义。
  • Java和Tomcat版本已检查。 AWS和我的locak机器版本是 mathcing。

仍然没有修复错误。请帮我解决一下这个。在此先感谢。

1 个答案:

答案 0 :(得分:0)

如果您正在尝试使用Jersey,为什么使用Servlets?这不是泽西岛的工作方式。使用Jersey,您可以使用@Path注释资源类。例如

package com.harsha.app.services;

@Path("pets")
public class PetsResource {
    @GET
    @Path("{id}")
    @Produces("application/json")
    public Pet get(@PathParam("id") long id) {
        ...
    }

    @POST
    @Consumes("application/json")
    public Response create(Pet pet) {
        ...
    }
}

注意顶部的包裹。对于使用@Path注释的类,Jersey将扫描该包(因为这是您在web.xml中配置的包),因此它可以将其注册为资源类。这就是您收到错误消息“没有根资源类”的原因。

我甚至不打算尝试解释上面代码的作用。这个话题太广泛了。您将需要通过一些教程和文档来真正学习这些东西。但你目前所做的完全错误。