Jersey, using HTML file instead of HTML string - java

Currently I need to programm a RESTful Webservice in Java and I'm using Grizzly server as my server and I'm using Jersey for the HTML code generation.
This is my Grizzly server:
public static void main(String[] args) throws IOException {
URI baseUri = URI.create("http://localhost:9998");
final ResourceConfig resourceConfig = new ResourceConfig(homepage.class);
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig);
System.out.println("Starting grizzly ...");
JOptionPane.showMessageDialog(null, "Stop Server");
server.shutdownNow();
}
And this is my current homepage code:
#Path("")
public class homepage {
#GET
#Produces("text/html")
public String sayHelloInHtml() {
return "<html><body><h2>Hello World</h2></body></html>";
}
}
Right now I'm using a string for my HTML code but is their a way to use a HTML file instead?
Also how can I create a button that triggers a Java method on click? I know how to create a button but I don't know how to make the event handler to trigger the Java method on click.

Related

How to create a multipart form post request handler in vertx

Hello I am using vertx in java on a standalone app to read a port in my web app. I want to get the post data from a form.
My web app has a form with a post method that I am looking to read.
My logic is
Create verticle
Create http Server
Create handler request ( it does not take all the parameters in my
code)
Listen to httpServer
Expect Multipart Request in Handler
Multimap and get form attributes
I dont know what I am missing , I am new to vertx .
For some reason I cannot post code on here.
My code:
https://pastebin.com/A1hjXFb6
Make sure that your HTML form is having enctype="multipart/form-data" attribute.
Then in your vertx code:
public class loginLogic extends AbstractVerticle {
//Vertx vertx;
private HttpServer httpServer = null;
#Override
public void start() {
Router router = Router.router(vertx);
router.route().handler(BodyHandler.create().setUploadsDirectory("uploads"));
router.post("/form").handler(ctx -> {
ctx.response().putHeader("Content-Type", "text/plain");
ctx.response().setChunked(true);
for (FileUpload f : ctx.fileUploads()) {
System.out.println("f");
ctx.response().write("Filename: " + f.fileName());
ctx.response().write("\n");
ctx.response().write("Size: " + f.size());
}
ctx.response().end();
});
vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}
}

Grizzly PUT request with json body fails

I have the java server on the cloud running. Everything is ok with GET and DELETE requests, but not ok with the PUT request. I have the following PUT request handler
#PUT
#JSONP(queryParam = "callback")
public void putEvent(String eventJson) throws Exception {
Event event = new ObjectMapper().readValue(eventJson, Event.class);
EventDao.getInstance().saveOrUpdateEvent(event);
}
And here is the Server class
public static final String BASE_API_URI = "http://localhost:8080/myrest-api/";
public boolean getFileCacheEnabled() {
return false;
}
public static void main(String[] args) throws Exception {
Server server = new Server();
final HttpServer httpServer = server.startServer();
System.out.println("Press enter to stop the server...");
System.in.read();
httpServer.shutdown();
}
public HttpServer startServer() {
final ResourceConfig rc = new ResourceConfig().packages("com.myrest.events");
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_API_URI), rc);
server.getServerConfiguration().addHttpHandler(getHttpHandler(), "/page");
return server;
}
public HttpHandler getHttpHandler() {
StaticHttpHandler handler = new StaticHttpHandler("src/main/resources/webapp/");
handler.setFileCacheEnabled(getFileCacheEnabled());
return handler;
}
When I send PUT request with following JSON body
{
"name":"SimpleName",
"description":"SimpleDescription",
"author":"Me"
}
I get
Status: 500 Request failed
Although when I deploy the app locally, and try the same everything is fine. Btw I tried POST request instead, I get the same error.

How to call #SendTo from Normal Request Call i.e #RequestMapping

I have implemented Web Socket using Spring MVC and it is working fine for me i.e work from one browser to another browser which is open for those socket using this code.
#MessageMapping("/hello")
#SendTo("/topic/greetings")
public HelloMessage greeting(HelloMessage message) throws Exception {
Thread.sleep(3000); // simulated delay
return message;
}
Can any one help me for who to call #SendTo("/topic/greetings") from normal api controller.I have try using this but it is not working for me
#RequestMapping(value = "/sendMessage")
#SendTo("/topic/greetings")
public HelloMessage sendMessage() throws Exception {
return new HelloMessage((int) Math.random(), "This is Send From Server");
}
any idea for this?
Thanks
I have found solution for that
#Autowired
private SimpMessagingTemplate template;
#RequestMapping(value = "/sendMessage")
public void sendMessage() throws Exception {
this.template.convertAndSend("/topic/greetings", new HelloMessage(
(int) Math.random(), "This is Send From Server"));
}
by using this we can send message to open WebSocket.
Thanks

Restlet and consuming/storing files

How would one handle consuming an attachment from a client POST/PUT request on the server side and store that file in a local folder, all using Restlet ?
My thoughts are as follows:
Setup Server as follows:
new MailServerComponenet.start();
public MailServer(){
getServers().add(Protocol.HTTP, 8111);
getDefaultHost().attachDefault(new MailServer());
server.getContext().getParameters().set("tracing", "true");
}
#Put
public void store(Form form){
// *And here is where I am not sure*
}
Thanks for any insight and help in advance.
Here are the following steps you should follow to implement your Restlet application:
Create a component
Component component = new Component();
Create an application and attach it on the component
component.getServers().add(Protocol.HTTP, 8182);
Application application = new MyApplication();
component.getDefaultHost().attachDefault(application);
component.start();
Configure the application within the method createInboundRoot (create a router and attach server resource on it)
public class MyApplication extends Application {
#Override
public Restlet createInboundRoot() {
Router router = new Router();
router.attach("/test", MyServerResource.class);
return router;
}
}
Implement the server resources
public class MyServerResource extends ServerResource {
#Post
public Representation handlePost(Representation repr) {
(...)
}
}
Now the global frame is implemented, I would wonder how you would send the content to Restlet. Is it simple binary content within the request payload or multi-part content?
Binary content
#Post
public Representation handlePost(FileRepresentation fileRepr) {
fileRepr.write(new FileOutputStream(
new File("/tmp/myfile.txt")));
return null;
}
Multipart content. You can have a look at this answer in this case: File Upload with Description in Restlet
Hope it helps you,
Thierry

Using jax-ws client methods in Weblogic enviroment

I faced with problem using jax ws client with Weblogic 10.3. I generate webservice stubs and test connection with webservice in simple java project. All works fine. But when I pack this project in jar file and add it to my main project which contains other jars and running on weblogic I get:
java.lang.NoSuchMethodError: org.home.client.AddressWS.getAddressByRequestAsync(ILjava/lang/String;)Ljavax/xml/ws/Response;
This exception was thrown when I tried to call webservice stub`s method.
public class MyServiceImpl implements MyService {
private AddressWS service;
private static final String ENDPOINT = "http://endpoint.address.ws.company.org/";
private static final String SERVICE_NAME = "AddressWSImplService";
#Override
public void setSOAPServiceURL(String serviceURL) {
URL url = createURL(serviceURL);
QName qName = new QName(ENDPOINT, SERVICE_NAME);
AddressWSImplService addressWSImplService= new AddressWSImplService(url, qName);
service = addressWSImplService.getAddressWSImplPort();
}
#Override
public String getAddressById(int id, String param) throws TimeoutException {
// NoSuchMethodError was thrown here
final Response<GetAddressById> response = service
.getAddressByIdAsync(id, param);
return (String) getValue(new Future<String>() {...});}
Any pointers will be helpfull.

Categories

Resources