com.ovea.tadjin.util.jersey.JerseyServlet Maven / Gradle / Ivy
The newest version!
/**
* Copyright (C) 2011 Ovea
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ovea.tadjin.util.jersey;
import com.google.inject.Injector;
import com.mycila.inject.web.HttpContext;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import org.eclipse.jetty.util.IO;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Mathieu Carbou ([email protected])
*/
public class JerseyServlet extends GuiceContainer {
@Inject
public JerseyServlet(Injector injector) {
super(injector);
}
@Override
public void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
// first consumes requets parameters before jersey processing.
// See this issue: http://jersey.576304.n2.nabble.com/Jersey-empties-request-getParameterMap-with-POST-td4254182.html
request.getParameterMap();
final HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(request) {
ByteArrayOutputStream baos;
@Override
public ServletInputStream getInputStream() throws IOException {
if (baos == null) {
baos = new ByteArrayOutputStream();
IO.copy(request.getInputStream(), baos);
}
return new ServletInputStream() {
InputStream in = new ByteArrayInputStream(baos.toByteArray());
@Override
public int read() throws IOException {
return in.read();
}
};
}
@Override
public String toString() {
return HttpServletRequestWrapper.class.getSimpleName() + "[" + getRequestURI() + "]";
}
};
HttpContext.change(wrappedRequest, response);
try {
super.service(wrappedRequest, response);
} finally {
HttpContext.end();
}
}
}