diff --git a/engine/src/main/java/com/arcadedb/query/sql/executor/CreateEdgesStep.java b/engine/src/main/java/com/arcadedb/query/sql/executor/CreateEdgesStep.java index a9186e9b904..07628020b6c 100755 --- a/engine/src/main/java/com/arcadedb/query/sql/executor/CreateEdgesStep.java +++ b/engine/src/main/java/com/arcadedb/query/sql/executor/CreateEdgesStep.java @@ -26,6 +26,7 @@ import com.arcadedb.exception.CommandExecutionException; import com.arcadedb.exception.SchemaException; import com.arcadedb.exception.TimeoutException; +import com.arcadedb.exception.TypeMismatchException; import com.arcadedb.graph.Edge; import com.arcadedb.graph.GraphEngine; import com.arcadedb.graph.MutableEdge; @@ -335,22 +336,38 @@ private Vertex asVertex(Object currentFrom) { rid = result.getProperty("rid"); if (rid != null) currentFrom = rid; + else if (result.isElement()) + // a record that is not a vertex: refused below by its RID and kind, not by the JSON of its whole content + currentFrom = result.getElement().get(); else - throw new CommandExecutionException("Invalid vertex for edge creation: " + result); + throw new TypeMismatchException("Invalid vertex for edge creation: " + result); } } + // An endpoint that is not a vertex is the caller's mistake: it is refused with a TypeMismatchException, a client error for + // every protocol, and a message of our own. Casting the record to a vertex raised a ClassCastException instead, which + // reached the client as a raw Java exception under an HTTP 500 (#12425) if (currentFrom instanceof Vertex vertex) return vertex; - else if (currentFrom instanceof Document document) - return document.asVertex(); - else if (RID.is(currentFrom)) - return getContext().getDatabase().newRID(currentFrom.toString()).asVertex(); - throw new CommandExecutionException( + if (currentFrom instanceof Document document) + throw new TypeMismatchException(notAVertexMessage(document)); + + // A RID given as text, or as the @rid of a projection: the record it names is read and judged like any other endpoint, so + // a document is refused as the wrong kind of record and not answered as a record that does not exist + if (RID.is(currentFrom)) + return asVertex(getContext().getDatabase().newRID(currentFrom.toString()).getRecord()); + + throw new TypeMismatchException( "Invalid vertex for edge creation: " + (currentFrom == null ? "null" : currentFrom.toString())); } + private static String notAVertexMessage(final Document document) { + final RID identity = document.getIdentity(); + return "Invalid vertex for edge creation: the " + (document instanceof Edge ? "edge" : "document") + + (identity != null ? " " + identity : "") + " is not a vertex"; + } + @Override public String prettyPrint(final int depth, final int indent) { final String spaces = ExecutionStepInternal.getIndent(depth, indent); diff --git a/engine/src/main/java/com/arcadedb/query/sql/executor/MatchExecutionPlanner.java b/engine/src/main/java/com/arcadedb/query/sql/executor/MatchExecutionPlanner.java index a1c440809fb..b2cdff06146 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/executor/MatchExecutionPlanner.java +++ b/engine/src/main/java/com/arcadedb/query/sql/executor/MatchExecutionPlanner.java @@ -20,6 +20,7 @@ import com.arcadedb.database.Database; import com.arcadedb.exception.CommandExecutionException; +import com.arcadedb.exception.CommandSQLParsingException; import com.arcadedb.exception.SchemaException; import com.arcadedb.graph.GraphTraversalProvider; import com.arcadedb.graph.GraphTraversalProviderRegistry; @@ -259,7 +260,7 @@ private void checkOrderByRecordAttributes() { final String attribute = item.getRecordAttr(); if (attribute == null || isReturnedColumn(attribute)) continue; - throw new CommandExecutionException("ORDER BY " + attribute + throw new CommandSQLParsingException("ORDER BY " + attribute + " has no meaning on the rows of this MATCH: its RETURN builds new rows out of the matched aliases, which have no " + attribute + " of their own. Order by ." + attribute + " or by a column of the RETURN instead, for example " + "RETURN a." + attribute + " AS key ... ORDER BY key"); diff --git a/engine/src/main/java/com/arcadedb/query/sql/parser/Rid.java b/engine/src/main/java/com/arcadedb/query/sql/parser/Rid.java index a421bf960bf..e50e3f21a2a 100644 --- a/engine/src/main/java/com/arcadedb/query/sql/parser/Rid.java +++ b/engine/src/main/java/com/arcadedb/query/sql/parser/Rid.java @@ -22,7 +22,7 @@ import com.arcadedb.database.Identifiable; import com.arcadedb.database.RID; -import com.arcadedb.exception.CommandExecutionException; +import com.arcadedb.exception.TypeMismatchException; import com.arcadedb.query.sql.executor.CommandContext; import com.arcadedb.query.sql.executor.Result; import com.arcadedb.utility.CodeUtils; @@ -93,11 +93,11 @@ private static RID toRecordId(final Object result, final CommandContext context) if (result instanceof String string) { if (!(string.startsWith("#") && (string.contains(":")))) - throw new CommandExecutionException("Cannot convert to RID: " + result); + throw new TypeMismatchException("Cannot convert to RID: " + result); final List parts = CodeUtils.split(string.substring(1), ':', 3); if (parts.size() != 2) - throw new CommandExecutionException("Cannot convert to RID: " + result); + throw new TypeMismatchException("Cannot convert to RID: " + result); final int bucketId; final long position; @@ -105,7 +105,7 @@ private static RID toRecordId(final Object result, final CommandContext context) bucketId = Integer.parseInt(parts.getFirst()); position = Long.parseLong(parts.get(1)); } catch (final NumberFormatException e) { - throw new CommandExecutionException("Cannot convert to RID: " + result, e); + throw new TypeMismatchException("Cannot convert to RID: " + result, e); } return RID.create(context.getDatabase(), bucketId, position); } diff --git a/engine/src/test/java/com/arcadedb/query/sql/executor/Issue12425CallerMistakesInGraphStatementsTest.java b/engine/src/test/java/com/arcadedb/query/sql/executor/Issue12425CallerMistakesInGraphStatementsTest.java new file mode 100644 index 00000000000..80789f7785b --- /dev/null +++ b/engine/src/test/java/com/arcadedb/query/sql/executor/Issue12425CallerMistakesInGraphStatementsTest.java @@ -0,0 +1,202 @@ +/* + * Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com) + * SPDX-License-Identifier: Apache-2.0 + */ +package com.arcadedb.query.sql.executor; + +import com.arcadedb.TestHelper; +import com.arcadedb.database.RID; +import com.arcadedb.exception.RecordNotFoundException; +import com.arcadedb.exception.TypeMismatchException; +import com.arcadedb.graph.MutableVertex; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Issue #12425: a graph statement refused for a mistake of the caller has to say so with a typed exception the servers + * answer as a client error (HTTP 400, Postgres 42804, Bolt VALIDATION), not with a plain {@code CommandExecutionException} + * (HTTP 500) and never with the raw {@link ClassCastException} of a record cast. A refused statement writes nothing. + * + * @author lvca (l.garulli@arcadedata.com) + */ +class Issue12425CallerMistakesInGraphStatementsTest extends TestHelper { + private RID vertexRid; + private RID otherVertexRid; + private RID documentRid; + private RID edgeRid; + + @Test + void aDocumentRidLiteralAsAnEndpointIsRefusedAndNamed() { + createFixtures(); + + assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM " + documentRid + " TO " + vertexRid, "document", documentRid); + assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM " + vertexRid + " TO " + documentRid, "document", documentRid); + assertThat(linkCount()).isZero(); + } + + @Test + void aDocumentRidGivenAsAStringIsRefusedAndNamedNotAnsweredAsMissing() { + createFixtures(); + + // the record exists: a "record not found" would be a wrong answer, the endpoint is the wrong kind of record + assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM ? TO ?", "document", documentRid, documentRid.toString(), + vertexRid.toString()); + assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM ? TO ?", "document", documentRid, vertexRid.toString(), + documentRid.toString()); + assertThat(linkCount()).isZero(); + } + + @Test + void anEdgeAsAnEndpointIsRefusedAndNamed() { + createFixtures(); + + assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM " + edgeRid + " TO " + vertexRid, "edge", edgeRid); + assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM ? TO ?", "edge", edgeRid, vertexRid.toString(), edgeRid.toString()); + assertThat(linkCount()).isZero(); + } + + @Test + void aQueryThatReturnsADocumentOrAnEdgeAsAnEndpointIsRefusedAndNamed() { + createFixtures(); + + assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM (SELECT FROM Doc12425) TO (SELECT FROM V12425)", "document", documentRid); + assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM (SELECT FROM V12425) TO (SELECT FROM Doc12425)", "document", documentRid); + assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM (SELECT FROM Wire12425) TO (SELECT FROM V12425)", "edge", edgeRid); + assertThat(linkCount()).isZero(); + } + + @Test + void aProjectedRidOfADocumentIsRefusedAndNamed() { + createFixtures(); + + assertRefusedAsNotAVertex("CREATE EDGE Link12425 FROM (SELECT @rid AS rid FROM Doc12425) TO (SELECT FROM V12425)", "document", + documentRid); + assertThat(linkCount()).isZero(); + } + + @Test + void aDocumentAmongSeveralEndpointsLeavesNoEdgeOfTheOnesBeforeIt() { + createFixtures(); + + // the endpoints are read one at a time: the edge to the first vertex is built before the document is reached, and the + // refused statement must not leave it behind once its transaction ends + database.begin(); + try { + assertThatThrownBy(() -> drainCommand("CREATE EDGE Link12425 FROM " + vertexRid + " TO [" + otherVertexRid + ", " + documentRid + "]"))// + .isExactlyInstanceOf(TypeMismatchException.class)// + .hasMessageContaining("the document " + documentRid + " is not a vertex"); + } finally { + database.rollback(); + } + + assertThat(linkCount()).isZero(); + } + + @Test + void anEndpointThatIsNotARecordAtAllIsRefused() { + createFixtures(); + + assertThatThrownBy(() -> inTransaction("CREATE EDGE Link12425 FROM ? TO ?", "nothing", vertexRid.toString()))// + .isExactlyInstanceOf(TypeMismatchException.class)// + .hasMessageContaining("Invalid vertex for edge creation: nothing"); + assertThat(linkCount()).isZero(); + } + + @Test + void aRidThatNamesNothingIsStillRecordNotFound() { + createFixtures(); + + // not a mistake of the kind above: the RID is well-formed and the record is simply not there + assertThatThrownBy( + () -> inTransaction("CREATE EDGE Link12425 FROM ? TO ?", "#" + documentRid.getBucketId() + ":99999", vertexRid.toString()))// + .isInstanceOf(RecordNotFoundException.class); + assertThat(linkCount()).isZero(); + } + + @Test + void validEndpointsStillMakeTheEdge() { + createFixtures(); + + inTransaction("CREATE EDGE Link12425 FROM " + vertexRid + " TO " + otherVertexRid); + inTransaction("CREATE EDGE Link12425 FROM ? TO ?", otherVertexRid.toString(), vertexRid.toString()); + inTransaction("CREATE EDGE Link12425 FROM (SELECT FROM V12425 WHERE k = 'a') TO (SELECT @rid FROM V12425 WHERE k = 'b')"); + + assertThat(linkCount()).isEqualTo(3L); + } + + @ParameterizedTest + @ValueSource(strings = { "garbage", "#1", "#1:2:3", "#a:b", "#1:", "#:1" }) + void aRidThatIsNotARidIsRefusedAsATypeMismatch(final String text) { + createFixtures(); + + assertThatThrownBy(() -> { + try (final ResultSet resultSet = database.query("sql", "MATCH {rid: '" + text + "', as: p} RETURN p")) { + while (resultSet.hasNext()) + resultSet.next(); + } + })// + .isExactlyInstanceOf(TypeMismatchException.class)// + .hasMessageContaining("Cannot convert to RID: " + text); + } + + private void assertRefusedAsNotAVertex(final String sql, final String kind, final RID offender, final Object... parameters) { + assertThatThrownBy(() -> inTransaction(sql, parameters))// + .isExactlyInstanceOf(TypeMismatchException.class)// + .as("the refusal is a typed one, with no Java cast exception under it: %s", sql)// + .hasNoCause()// + .hasMessage("Invalid vertex for edge creation: the " + kind + " " + offender + " is not a vertex"); + } + + private void inTransaction(final String sql, final Object... parameters) { + database.transaction(() -> drainCommand(sql, parameters)); + } + + /** Runs the command to its end: the statements are lazy, and one that is not pulled does nothing. */ + private void drainCommand(final String sql, final Object... parameters) { + try (final ResultSet resultSet = database.command("sql", sql, parameters)) { + while (resultSet.hasNext()) + resultSet.next(); + } + } + + /** The count of the stored links, read by a scan: the counter {@code count(*)} answers from is not ground truth. */ + private long linkCount() { + try (final ResultSet resultSet = database.query("sql", "SELECT count(@rid) AS n FROM Link12425")) { + return resultSet.next().getProperty("n").longValue(); + } + } + + private void createFixtures() { + database.getSchema().createVertexType("V12425"); + database.getSchema().createEdgeType("Link12425"); + database.getSchema().createEdgeType("Wire12425"); + database.getSchema().createDocumentType("Doc12425"); + + database.transaction(() -> { + final MutableVertex a = database.newVertex("V12425").set("k", "a").save(); + final MutableVertex b = database.newVertex("V12425").set("k", "b").save(); + vertexRid = a.getIdentity(); + otherVertexRid = b.getIdentity(); + documentRid = database.newDocument("Doc12425").set("k", "d").save().getIdentity(); + edgeRid = a.newEdge("Wire12425", b).getIdentity(); + }); + } +} diff --git a/engine/src/test/java/com/arcadedb/query/sql/executor/MatchPatternRegressionTest.java b/engine/src/test/java/com/arcadedb/query/sql/executor/MatchPatternRegressionTest.java index 067f0827067..32ff0cd3790 100644 --- a/engine/src/test/java/com/arcadedb/query/sql/executor/MatchPatternRegressionTest.java +++ b/engine/src/test/java/com/arcadedb/query/sql/executor/MatchPatternRegressionTest.java @@ -23,6 +23,7 @@ import com.arcadedb.database.Identifiable; import com.arcadedb.database.RID; import com.arcadedb.exception.CommandExecutionException; +import com.arcadedb.exception.CommandSQLParsingException; import com.arcadedb.exception.HeapLimitExceededException; import com.arcadedb.exception.SchemaException; import com.arcadedb.exception.TimeoutException; @@ -492,7 +493,7 @@ void bareRidOnAProjectionIsRefused() { for (final String direction : new String[] { "", " ASC", " DESC" }) assertThatThrownBy(() -> database.query("sql", "MATCH {type:S, as:s}.out('R'){as:p} RETURN s.@rid AS srid, p.n AS pn ORDER BY @rid" + direction).close())// - .isInstanceOf(CommandExecutionException.class)// + .isInstanceOf(CommandSQLParsingException.class)// .hasMessageContaining("ORDER BY @rid has no meaning on the rows of this MATCH")// .hasMessageContaining(".@rid"); } @@ -502,7 +503,7 @@ void bareRidOnAProjectionIsRefused() { void bareTypeOnAProjectionIsRefused() { orderByRecordAttributeGraph(); assertThatThrownBy(() -> database.query("sql", "MATCH {type:S, as:s} RETURN s.n AS n ORDER BY @type").close())// - .isInstanceOf(CommandExecutionException.class)// + .isInstanceOf(CommandSQLParsingException.class)// .hasMessageContaining("ORDER BY @type has no meaning"); } @@ -511,9 +512,9 @@ void bareTypeOnAProjectionIsRefused() { void bareRidOnPathsAndPatternsIsRefused() { orderByRecordAttributeGraph(); assertThatThrownBy(() -> database.query("sql", "MATCH {type:S, as:s}.out('R'){as:p} RETURN $paths ORDER BY @rid").close())// - .isInstanceOf(CommandExecutionException.class); + .isInstanceOf(CommandSQLParsingException.class); assertThatThrownBy(() -> database.query("sql", "MATCH {type:S, as:s}.out('R'){as:p} RETURN $patterns ORDER BY @rid").close())// - .isInstanceOf(CommandExecutionException.class); + .isInstanceOf(CommandSQLParsingException.class); } /** Regression test for issue #9911. */ diff --git a/server/src/test/java/com/arcadedb/server/http/Issue12425CallerMistakesInGraphStatementsAre400Test.java b/server/src/test/java/com/arcadedb/server/http/Issue12425CallerMistakesInGraphStatementsAre400Test.java new file mode 100644 index 00000000000..74005c0d8e4 --- /dev/null +++ b/server/src/test/java/com/arcadedb/server/http/Issue12425CallerMistakesInGraphStatementsAre400Test.java @@ -0,0 +1,168 @@ +/* + * Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com) + * SPDX-License-Identifier: Apache-2.0 + */ +package com.arcadedb.server.http; + +import com.arcadedb.serializer.json.JSONObject; +import com.arcadedb.server.BaseGraphServerTest; +import com.arcadedb.server.StaticBaseServerTest; +import org.junit.jupiter.api.Test; + +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Issue #12425: the graph statements answered HTTP 500 for a mistake of the caller, and one of them leaked a raw + * {@code java.lang.ClassCastException}. The HTTP API reference reserves 500 for a failure of the server itself and lists 400 + * for a statement the server refuses to run. Nothing is written by any of them. + */ +class Issue12425CallerMistakesInGraphStatementsAre400Test extends BaseGraphServerTest { + + @Test + void anEndpointThatIsADocumentIsRefusedWithAMessageAndNothingIsWritten() throws Exception { + final String documentRid = createFixtures(); + + final Response response = command("sql", "CREATE EDGE Link12425 FROM " + documentRid + " TO " + vertexRid); + + assertThat(response.status).as(response.body).isEqualTo(400); + assertThat(response.body).as("the answer names the cause").contains("Invalid vertex for edge creation"); + assertThat(response.body).as("the answer names the record").contains(documentRid); + assertThat(response.body).as("no Java class name reaches the client").doesNotContain("java.lang.ClassCastException"); + assertThat(edgeCount()).as("nothing is written").isZero(); + } + + @Test + void anEndpointThatIsADocumentRidGivenAsAStringIsRefusedNotAnsweredAsMissing() throws Exception { + final String documentRid = createFixtures(); + + final Response response = command("sql", "CREATE EDGE Link12425 FROM :from TO :to", + new JSONObject().put("from", documentRid).put("to", vertexRid)); + + assertThat(response.status).as("the record exists, so 404 would be a wrong answer: " + response.body).isEqualTo(400); + assertThat(response.body).contains("Invalid vertex for edge creation"); + assertThat(response.body).contains(documentRid); + assertThat(edgeCount()).as("nothing is written").isZero(); + } + + @Test + void aQueryThatReturnsADocumentAsAnEndpointIsRefusedWithAMessageAndNothingIsWritten() throws Exception { + createFixtures(); + + final Response from = command("sql", "CREATE EDGE Link12425 FROM (SELECT FROM Doc12425) TO (SELECT FROM V12425)"); + assertThat(from.status).as(from.body).isEqualTo(400); + assertThat(from.body).contains("Invalid vertex for edge creation"); + + final Response to = command("sql", "CREATE EDGE Link12425 FROM (SELECT FROM V12425) TO (SELECT FROM Doc12425)"); + assertThat(to.status).as(to.body).isEqualTo(400); + assertThat(to.body).contains("Invalid vertex for edge creation"); + + assertThat(edgeCount()).as("nothing is written").isZero(); + } + + @Test + void aRidThatIsNotARidIsRefusedWithAMessage() throws Exception { + createFixtures(); + + final Response response = command("sql", "MATCH {rid: 'garbage', as: p} RETURN p"); + + assertThat(response.status).as(response.body).isEqualTo(400); + assertThat(response.body).contains("Cannot convert to RID: garbage"); + } + + @Test + void aBareRidOrderByOnTheRowsOfAMatchIsRefusedWithAMessage() throws Exception { + createFixtures(); + + final Response response = command("sql", "MATCH {type: V12425, as: p} RETURN p.k AS k ORDER BY @rid"); + + assertThat(response.status).as(response.body).isEqualTo(400); + assertThat(response.body).contains("ORDER BY @rid has no meaning on the rows of this MATCH"); + } + + @Test + void aValidEdgeBetweenTwoVerticesIsStillCreated() throws Exception { + createFixtures(); + + final Response response = command("sql", "CREATE EDGE Link12425 FROM " + vertexRid + " TO " + vertexRid); + + assertThat(response.status).as(response.body).isEqualTo(200); + assertThat(edgeCount()).isEqualTo(1L); + } + + private String vertexRid; + + /** Creates the types and one record of each kind; answers the RID of the document and keeps the RID of the vertex. */ + private String createFixtures() throws Exception { + for (final String sql : new String[] { "CREATE VERTEX TYPE V12425", "CREATE PROPERTY V12425.k STRING", + "CREATE EDGE TYPE Link12425", "CREATE DOCUMENT TYPE Doc12425" }) + assertThat(command("sql", sql).status).as(sql).isEqualTo(200); + + vertexRid = ridOf(command("sql", "INSERT INTO V12425 SET k = 'a'")); + return ridOf(command("sql", "INSERT INTO Doc12425 SET k = 'd'")); + } + + private static String ridOf(final Response response) { + assertThat(response.status).as(response.body).isEqualTo(200); + return new JSONObject(response.body).getJSONArray("result").getJSONObject(0).getString("@rid"); + } + + private long edgeCount() throws Exception { + final Response response = command("sql", "SELECT count(@rid) AS n FROM Link12425"); + assertThat(response.status).as(response.body).isEqualTo(200); + return new JSONObject(response.body).getJSONArray("result").getJSONObject(0).getLong("n"); + } + + private Response command(final String language, final String command) throws Exception { + return command(language, command, null); + } + + private Response command(final String language, final String command, final JSONObject params) throws Exception { + final HttpURLConnection connection = + (HttpURLConnection) new URI(getServerHttpUrl("/api/v1/command/" + getDatabaseName())).toURL().openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "application/json"); + final String credentials = + Base64.getEncoder().encodeToString(("root:" + StaticBaseServerTest.DEFAULT_PASSWORD_FOR_TESTS).getBytes(StandardCharsets.UTF_8)); + connection.setRequestProperty("Authorization", "Basic " + credentials); + connection.setDoOutput(true); + final JSONObject request = new JSONObject().put("language", language).put("command", command); + if (params != null) + request.put("params", params); + final byte[] payload = request.toString().getBytes(StandardCharsets.UTF_8); + try (final OutputStream out = connection.getOutputStream()) { + out.write(payload); + } + try { + final int status = connection.getResponseCode(); + final InputStream in = status >= 400 ? connection.getErrorStream() : connection.getInputStream(); + final String body = in == null ? "" : new String(in.readAllBytes(), StandardCharsets.UTF_8); + return new Response(status, body); + } finally { + connection.disconnect(); + } + } + + private record Response(int status, String body) { + } +}