有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

web服务如何将文件(txt)从java上传到restful web服务?

I want to upload txt file from java application(software) to restful web-service , Because inside txt file i have list of sql query to execute. So , I want to upload file into web-service first then execute query line by line to database.

我将txt文件转换为列表对象,然后再次转换为字符串并传递它,但未能成功

这是Web服务代码

package com.java.webservice;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.sun.jersey.api.client.WebResource;

@Path("UploadFile")
public class UploadFile {

    private List<String> storedQueries = new ArrayList<String>();

    private Connection conn = null;
    // private PreparedStatement pstm = null;
    private Statement pstm = null;
    private ResultSet rs = null;
    private String q = "";

    // @GET here defines, this method will method will process HTTP GET
    // requests.
    @GET
    // @Path here defines method level path. Identifies the URI path that a
    // resource class method will serve requests for.
    @Path("/getTest")
    // @Produces here defines the media type(s) that the methods
    // of a resource class can produce.
    @Produces(MediaType.APPLICATION_JSON)
    // @PathParam injects the value of URI parameter that defined in @Path
    // expression, into the method.

    public Response getTest(@QueryParam("name") String name) {
        // String name = "Lokendra Pun ,Java Engineer";
        System.out.println("Your Name IS: " + name);

        java.util.StringTokenizer st = new java.util.StringTokenizer(name, ",");
        java.util.ArrayList newArrayList = new java.util.ArrayList();
        while (st.hasMoreTokens()) {
            // the trim() below may not always be desired or necessary
            newArrayList.add(st.nextToken().trim());
        }

        // this if statement only necessary because a String created from
        // ArrayList.toString() ends up as "[1, 2, 3, 4]" not, "1, 2, 3, 4"

        if (newArrayList.size() == 1) {
            // remove [] around item
            int length = ((String) newArrayList.get(0)).length();
            newArrayList.set(0, ((String) newArrayList.get(0)).substring(1, length - 1));
        } else if (newArrayList.size() > 1) {
            // remove '[' in first item and ']' in last
            int lastIndex = newArrayList.size() - 1;
            String oldString = (String) newArrayList.get(0);
            String newString = oldString.substring(1, oldString.length());

            newArrayList.set(0, newString);
            oldString = (String) newArrayList.get(lastIndex);

            newString = oldString.substring(0, oldString.length() - 1);
            newArrayList.set(newArrayList.size() - 1, newString);
        }

        System.out.println("newArrayList->" + newArrayList.toString());
        System.out.println("==================");
        for (int i = 0; i < newArrayList.size(); i++) {
            System.out.println("Name" + i + " :" + newArrayList.get(i));
        }
        System.out.println("==================");

        return Response.status(200).entity(name).build();
    }

    /**
     * 
     * 
     * method to get file name from remote server and process query into
     * database
     * 
     * 
     * 
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/getUploadQuery")
    public Response getUploadQuery(@QueryParam("file_name") String file_name,
            @QueryParam("database_name") String database_name) {
        System.out.println("I am inside getTeacher Method");
        String list = null;
        try {
            conn = getConnection(database_name);

            if (conn != null) {
                try {
                    for (String line : Files.readAllLines(Paths.get(file_name))) {
                        storedQueries.add(line);
                        System.out.println(line);
                    }

                    for (int i = 0; i < storedQueries.size(); i++) {
                        System.out.println("Looping Query Length is: " + storedQueries.size());
                        System.out.println("Connection Object Inside Loop : " + conn);
                        pstm = conn.createStatement();
                        System.out.println("Looping Size now : " + i);
                        if (!storedQueries.get(i).equals("")) {
                            System.out.println("Query Before Executed is: " + storedQueries.get(i));
                            // pstm =
                            // conn.prepareStatement(storedQueries.get(i));
                            // pstm.executeUpdate();
                            pstm.addBatch(storedQueries.get(i));
                            pstm.executeBatch();
                        }

                    }

                    pstm.close();
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                list = "true";
            } else {
                list = "false";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return Response.status(200).entity(list).build();
    }

    /**
     * 
     * method to connect to remote server database according to db and school
     * name
     * 
     * @param database_name
     * @return
     */
    public Connection getConnection(String database_name) {
        System.out.println("Database Name before Connection: " + database_name);
        try {
            Class.forName("com.mysql.jdbc.Driver");
            // Setup the connection with the DB
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost/" + database_name + "?" + "user=root&password=java@安卓2016");
            System.out.println(conn);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return conn;
    }
}

下面是从java应用程序调用服务的代码

package WSserviceCall;

import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TestMain {

    public static final String BASE_URI = "http://localhost:8080/MovieGalaxyService";
    public static final String PATH_TEST = "/UploadFile/getTest";
    public static final String PATH_LOAD_FILE = "/UploadFile/getUploadQuery";
    public static final String PATH_AGE = "/UploadFile/age/";

    public static void main(String[] args) {
        try {
            // TODO Auto-generated method stub
            List<String> storedQueries = new ArrayList<String>();
            String currentDirectory = System.getProperty("user.dir");
            String file_name = currentDirectory + "/databaseBackupScript.txt";

            String name = "Lokendra Pun Param";
            String age ="26";

            try{
               for (String line : Files.readAllLines(Paths.get(file_name))) {
                    storedQueries.add(line);
                    System.out.println(line);
                }
            }catch(Exception e){
                e.printStackTrace();
            }

           // String names = ""+aa;
            //System.out.println("Array Objec is: "+aa);
            //System.out.println("String Objects is: "+aa.toString());
            ClientConfig config = new DefaultClientConfig();
            Client client = Client.create(config);
            WebResource resource = client.resource(BASE_URI);

            String param = storedQueries.toString();
            String temp_uri  = URLEncoder.encode(param, "UTF-8");
            WebResource testResource = resource.path(PATH_TEST).
                    queryParam("name",temp_uri);

            //WebResource testResource = resource.path(PATH_TEST);
            //      System.out.println("Client Response \n"
            //      + getClientResponse(testResource));
            //      System.out.println("Response \n" + getResponse(testResource) + "\n\n");
            String testValue = getResponse(testResource);
            System.out.println("Test Resource Value is : "+testValue);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(TestMain.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
    * Returns client response.
    * e.g : 
    * GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra 
    * returned a response status of 200 OK
    *
    * @param service
    * @return
    */
    private static String getClientResponse(WebResource resource) {
        return resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class).toString();
    }

    /**
    * Returns the response as JSON data
    * e.g : status : true or false
    * 
    * @param service
    * @return
    */
    private static String getResponse(WebResource resource) {
        return resource.accept(MediaType.APPLICATION_JSON).get(String.class);
    }

}

共 (0) 个答案