Skip to content

Commit

Permalink
agregada opcion para guardar el response sin mostrarlo en la vista
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastian4j committed Jun 2, 2022
1 parent a5baf4d commit a33f0c2
Show file tree
Hide file tree
Showing 9 changed files with 109 additions and 67 deletions.
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Spaceship :rocket:

![v1.4.0](https://github.com/sebastian4j/spaceship/blob/main/images/v1.4.0.png?raw=true)
![v1.5.0](https://github.com/sebastian4j/spaceship/blob/main/images/v1.5.0.png?raw=true)

- Es una aplicación escrita en Java 17, JavaFX y compilable con GraalVM para una ejecución nativa.
- Permite hacer peticiones a urls y visualizar la respuesta.
Expand All @@ -17,6 +17,7 @@
- guardar el response obtenido
- ver los milisegundos y bytes transferidos
- muestra el código de estado http obtenido
- guardar el response directo a un archivo sin mostrar el contenido
- Compilar la app:

```
Expand All @@ -25,10 +26,10 @@ mvn clean package
- Lanzar la app:
```
linux:
java --module-path target/spaceship-1.4.0.jar:target/lib/ --module com.github.sebastian4j.spaceship/com.github.sebastian4j.spaceship.Spaceship
java --module-path target/spaceship-1.5.0.jar:target/lib/ --module com.github.sebastian4j.spaceship/com.github.sebastian4j.spaceship.Spaceship
windows:
java --module-path target/spaceship-1.4.0.jar;target/lib/ --module com.github.sebastian4j.spaceship/com.github.sebastian4j.spaceship.Spaceship
java --module-path target/spaceship-1.5.0.jar;target/lib/ --module com.github.sebastian4j.spaceship/com.github.sebastian4j.spaceship.Spaceship
```
- Para compilarlo en forma nativa:
- descargar graalvm-ce-java17-22.1.0 (me imagino que funciona con versiones posteriores)
Expand Down
Binary file added images/v1.5.0.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 2 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.github.sebastian4j</groupId>
<artifactId>spaceship</artifactId>
<version>1.4.0</version>
<version>1.5.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source>
Expand Down Expand Up @@ -111,6 +111,7 @@
<list>javafx.scene.control.MenuItem</list>
<list>impl.jfxtras.styles.jmetro.FluentButtonSkin</list>
<list>impl.jfxtras.styles.jmetro.TextFieldSkin</list>
<list>javafx.scene.control.Alert</list>
<list>com.github.sebastian4j.spaceship.fxml.RequestController</list>
<list>com.github.sebastian4j.spaceship.fxml.RequestTabController</list>
<list>com.github.sebastian4j.spaceship.dto.GUIRequest</list>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
import java.util.List;
import java.util.Map;

public record RequestResponse(String body, Map<String, List<String>> headers, long bytes, String statusCode) {
public record RequestResponse(String body, Map<String, List<String>> headers, long bytes, String statusCode, byte[] response) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,62 +30,48 @@
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class RequestTabController implements Initializable, FileLoader {
private static final System.Logger LOGGER = System.getLogger(RequestTabController.class.getName());
@FXML
private FlowPane a;

@FXML
private Button addHeader;

@FXML
private TextArea bodyresult;

@FXML
private VBox containerHeader;

@FXML
private VBox containerHeaderResponse;

@FXML
private ComboBox<String> methods;

@FXML
private TextArea requestbody;

@FXML
private ScrollPane scrollHeaders;

@FXML
private Button send;

@FXML
private Tab tab1;

@FXML
private Tab tab2;

@FXML
private Text textFlowPaneResponse;

@FXML
private TextField url;

@FXML
private VBox vboxurl;

@FXML
private HBox hboxResponse;

@FXML
private VBox vboxResultResponse;

@FXML
private BorderPane contenedor;

@FXML
private TabPane tabsContainer;
@FXML
private CheckBox onlySave;

private ResourceBundle rb;
private File last;
Expand All @@ -94,6 +80,7 @@ public class RequestTabController implements Initializable, FileLoader {
private Task<Void> runningTask;
private Future<?> future;
private RequestResponseUtils requestResponseUtils = new RequestResponseUtils();
private File saveResponse = null;
@FXML
void addHeader(ActionEvent event) {
addHeader(null, null);
Expand Down Expand Up @@ -147,48 +134,70 @@ private void calculateHeaderResponseWidth(TextField tfk, TextField tfv) {
tfv.setPrefWidth(widthVal);
}

private File fileToSaveRequest() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(rb.getString("file.chooser.save"));
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter(rb.getString("file.chooser.all.files"), "*.*"));
return fileChooser.showSaveDialog(null);
}

private void sendRequest() {
saveResponse = null;
var toFile = onlySave.isSelected();
var send = new AtomicBoolean(true);
if (toFile) {
saveResponse = fileToSaveRequest();
if (saveResponse == null) {
send.set(false);
FXMLUtils.showWarningAlert(rb.getString("only.save.error.title"), rb.getString("only.save.error.text"));
}
}

runningTask = new Task<>() {
@Override
protected Void call() {
try {
LOGGER.log(System.Logger.Level.INFO, "enviando request");
var ini = System.currentTimeMillis();
var result = requestResponseUtils.sendRequest(
url.getText(), FXMLUtils.headers(containerHeader),
HttpMethods.hasBody(methods.getSelectionModel().getSelectedItem()), requestbody.getText());
var res = System.currentTimeMillis() - ini;
Platform.runLater(() -> {
textFlowPaneResponse.setText(
rb.getString("milis") + ": " + res +
" bytes: " + result.bytes() +
" status: " + result.statusCode());
VBox vb = new VBox();
containerHeaderResponse.getChildren().clear();
result.headers().forEach((a, b) -> {
for (var val : b) {
var key = new TextField(a);
key.setMinWidth(300);
var value = new TextField(val);
value.setMinWidth(400);
var hbox = new HBox(key, value);
hbox.setSpacing(2);
hbox.setAlignment(Pos.CENTER);
vb.getChildren().add(hbox);
calculateHeaderResponseWidth(key, value);
stage.widthProperty().addListener((observableValue, number, t1) ->
calculateHeaderResponseWidth(key, value)
);
}
if (send.get()) {
LOGGER.log(System.Logger.Level.INFO, "enviando request");
var ini = System.currentTimeMillis();
var result = requestResponseUtils.sendRequest(
url.getText(), FXMLUtils.headers(containerHeader),
HttpMethods.hasBody(methods.getSelectionModel().getSelectedItem()), requestbody.getText(),
saveResponse);

var res = System.currentTimeMillis() - ini;
Platform.runLater(() -> {
textFlowPaneResponse.setText(
rb.getString("milis") + ": " + res +
" bytes: " + result.bytes() +
" status: " + result.statusCode());
VBox vb = new VBox();
containerHeaderResponse.getChildren().clear();
result.headers().forEach((a, b) -> {
for (var val : b) {
var key = new TextField(a);
key.setMinWidth(300);
var value = new TextField(val);
value.setMinWidth(400);
var hbox = new HBox(key, value);
hbox.setSpacing(2);
hbox.setAlignment(Pos.CENTER);
vb.getChildren().add(hbox);
calculateHeaderResponseWidth(key, value);
stage.widthProperty().addListener((observableValue, number, t1) ->
calculateHeaderResponseWidth(key, value)
);
}
});
var sp = new HBox();
sp.setMinHeight(50); // espacio al final
vb.getChildren().add(sp);
containerHeaderResponse.getChildren().add(vb);
bodyresult.setText(result.body());
tabsContainer.getSelectionModel().select(tab2);
});
var sp = new HBox();
sp.setMinHeight(50); // espacio al final
vb.getChildren().add(sp);
containerHeaderResponse.getChildren().add(vb);
bodyresult.setText(result.body());
tabsContainer.getSelectionModel().select(tab2);
});
LOGGER.log(System.Logger.Level.INFO, "request finalizado");
LOGGER.log(System.Logger.Level.INFO, "request finalizado");
}
} catch (Exception e) {
LOGGER.log(System.Logger.Level.ERROR, "error al enviar request", e);
}
Expand Down Expand Up @@ -254,10 +263,11 @@ public void initialize(URL url, ResourceBundle rb) {
scrollHeaders.widthProperty().addListener(cl -> {
containerHeader.setMinWidth(scrollHeaders.getWidth());
containerHeaderResponse.setMinWidth(scrollHeaders.getWidth());
this.url.setMinWidth(scrollHeaders.getWidth() - send.getWidth() - methods.getWidth() - 50);
this.url.setMinWidth(scrollHeaders.getWidth() - send.getWidth() - methods.getWidth() - 100);
});
vboxResultResponse.heightProperty().addListener((observableValue, number, t1) -> resize());
resize();
onlySave.setTooltip(new Tooltip(rb.getString("only.save")));
}

private void resize() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.github.sebastian4j.spaceship.dto.GUIRequest;
import com.github.sebastian4j.spaceship.dto.Header;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
Expand Down Expand Up @@ -68,4 +69,11 @@ public static Map<String, String> headers(VBox container) {
});
return headers;
}

public static void showWarningAlert(String title, String text) {
var alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle(title);
alert.setContentText(text);
alert.show();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import com.github.sebastian4j.spaceship.dto.RequestResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
Expand Down Expand Up @@ -33,7 +35,8 @@ public void kill() {
}
}

public RequestResponse sendRequest(final String url, Map<String, String> headers, boolean withBody, final String body) {
public RequestResponse sendRequest(final String url, Map<String, String> headers, boolean withBody,
final String body, File toFile) {
String result = "";
final var sb = new StringBuilder();
final var bytes = new AtomicLong();
Expand All @@ -56,11 +59,20 @@ public RequestResponse sendRequest(final String url, Map<String, String> headers
String res = "";
int lee;
LOGGER.log(System.Logger.Level.INFO, "leyendo en thread");
while ((lee = is.read()) != -1) {
sb.append((char) lee);
if (toFile == null) { // retornar la salida
while ((lee = is.read()) != -1) {
sb.append((char) lee);
}
res = sb.toString();
bytes.set(res.getBytes(StandardCharsets.UTF_8).length);
} else { // guardar en archivo la salida
try (var os = new FileOutputStream(toFile)) {
var br = is.readAllBytes();
os.write(br);
bytes.set(br.length);
}
}
res = sb.toString();
bytes.set(res.getBytes(StandardCharsets.UTF_8).length);

}
hr.putAll(con.getHeaderFields());
} catch (Exception e) {
Expand All @@ -79,7 +91,7 @@ public RequestResponse sendRequest(final String url, Map<String, String> headers
LOGGER.log(System.Logger.Level.ERROR, "error al enviar request", e);
result = e.getMessage() + " ~ " + readError();
}
return new RequestResponse(result, hr, bytes.get(), statusCode[0]);
return new RequestResponse(result, hr, bytes.get(), statusCode[0], new byte[]{});
}

private String readError() {
Expand Down
6 changes: 5 additions & 1 deletion src/main/resources/label.properties
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,8 @@ milis=miliseconds
cancel.send=Cancel
no.name=Default
file.extension=spc
file.quick.save=Save
file.quick.save=Save
only.save=response to file
only.save.error.title=Unable to save response
only.save.error.text=Select the destination file
only.save.response=save
8 changes: 7 additions & 1 deletion src/main/resources/requestTab.fxml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>
<BorderPane fx:id="contenedor" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.github.sebastian4j.spaceship.fxml.RequestTabController">
<top>
Expand All @@ -14,8 +15,13 @@
<FlowPane hgap="5.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" BorderPane.alignment="CENTER">
<children>
<ComboBox fx:id="methods" prefHeight="24.0" prefWidth="82.0" />
<TextField fx:id="url" minHeight="24.0" minWidth="526.0" onAction="#sendRequest" />
<TextField fx:id="url" minHeight="24.0" minWidth="484.0" onAction="#sendRequest" prefHeight="24.0" prefWidth="484.0" />
<Button fx:id="send" minHeight="24.0" minWidth="102.0" mnemonicParsing="false" onAction="#sendRequest" text="%url.search" />
<CheckBox fx:id="onlySave" mnemonicParsing="false" text="%only.save.response" textAlignment="CENTER" wrapText="true">
<font>
<Font size="10.0" />
</font>
</CheckBox>
</children>
<BorderPane.margin>
<Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
Expand Down

0 comments on commit a33f0c2

Please sign in to comment.