Skip to content

Commit 58331f6

Browse files
authored
Merge pull request #8971 from JimsimroDev/jimsimrodev
#20 - Java
2 parents acd67ac + 9369b16 commit 58331f6

File tree

2 files changed

+341
-0
lines changed

2 files changed

+341
-0
lines changed
Lines changed: 239 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,239 @@
1+
/*
2+
* EJERCICIO:
3+
* Utilizando un mecanismo de peticiones HTTP de tu lenguaje, realiza
4+
* una petición a la web que tú quieras, verifica que dicha petición
5+
* fue exitosa y muestra por consola el contenido de la web.
6+
*
7+
* DIFICULTAD EXTRA (opcional):
8+
* Utilizando la PokéAPI (https://pokeapi.co), crea un programa por
9+
* terminal al que le puedas solicitar información de un Pokémon concreto
10+
* utilizando su nombre o número.
11+
* - Muestra el nombre, id, peso, altura y tipo(s) del Pokémon
12+
* - Muestra el nombre de su cadena de evoluciones
13+
* - Muestra los juegos en los que aparece
14+
* - Controla posibles errores
15+
*/
16+
17+
import java.io.IOException;
18+
import java.net.URI;
19+
import java.net.http.HttpClient;
20+
import java.net.http.HttpRequest;
21+
import java.net.http.HttpResponse;
22+
import java.util.Scanner;
23+
24+
public class JimsimroDev {
25+
private static final String URL_BASE = "https://pokeapi.co/api/v2/pokemon/";
26+
27+
String consumirApi(String url) {
28+
HttpClient client = HttpClient.newHttpClient();
29+
HttpRequest request = HttpRequest.newBuilder()
30+
.uri(URI.create(url))
31+
.build();
32+
HttpResponse<String> response = null;
33+
34+
try {
35+
response = client.send(request, HttpResponse.BodyHandlers.ofString());
36+
} catch (IOException e) {
37+
throw new RuntimeException(e);
38+
} catch (InterruptedException e) {
39+
throw new RuntimeException(e);
40+
}
41+
if (response.statusCode() == 200) {
42+
IO.println("Respuesta exitosa codigo: " + response.statusCode());
43+
String json = response.body();
44+
return json;
45+
}
46+
throw new RuntimeException("Eror al procesar la solicitud codigo de error " + response.statusCode());
47+
}
48+
49+
// Busca campo en la Raiz
50+
private String getCampo(StringBuilder data, String campo) {
51+
String patron = "\"" + campo + "\":";
52+
int inicio = data.indexOf(patron);
53+
if (inicio != -1) {
54+
inicio += patron.length();
55+
while (inicio < data.length() && Character.isWhitespace(data.charAt(inicio))) {
56+
inicio++;
57+
}
58+
if (inicio < data.length()) {
59+
if (data.charAt(inicio) == '"') {
60+
inicio++;
61+
int fin = data.indexOf("\"", inicio);
62+
if (fin != -1) {
63+
return data.substring(inicio, fin);
64+
}
65+
} else {
66+
int fin = inicio;
67+
while (fin < data.length() &&
68+
data.charAt(fin) != ',' &&
69+
data.charAt(fin) != '}' &&
70+
data.charAt(fin) != '\n') {
71+
fin++;
72+
}
73+
return data.substring(inicio, fin).trim();
74+
}
75+
}
76+
}
77+
return null;
78+
}
79+
80+
// Busca campo en una sección dada
81+
private String getCampo(StringBuilder data, String seccion, String campo) {
82+
int indiceSeccion = data.indexOf("\"" + seccion + "\"");
83+
if (indiceSeccion != -1) {
84+
String patron = "\"" + campo + "\":\"";
85+
int indiceCampo = data.indexOf(patron, indiceSeccion);
86+
87+
if (indiceCampo != -1) {
88+
int empiezaValor = indiceCampo + patron.length();
89+
int terminaValor = data.indexOf("\"", empiezaValor);
90+
return data.substring(empiezaValor, terminaValor);
91+
}
92+
}
93+
return null;
94+
}
95+
96+
// Busca los typos
97+
private String[] getTypes(StringBuilder data) {
98+
String tiposPattern = "\"types\":[";
99+
int startIndex = data.indexOf(tiposPattern);
100+
if (startIndex != -1) {
101+
startIndex += tiposPattern.length();
102+
int endIdex = data.indexOf("]", startIndex);
103+
if (endIdex != -1) {
104+
String tiposArray = data.substring(startIndex, endIdex);
105+
String[] tipos = tiposArray.split("},");
106+
String[] resultados = new String[tipos.length];
107+
// Procesar cada tipo
108+
for (int i = 0; i < tipos.length; i++) {
109+
String tipo = tipos[i];
110+
String namePattern = "\"name\":\"";
111+
int nameStart = tipo.indexOf(namePattern);
112+
if (nameStart != -1) {
113+
nameStart += namePattern.length();
114+
int nameEnd = tipo.indexOf("\"", nameStart);
115+
if (nameEnd != -1) {
116+
resultados[i] = tipo.substring(nameStart, nameEnd);
117+
}
118+
}
119+
}
120+
return resultados;
121+
}
122+
}
123+
return new String[0];
124+
}
125+
126+
private String getEvolutionChainUrl(StringBuilder data) {
127+
String patron = "\"evolution_chain\":{\"url\":\"";
128+
int inicio = data.indexOf(patron);
129+
if (inicio != -1) {
130+
inicio += patron.length();
131+
int fin = data.indexOf("\"", inicio);
132+
if (fin != -1) {
133+
return data.substring(inicio, fin);
134+
}
135+
}
136+
return null;
137+
}
138+
139+
void evolution_chain(StringBuilder data) {
140+
// Obtener el nombre de la especie actual
141+
String speciesName = getCampo(data, "species", "name");
142+
IO.println("Evolución: " + speciesName);
143+
144+
// Buscar el patrón de evolves_to
145+
String evolvesToPattern = "\"evolves_to\":[";
146+
int evolvesToIndex = data.indexOf(evolvesToPattern);
147+
148+
if (evolvesToIndex != -1) {
149+
// Si encontramos evolves_to y no está vacío
150+
evolvesToIndex += evolvesToPattern.length();
151+
if (data.charAt(evolvesToIndex) != ']') {
152+
// Obtener el contenido del evolves_to
153+
int endIndex = findMatchingBracket(data, evolvesToIndex);
154+
if (endIndex != -1) {
155+
// Crear un nuevo StringBuilder con el contenido de evolves_to
156+
StringBuilder evolvesTo = new StringBuilder(
157+
data.substring(evolvesToIndex, endIndex));
158+
// Llamada recursiva con el nuevo contenido
159+
evolution_chain(evolvesTo);
160+
}
161+
}
162+
}
163+
}
164+
165+
// Método auxiliar para encontrar el corchete de cierre correspondiente
166+
private int findMatchingBracket(StringBuilder data, int startIndex) {
167+
int count = 1;
168+
for (int i = startIndex; i < data.length(); i++) {
169+
if (data.charAt(i) == '[')
170+
count++;
171+
if (data.charAt(i) == ']')
172+
count--;
173+
if (count == 0)
174+
return i;
175+
}
176+
return -1;
177+
}
178+
179+
void main() {
180+
Scanner in = new Scanner(System.in);
181+
182+
// HttpClient client = HttpClient.newHttpClient();
183+
//
184+
// HttpRequest request = HttpRequest.newBuilder()
185+
// .uri(URI.create("https://www.mercadolibre.com.co/"))
186+
// .build();
187+
// HttpResponse<String> response = null;
188+
//
189+
// try {
190+
// response = client.send(request, HttpResponse.BodyHandlers.ofString());
191+
// } catch (IOException e) {
192+
// throw new RuntimeException(e);
193+
// } catch (InterruptedException e) {
194+
// throw new RuntimeException(e);
195+
// }
196+
// String json = response.body();
197+
// IO.println("Estado " + response.statusCode());
198+
// IO.println(json);
199+
200+
IO.println("Ingresa el nombre del pokemon a consultar");
201+
String pokemon = in.nextLine();
202+
203+
StringBuilder data = new StringBuilder();
204+
StringBuilder url = new StringBuilder();
205+
206+
data.append(consumirApi(URL_BASE + pokemon));
207+
208+
String nombre = getCampo(data, "name");
209+
210+
String id = getCampo(data, "id");
211+
212+
String peso = getCampo(data, "weight");
213+
214+
String altura = getCampo(data, "height");
215+
String[] tipos = getTypes(data);
216+
217+
String urlSpecies = getCampo(data, "species", "url");
218+
219+
url.append(consumirApi(urlSpecies));
220+
String urlEvolucion = getEvolutionChainUrl(url);
221+
222+
// StringBuilder evolution = new StringBuilder();
223+
// String evolucin = getCampo(evolution, "species", "name");
224+
// IO.println("url evloucion " + evolution);
225+
// IO.println("evolution" + evolucin);
226+
227+
StringBuilder evolutionData = new StringBuilder(consumirApi(urlEvolucion));
228+
evolution_chain(evolutionData);
229+
IO.println("Nombre: " + nombre);
230+
IO.println("ID: " + id);
231+
IO.println("Peso: " + peso);
232+
IO.println("Altura: " + altura);
233+
IO.println("Tipos:");
234+
for (String tipo : tipos) {
235+
IO.println("- " + tipo);
236+
}
237+
in.close();
238+
}
239+
}
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
/*
2+
* EJERCICIO:
3+
* Explora el concepto de callback en tu lenguaje creando un ejemplo
4+
* simple (a tu elección) que muestre su funcionamiento.
5+
*
6+
* DIFICULTAD EXTRA (opcional):
7+
* Crea un simulador de pedidos de un restaurante utilizando callbacks.
8+
* Estará formado por una función que procesa pedidos.
9+
* Debe aceptar el nombre del plato, una callback de confirmación, una
10+
* de listo y otra de entrega.
11+
* - Debe imprimir un confirmación cuando empiece el procesamiento.
12+
* - Debe simular un tiempo aleatorio entre 1 a 10 segundos entre
13+
* procesos.
14+
* - Debe invocar a cada callback siguiendo un orden de procesado.
15+
* - Debe notificar que el plato está listo o ha sido entregado.
16+
*/
17+
18+
public class JimsimroDev {
19+
private static final String DIV_LINE = ":::::::::::::::::::::::::";
20+
private static final int MIN = 1000;
21+
private static final int MAX = 10000;
22+
23+
interface Noficar {
24+
void notificacion(String mensaje);
25+
}
26+
27+
interface Confirmado {
28+
void confirmarPedidos(String mensaje);
29+
}
30+
31+
interface Listo {
32+
void pedidoListo(String mensaje);
33+
}
34+
35+
interface Entregado {
36+
void entregarPedidos(String mensaje);
37+
}
38+
39+
static void notificacionEnviada(String proceso, Noficar callback) {
40+
try {
41+
System.out.println("Iniciando proceso...");
42+
Thread.sleep(5000);
43+
callback.notificacion("Proceso completado: " + proceso);
44+
} catch (InterruptedException e) {
45+
System.out.println("Erro timeout" + e);
46+
}
47+
48+
}
49+
50+
static int ramdon() {
51+
return (int) (Math.random() * (MAX - MIN + 1)) + MIN;
52+
}
53+
54+
static void procesarPedidos(String plato, Confirmado confirmado, Listo listo, Entregado entregado) {
55+
Thread hacerPedido = new Thread(() -> {
56+
try {
57+
58+
print("Iniciando pedido " + plato +"....");
59+
Thread.sleep(ramdon());
60+
confirmado.confirmarPedidos(plato + " Confirmado");
61+
62+
print("Preparando pedido " + plato + "....");
63+
print(DIV_LINE);
64+
Thread.sleep(ramdon());
65+
listo.pedidoListo(plato + " Listo");
66+
67+
print("Entregando el plato "+plato);
68+
print(DIV_LINE);
69+
Thread.sleep(ramdon());
70+
entregado.entregarPedidos(plato + " Entregado");
71+
72+
} catch (InterruptedException e) {
73+
print("Erro no pedido" + e);
74+
}
75+
});
76+
hacerPedido.start();
77+
}
78+
79+
static void hacerOrden(String plato) {
80+
procesarPedidos(
81+
plato,
82+
JimsimroDev::print,
83+
JimsimroDev::print,
84+
JimsimroDev::print);
85+
}
86+
87+
static void print(Object... args) {
88+
for (Object s : args) {
89+
System.out.print(s + " ");
90+
}
91+
System.out.println();
92+
}
93+
94+
public static void main(String[] args) {
95+
notificacionEnviada("Enviando SMS ", System.out::println);
96+
97+
// EXTRA
98+
hacerOrden("Bandeja Paisa");
99+
hacerOrden("Lechona");
100+
hacerOrden("Mote De Queso");
101+
}
102+
}

0 commit comments

Comments
 (0)