Klasse aufrufen aus Servlet


#1

Hallo Zusammen, ich hoffe sehr das mir hier jemand weiterhelfen kann, da ich schon schier am verzweifeln bin :frowning:

Ich muss aus einem Servlet einer Klasse aufrufen um anschlie├čend den return einer dieser Methoden wieder verarbeiten zu k├Ânnen. Da ich mit Servlets noch wenig zu tun hatte verzweifel ich hier gerade.

Mein Servlet sieht wie folgt aus:

public class ReceiveMessageServlet extends HttpServlet {

@SuppressWarnings({ "unchecked", "static-access" })
@Override
public final void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    // Validating unique subscription token before processing the message
    String subscriptionToken = System.getProperty(Constants.BASE_PACKAGE + ".subscriptionUniqueToken");
    if (!subscriptionToken.equals(req.getParameter("token"))) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().close();
        return;

    }

    ServletInputStream inputStream = req.getInputStream();

    // Parse the JSON message to the POJO model class
    JsonParser parser = JacksonFactory.getDefaultInstance().createJsonParser(inputStream);
    parser.skipToKey("message");
    PubsubMessage message = parser.parseAndClose(PubsubMessage.class);

    // Store the message in the datastore
    Entity messageToStore = new Entity("PubsubMessage");
    messageToStore.setProperty("message", new String(message.decodeData(), "UTF-8"));
    messageToStore.setProperty("receipt-time", System.currentTimeMillis());
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    datastore.put(messageToStore);

    // Invalidate the cache
    MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService();
    memcacheService.delete(Constants.MESSAGE_CACHE_KEY);

    // Acknowledge the message by returning a success code
    resp.setStatus(HttpServletResponse.SC_OK);



    resp.getWriter().close();
}

}

Und die Klasse so:

Public class Program {
   // public static JSONObject inpParms;
    public static String apikey;
    public static String apiurl;
    public static String jsonBody;

    /**
     * Read the JSON schema from the file rrsJson.json
     * 
     * @param filename It expects a fully qualified file name that contains input JSON file
     */     
    public static void readJson(String filename) {
        try {
            File apiFile = new File(filename);
            @SuppressWarnings("resource")
            Scanner sc = new Scanner(apiFile);
            jsonBody = "";
            while (sc.hasNext()) {
                jsonBody += sc.nextLine()+"\n";
            }
        }
        catch (Exception e){
            System.out.println(e.toString());
       }
    }

    /**
     * Read the API key and API URL of Azure ML request response REST API
     * 
     * @param filename fully qualified file name that contains API key and API URL
     */ 
     public static void readApiInfo(String filename) {

        try {
            File apiFile = new File(filename);
            @SuppressWarnings("resource")
            Scanner sc = new Scanner(apiFile);

            apiurl = sc.nextLine();
            apikey = sc.nextLine();

        }
        catch (Exception e){
            System.out.println(e.toString());
       }

    }

    /**
     * Call REST API for retrieving prediction from Azure ML 
     * @return response from the REST API
     */ 
    @SuppressWarnings("deprecation")
    public static String rrsHttpPost() {

        HttpPost post;
        HttpClient client;
        StringEntity entity;

        try {
            // create HttpPost and HttpClient object
            post = new HttpPost(apiurl);
            client = HttpClientBuilder.create().build();

           // setup output message by copying JSON body into 
           // apache StringEntity object along with content type
           entity = new StringEntity(jsonBody, HTTP.UTF_8);
           entity.setContentEncoding(HTTP.UTF_8);
           entity.setContentType("text/json");


           // add HTTP headers
           post.setHeader("Accept", "text/json");
           post.setHeader("Accept-Charset", "UTF-8");

           // set Authorization header based on the API key
           post.setHeader("Authorization", ("Bearer "+apikey));
           post.setEntity(entity);

           // Call REST API and retrieve response content
           HttpResponse authResponse = client.execute(post);

           return EntityUtils.toString(authResponse.getEntity());

        }
        catch (Exception e) {

            return e.toString();
       }

   }

    /**
     * @param args the command line arguments specifying JSON and API info file names
     */
    public static void main(String[] args) {
        // check for mandatory argments. This program expects 2 arguments 
        // first argument is full path with file name of JSON file and 
        // second argument is full path with file name of API file that contains API URL and API Key of request response REST API
        if (args.length < 2) {
            System.out.println("Incorrect usage. Please use the following calling pattern");
            System.out.println("java AzureML_RRSApp <jsonFilename> <apiInfoFilename>");
        }

        try {

            // read JSON file name
           String jsonFile = "rrsJson.json";
            // read API file name
            String apiFile = "apiInfo.txt";

            // call method to read API URL and key from API file
            readApiInfo(apiFile);

            // call method to read JSON input from the JSON file
          readJson(jsonFile);

            // print the response from REST API
         System.out.println(rrsHttpPost());
         }
        catch (Exception e) {
            System.out.println(e.toString());
        }
   }
}

Es geht um die Methode: public static String rrsHttpPost()

Wie kann ich den R├╝ckgabewert in mein Servlet ├╝bernehmen und wie rufe ich diese Klasse auf damit sie l├Ąuft?

Ich bedanke mich f├╝r eure Hilfe.


#2

OhÔÇŽ Ich will dir in keinsterweise zu Nahe treten, aber hast du dich auch mal mit Java befasst, bevor du dich mit Servlets befasst hast? NajaÔÇŽ wenn man Java f├╝r die Programmierung von Servlets lernt, ist das Ok. Aber an Grundlagen kommt man dennoch nicht vorbei.

Statische Methoden ruft man auf dem jeweiligen Klassennamen auf. F├╝r deinen Fall gilt also:

String rssHttpPost = Program.rrsHttpPost();

Das ist eine essentielle Java-Grundlage, die man auch dort beherzigen sollte, wo

@SuppressWarnings({ "unchecked", "static-access" })

im Code steht. :wink: