package com.llgc; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; /* import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; */ import org.json.JSONException; import org.json.JSONObject; @Path("/euro") public class Serveur { // Ici, le path est cumulatif avec le "/euro". // On fait donc bien référence au chemin "/euro/{f}" avec {f} : un nombre // flottant @Path("{f}") // Méthode GET @GET // Mime Type en sortie @Produces(MediaType.APPLICATION_XML) // Mime Type en entrée @Consumes(MediaType.APPLICATION_XML) // On dit que le f est extrait du path et que c'est un double. public String traitementXml(@PathParam("f") Double f) { return "" + f / 6.65 + "" + f + ""; } @Path("{f}") @GET @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public String traitementJson(@PathParam("f") Double f) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("Francs", f); jsonObject.put("Euros", f / 6.65); return jsonObject.toString(); } @Path("{f}") @GET @Produces(MediaType.TEXT_HTML) @Consumes(MediaType.TEXT_HTML) public String traitementPlainHtml(@PathParam("f") Double f) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("FrancsHMTLHTMLHTML", f); jsonObject.put("Euris", f / 6.65); return jsonObject.toString(); } @GET @Path("/down") @Produces("image/png") // Le client veut télécharger public Response download() { File file = new File("image.png"); ResponseBuilder response = Response.ok((Object) file); response.header("Content-Disposition", "attachment; filename=test.png"); return response.build(); } @Path("/upload") @POST @Consumes(MediaType.MULTIPART_FORM_DATA) // Le client veut uploader public Response upload(@FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) { String uploadedFileLocation = "./" + "Jersey_" + fileDetail.getFileName(); saveToFile(uploadedInputStream, uploadedFileLocation); String output = "File uploaded via Jersey based RESTFul Webservice to: " + uploadedFileLocation; return Response.status(200).entity(output).build(); } private void saveToFile(InputStream uploadedInputStream, String uploadedFileLocation) { try { OutputStream out = null; int read = 0; byte[] bytes = new byte[1024]; out = new FileOutputStream(new File(uploadedFileLocation)); while ((read = uploadedInputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }