Skip to content

Commit

Permalink
refactor: extract interface
Browse files Browse the repository at this point in the history
  • Loading branch information
Adriano Santos committed Aug 21, 2024
1 parent 8e8172d commit 278af03
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import io.eigr.spawn.java.actors.PostalCodeActor;
import io.eigr.spawn.java.actors.RouterActor;
import io.eigr.spawn.java.service.PostalCodeService;
import io.eigr.spawn.java.service.ViaCepService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -22,7 +23,7 @@ public static void main(String[] args) throws SpawnException {
Config cfg = Config.createDefaultConfig();

DependencyInjector dependencyInjector = SimpleDependencyInjector.createInjector();
dependencyInjector.bind(PostalCodeService.class, new PostalCodeService());
dependencyInjector.bind(PostalCodeService.class, new ViaCepService());

Spawn spawnSystem = new Spawn.SpawnSystem()
.create(cfg.spawnSystemName, dependencyInjector)
Expand Down Expand Up @@ -82,3 +83,4 @@ public String toString() {
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import static io.eigr.spawn.api.actors.behaviors.ActorBehavior.action;
import static io.eigr.spawn.api.actors.behaviors.ActorBehavior.name;

public class PostalCodeActor implements StatefulActor<DomainProto.PostalCodeState> {
public final class PostalCodeActor implements StatefulActor<DomainProto.PostalCodeState> {
private static final Logger log = LoggerFactory.getLogger(PostalCodeActor.class);

private PostalCodeService postalCodeService;
Expand All @@ -30,8 +30,7 @@ public ActorBehavior configure(BehaviorCtx behaviorCtx) {
this.postalCodeService = behaviorCtx.getInjector().getInstance(PostalCodeService.class);
return new UnNamedActorBehavior(
name("PostalCode"),
action("GetPostalCodeData", ActionBindings.of(DomainProto.GetRequest.class, this::getPostalCodeData))
);
action("GetPostalCodeData", ActionBindings.of(DomainProto.GetRequest.class, this::getPostalCodeData)));
}

private Value getPostalCodeData(ActorContext<DomainProto.PostalCodeState> context, DomainProto.GetRequest msg) {
Expand All @@ -49,7 +48,8 @@ private Value getPostalCodeData(ActorContext<DomainProto.PostalCodeState> contex

// If postal code data found, build state and response
if (!postalCodeData.isEmpty()) {
DomainProto.PostalCodeState newState = buildPostalCodeState(msg.getCode(), postalCodeData, DomainProto.PostalCodeStatus.FOUND);
DomainProto.PostalCodeState newState = buildPostalCodeState(msg.getCode(), postalCodeData,
DomainProto.PostalCodeStatus.FOUND);
return createValueWithStateAndResponse(newState);
}

Expand All @@ -67,7 +67,8 @@ private Value createValueWithStateAndResponse(DomainProto.PostalCodeState state)
return Value.at().state(state).response(response).reply();
}

private DomainProto.PostalCodeState buildPostalCodeState(String code, Map<String, String> data, DomainProto.PostalCodeStatus status) {
private DomainProto.PostalCodeState buildPostalCodeState(String code, Map<String, String> data,
DomainProto.PostalCodeStatus status) {
return DomainProto.PostalCodeState.newBuilder()
.setCode(code)
.setCity(data.get("localidade"))
Expand All @@ -79,4 +80,3 @@ private DomainProto.PostalCodeState buildPostalCodeState(String code, Map<String
}

}

Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,22 @@
import io.eigr.spawn.internal.ActionBindings;

import io.eigr.spawn.java.domain.DomainProto;
import io.eigr.spawn.java.service.PostalCodeService;
import io.eigr.spawn.java.service.ViaCepService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static io.eigr.spawn.api.actors.behaviors.ActorBehavior.action;
import static io.eigr.spawn.api.actors.behaviors.ActorBehavior.name;

public class RouterActor implements StatelessActor {
public final class RouterActor implements StatelessActor {
private static final Logger log = LoggerFactory.getLogger(RouterActor.class);

private PostalCodeService postalCodeService;
private ViaCepService postalCodeService;

@Override
public ActorBehavior configure(BehaviorCtx behaviorCtx) {
this.postalCodeService = behaviorCtx.getInjector().getInstance(PostalCodeService.class);
this.postalCodeService = behaviorCtx.getInjector().getInstance(ViaCepService.class);
return new NamedActorBehavior(
name("Router"),
action("GetPostalCode", ActionBindings.of(DomainProto.GetRequest.class, this::getPostalCodeData))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,61 +1,5 @@
package io.eigr.spawn.java.service;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public final class PostalCodeService {
private static final Logger log = LoggerFactory.getLogger(PostalCodeService.class);

private static final String CEP_SERVICE_URL = "https://viacep.com.br/ws/%s/json/";

private final OkHttpClient client;

public PostalCodeService() {
this.client = new OkHttpClient.Builder()
.connectTimeout(120, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
.callTimeout(400, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.connectionPool(new ConnectionPool(256, 100, TimeUnit.SECONDS))
.build();
}

public Map<String, String> find(String postalCode) {
log.debug("Looking for Brazil PostalCode '{}'.", postalCode);
// Massive use may block your access indefinitely.
Request request = new Request.Builder()
.url(String.format(CEP_SERVICE_URL, postalCode))
.get()
.build();

Call call = client.newCall(request);
try (Response response = call.execute()) {
assert response.body() != null;
if (response.isSuccessful()) {
String responseJson = response.body().string();
Type type = new TypeToken<Map<String, String>>() {
}.getType();
Map<String, String> map = new Gson().fromJson(responseJson, type);
log.debug("PostalCode response '{}'.", map);
if (!map.containsKey("erro")) {
if (!map.containsKey("pais"))
map.put("pais", "Brasil");
return map;
}
}
} catch (Exception err) {
log.error("Error while load postalcode.", err);
}
log.warn("postalcode '{}' not found.", postalCode);
return new HashMap<>();
}
public interface PostalCodeService {
Map<String, String> find(String postalCode);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package io.eigr.spawn.java.service;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public final class ViaCepService implements PostalCodeService {
private static final Logger log = LoggerFactory.getLogger(ViaCepService.class);

private static final String CEP_SERVICE_URL = "https://viacep.com.br/ws/%s/json/";

private final OkHttpClient client;

public ViaCepService() {
this.client = new OkHttpClient.Builder()
.connectTimeout(120, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
.callTimeout(400, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.connectionPool(new ConnectionPool(256, 100, TimeUnit.SECONDS))
.build();
}

@Override
public Map<String, String> find(String postalCode) {
log.debug("Looking for Brazil PostalCode '{}'.", postalCode);
// Massive use may block your access indefinitely.
Request request = new Request.Builder()
.url(String.format(CEP_SERVICE_URL, postalCode))
.get()
.build();

Call call = client.newCall(request);
try (Response response = call.execute()) {
assert response.body() != null;
if (response.isSuccessful()) {
String responseJson = response.body().string();
Type type = new TypeToken<Map<String, String>>() {
}.getType();
Map<String, String> map = new Gson().fromJson(responseJson, type);
log.debug("PostalCode response '{}'.", map);
if (!map.containsKey("erro")) {
if (!map.containsKey("pais"))
map.put("pais", "Brasil");
return map;
}
}
} catch (Exception err) {
log.error("Error while load postalcode.", err);
}
log.warn("postalcode '{}' not found.", postalCode);
return new HashMap<>();
}
}

0 comments on commit 278af03

Please sign in to comment.