FilesService.java
package com.training.rs;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
@ApplicationPath("/")
@Path("/")
public class FilesService extends Application {
private static int lastId = 0;
private Map<String, File> files = new HashMap<String, File>();
@GET
@Path("/ids")
@Produces(MediaType.APPLICATION_XML)
public Collection<Id> getFileIds() {
return transformToIdObject();
}
@GET
@Path("/file/{id}")
public File getFile(@PathParam("id") String id) {
return files.get(id);
}
@GET
@Path("/file/response/{id}")
public Response getResponseWithFile(@PathParam("id") String id) {
File file = files.get(id);
ResponseBuilder responseBuilder = Response.ok((Object) file);
responseBuilder.header("Content-Disposition", "attachment; filename="
+ file.getName());
return responseBuilder.build();
}
@PUT
@Path("/file")
public String putFile(File file) {
String generatedId = String.valueOf(lastId++);
files.put(generatedId, file);
return generatedId;
}
@DELETE
@Path("/file/{id}")
public void deleteFile(@PathParam("id") String id) {
files.remove(id);
}
private Collection<Id> transformToIdObject() {
return Collections2.transform(files.keySet(),
new Function<String, Id>() {
public Id apply(String id) {
return new Id(id);
}
});
}
}
Id.java
package com.training.rs;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Id {
private String id;
public Id() {
}
public Id(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.training</groupId>
<artifactId>jax_rs_files</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
</dependencies>
</project>