JAVA- generate scheduled JSON

2019-06-09 04:49发布

问题:

I started with this :http://examples.javacodegeeks.com/enterprise-java/rest/jersey/json-example-with-jersey-jackson/ and created a JSON on localhost:8080... I am not sure if there is any way to generate new Json every 3 or 5 second. for example just add one digit to new JSON every 3 sec.

@Path("/LNU.se")
public class EntryPoint { 
    @GET
    @Path("get")
    @Produces(MediaType.TEXT_PLAIN)
    public String test() {

        return "mahdi Test";
    }

    @POST
    @Path("post")
    @Consumes(MediaType.TEXT_PLAIN)
    public Response postTest(Track track){

        String resault = " the track is saved mahdi: "+ track;
        return Response.status(201).entity(resault).build();
    }
}

and another class:

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;


public class App {

    public static void main(String[] args) {


           ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
            context.setContextPath("/");

            Server jettyServer = new Server(8080);
            jettyServer.setHandler(context);

            ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
            jerseyServlet.setInitOrder(0);

            jerseyServlet.setInitParameter( "jersey.config.server.provider.classnames", EntryPoint.class.getCanonicalName());

                try {                   
                    jettyServer.start();
                    System.out.println(" open your browser on http://localhost:8080/LNU.se/get");
                      jettyServer.join();       

                } catch (Exception e) 
                {                   
                    e.printStackTrace();
                } finally {                 
                    jettyServer.destroy();
                }
    }
}

======================

UPDATE: -->

My server is:

package rest;
    import org.eclipse.jetty.server.Server;
    import org.eclipse.jetty.servlet.ServletContextHandler;
    import org.eclipse.jetty.servlet.ServletHolder;

    public class RestServer {
        public static void main(String[] args) throws Exception {
            ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
            context.setContextPath("/");
            Server jettyServer = new Server(8080);
            jettyServer.setHandler(context);

            ServletHolder jerseyServlet = context.addServlet(
                    org.glassfish.jersey.servlet.ServletContainer.class, "/*");
            jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
                    Calculator.class.getCanonicalName());
            try {
                jettyServer.start();
                System.out.println(" open the browser on http://localhost:8080/calculator/squareRoot?input=16");
                jettyServer.join();
            } finally {
                jettyServer.destroy();
            }
        }
    }

and this class:

package rest;

    import java.awt.event.ItemEvent;
    import javax.ws.rs.Consumes;
    import javax.ws.rs.GET;
    import javax.ws.rs.POST;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.QueryParam;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;

    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;

    @Path("calculator")
    public class Calculator {

        Result ress = new Result("mahdi84");
        public static String resul1;  
        @GET
        @Path("mahdi")
        @Produces(MediaType.APPLICATION_JSON)
        public Result  mahdi(){
            JSONObject json = new JSONObject();
            json.put("validTime", "2016-02-24T11:00:00Z");          
            JSONArray jsonArray = new JSONArray();
            JSONObject obj = new JSONObject();          
            obj.put("mcc", resul1);
            obj.put("temprature", resul1+1);
            obj.put("Humidity", resul1+10);
            jsonArray.add(obj);
            json.put("\n  JSONdata --> ", jsonArray);
        ress.setInput(Double.parseDouble(resul1));
        ress.setOutput(Double.parseDouble(resul1));
        ress.setTestVar(resul1);
        ress.setTestVar2(json);
            return ress;
        }

        @POST
        @Path("/post")
        @Consumes(MediaType.APPLICATION_JSON)
        public Response createDataInJSON(String data) { 
            resul1= data;          
            return Response.status(201).entity(result).build(); 
        }        
        static class Result{
            double input;
            double output;
            String action;
            Object testVar;
            JSONObject testVar2;
            public Result(){} 
            public JSONObject getTestVar2() {
                return testVar2;
            }
            public void setTestVar2(JSONObject testVar2) {
                this.testVar2 = testVar2;
            }

            public Object getTestVar() {
                return testVar;
            }

            public void setTestVar(Object testVar) {
                this.testVar = testVar;
            }

            public Result(String action) {
                this.action = action;
            }

            public String getAction() {
                return action;
            }

            public void setAction(String action) {
                this.action = action;
            }

            public double getInput() {
                return input;
            }

            public void setInput(double input) {
                this.input = input;
            }

            public double getOutput() {
                return output;
            }

            public void setOutput(double output) {
                this.output = output;
            }
        }
    }

and my client is:

  import java.util.Timer;
    import java.util.TimerTask;
    import com.sun.jersey.api.client.Client;
    import com.sun.jersey.api.client.ClientResponse;
    import com.sun.jersey.api.client.WebResource;
    public class JerseyClientPost extends TimerTask{
        public int cuntr = 0;       
      public static void main(String[] args) {        
        TimerTask mytask = new JerseyClientPost();
        Timer timer = new Timer();
        timer.schedule(mytask, 1000, 1000);

        }
    @Override
    public void run() {
        try {

            Client client = Client.create();
            WebResource webResource = client.resource("http://localhost:8080/calculator/post");           
            String input = Integer.toString(cuntr++);
            ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
            if (response.getStatus() != 201) {
                throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
            }
            String output = response.getEntity(String.class);

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

the client will post to the server every 1 sec and the server will generate new JSON on "http://localhost:8080/calculator/mahdi" when i try to read from "http://localhost:8080/calculator/mahdi" by apache http1.1 in another program : package HttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

public class MyHttpClient  {
    public static void main(String[] args) throws Exception{                
        HttpGet requset = new HttpGet("http://localhost:8080/calculator/mahdi");    
    DefaultHttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(requset);
            HttpEntity entity = response.getEntity();

            BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));        
            System.out.println("Reading began ... ");

            while (true) {
                String line = br.readLine();
                if (line != null && !line.isEmpty()) {
                    System.out.println(line);
                }               
            }   
    }
}

edit:

thank you I did that by using TImeTask class

it only print the first JSON! but when I refresh the weblink, it is updating on browser. would you please correct me if I am wrong? I want to see the stream of JSON on MyHttpClient, but it only shows the first JSON!

回答1:

I think you are mixing things. The server should only be a server, and not extend TimerTask. The client should call the server at a specific intervall

Do the follwing:

  1. Test your server in a web-browser. Make sure that it will respond.
  2. Write a client either in Java or javascript If you are using Java the client should have a http-client.
  3. The client should hava a timertask calling the the server at a specific intervall