Java tutorial
/* * Copyright (C) 2017 Federico Fissore * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package it.jugtorino.one.msvc.way.rabbit.reference.webapp; import javax.ws.rs.GET; 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 java.util.Collections; import java.util.HashMap; import java.util.Map; import com.rabbitmq.client.Address; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import it.jugtorino.one.msvc.way.rabbit.geoip.reference.client.RpcClient; @Path("geoip") public class GeoIPResource { private final RpcClient client; public GeoIPResource() throws Exception { ConnectionFactory factory = new ConnectionFactory(); Connection connection = factory.newConnection(Collections.singletonList(new Address("localhost"))); Channel channel = connection.createChannel(); channel.queueDeclare("geoip_service_v1", false, false, false, null); client = new RpcClient(channel, "geoip_service_v1"); client.startConsuming(); } @GET @Path("resolve/{ip}") @Produces(MediaType.APPLICATION_JSON) public Response resolveIP(@PathParam("ip") String ipAddress) throws Exception { Map<String, Object> ip = new HashMap<>(); ip.put("ip", ipAddress); Map<String, Object> message = new HashMap<>(); message.put("resolve_ip", ip); Map<String, Object> response = client.send(message) .thenApply(res -> (Map<String, Object>) res.get("resolve_ip")).join(); if (response == null) { return Response.status(404).build(); } return Response.ok(response).build(); } }