web-dev-qa-db-fra.com

Comment trouver l'IP de la requête RESTful entrante en utilisant JAX-RS sur Heroku?

J'écris un Java service RESTful hébergé sur Heroku basé sur un exemple -> https://api.heroku.com/myapps/template-Java-jaxrs/clone

Mon exemple de service est:

package com.example.services;

import com.example.models.Time;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/time")
@Produces(MediaType.APPLICATION_JSON)
public class TimeService {

    @GET
    public Time get() {
        return new Time();
    }

}

Ma principale est:

public class Main {

    public static final String BASE_URI = getBaseURI();

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
        final Map<String, String> initParams = new HashMap<String, String>();
        initParams.put("com.Sun.jersey.config.property.packages","services.contracts"); 

        System.out.println("Starting grizzly...");
        SelectorThread threadSelector = GrizzlyWebContainerFactory.create(BASE_URI, initParams);
        System.out.println(String.format("Jersey started with WADL available at %sapplication.wadl.",BASE_URI, BASE_URI));
    }

    private static String getBaseURI() 
    {
        return "http://localhost:"+(System.getenv("PORT")!=null?System.getenv("PORT"):"9998")+"/";      
    }

}

Ma question est de savoir comment puis-je trouver dans mon service l'adresse IP et la combinaison de ports d'où provient la demande? J'ai lu des trucs sur @Context qui injectent javax.ws.rs.core.HttpHeaders, javax.ws.rs.core.Request, etc. Cependant, aucune adresse IP ou information de port entrante n'est présente.

Je sais que si vous implémentez com.Sun.grizzly.tcp.Adapter, vous pouvez faire quelque chose comme:

public static void main(String[] args) {
    SelectorThread st = new SelectorThread();
    st.setPort(8282);
    st.setAdapter(new EmbeddedServer());
    try {
        st.initEndpoint();
        st.startEndpoint();
    } catch (Exception e) {
        System.out.println("Exception in SelectorThread: " + e);
    } finally {
        if (st.isRunning()) {
            st.stopEndpoint();
        }
    }
}

public void service(Request request, Response response)
        throws Exception {
    String requestURI = request.requestURI().toString();

    System.out.println("New incoming request with URI: " + requestURI);
    System.out.println("Request Method is: " + request.method());

    if (request.method().toString().equalsIgnoreCase("GET")) {
        response.setStatus(HttpURLConnection.HTTP_OK);
        byte[] bytes = "Here is my response text".getBytes();

        ByteChunk chunk = new ByteChunk();
        response.setContentLength(bytes.length);
        response.setContentType("text/plain");
        chunk.append(bytes, 0, bytes.length);
        OutputBuffer buffer = response.getOutputBuffer();
        buffer.doWrite(chunk, response);
        response.finish();
    }
}

public void afterService(Request request, Response response)
        throws Exception {
    request.recycle();
    response.recycle();
}

et accès

    request.remoteAddr()

Mais j'aimerais vraiment séparer mon API RESTful d'une manière plus structurée comme dans ma première implémentation.

Toute aide serait grandement appréciée. Merci!

30
Luke

Comme l'a dit Luke, lors de l'utilisation de Heroku, l'hôte distant est le niveau d'application AWS, donc l'adresse IP EC2.

L'en-tête "X-Forwarded-For" est la réponse:

String ip = "0.0.0.0";
try {
    ip = req.getHeader("X-Forwarded-For").split(",")[0];
} catch (Exception ignored){}
11
Ethan

Vous pouvez injecter HttpServletRequest :

@GET
@Produces(MediaType.TEXT_PLAIN)
public Response getIp(@Context HttpServletRequest req) {
    String remoteHost = req.getRemoteHost();
    String remoteAddr = req.getRemoteAddr();
    int remotePort = req.getRemotePort();
    String msg = remoteHost + " (" + remoteAddr + ":" + remotePort + ")";
    return Response.ok(msg).build();
}
51
user647772

Basé sur @ user647772 et @Ethan fusion. Merci à eux ;)

injectez HttpServletRequest:

@GET
@Produces(MediaType.TEXT_PLAIN)
public Response getFromp(@Context HttpServletRequest req) {
    String from = _getUserFrom(req);
    return Response.ok(from).build();
}

private String _getUserFrom(HttpServletRequest req) {
    String xForwardedFor = req.getHeader("X-Forwarded-For");
    xForwardedFor = xForwardedFor != null && xForwardedFor.contains(",") ? xForwardedFor.split(",")[0]:xForwardedFor;
    String remoteHost = req.getRemoteHost();
    String remoteAddr = req.getRemoteAddr();
    int remotePort = req.getRemotePort();
    StringBuffer sb = new StringBuffer();
    if (remoteHost != null 
    && !"".equals(remoteHost)
    && !remoteHost.equals(remoteAddr)) {
        sb.append(remoteHost).append(" ");
    }
    if (xForwardedFor != null 
    && !"".equals(xForwardedFor)) {
        sb.append(xForwardedFor).append("(fwd)=>");
    }
    if (remoteAddr != null || !"".equals(remoteAddr)) {
        sb.append(remoteAddr).append(":").append(remotePort);
    }
    return sb.toString();
}
6
boly38