I'm new to BaseX and I'm trying to connect to a BaseX server initialized from my program
and later trying to connect to it
BaseXServer server = new BaseXServer();
ClientSession session = new ClientSession("localhost", 1984, "admin", "admin");
and shows to me this error
Exception in thread "main" .basex.server.LoginException: Access denied: admin.
at .basex.api.client.ClientSession.<init>(ClientSession.java:123)
at .basex.api.client.ClientSession.<init>(ClientSession.java:76)
at TextBasexCrud.main(TextBasexCrud.java:39)
The thing is that when I try to start it from CMD or PowerShell, using the command basexserver
, I don't have problem connecting to it from my program.
I've tried to find information about this but I haven't found it. I would really appreciate some help.
Here is my whole code:
import .basex.*;
import .basex.api.client.*;
import .basex.core.*;
import .basex.core.cmd.*;
import java.io.*;
import java.util.Scanner;
/**
* Programa que implementa operaciones CRUD en una base de datos XML usando BaseX.
* El programa pregunta al usuario el nombre de la base de datos y, si no existe, la crea.
* Luego se ofrece un menú para realizar las operaciones:
* - Crear (insertar un nuevo registro)
* - Leer
* - Actualizar
* - Eliminar
*
* Nota: Al realizar la inserción, el usuario debe introducir una ruta XPath válida (por ejemplo, /books)
* que indique en qué nodo se debe insertar el XML.
*/
public final class TextBasexCrud {
private static Scanner scanner = new Scanner(System.in);
public static void main(final String[] args) throws Exception {
System.out.println("=== BaseX CRUD Operations ===");
// Crear el contexto global
final Context context = new Context();
BaseXServer server = new BaseXServer();
System.out.println("\n* Create a client session.");
ClientSession session = new ClientSession("localhost", 1984, "admin", "admin");
// Solicitar el nombre de la base de datos
System.out.print("Enter the database name: ");
String dbName = scanner.nextLine();
// Verificar si la base de datos existe; si no, se crea
if (!checkDatabaseExists(session, dbName)) {
createDatabase(session, dbName);
}
// Menú de operaciones CRUD
String operation;
do {
System.out.println("\nSelect operation:");
System.out.println("1. Create Record");
System.out.println("2. Read Records");
System.out.println("3. Update Record");
System.out.println("4. Delete Record");
System.out.println("5. Exit");
System.out.print("Enter choice (1-5): ");
operation = scanner.nextLine();
switch (operation) {
case "1":
createRecord(session, dbName);
break;
case "2":
readRecord(session, dbName);
break;
case "3":
updateRecord(session, dbName);
break;
case "4":
deleteRecord(session, dbName);
break;
case "5":
System.out.println("Exiting program.");
server.stop();
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (!operation.equals("5"));
context.close();
}
private static boolean checkDatabaseExists(ClientSession session, String dbName) {
try {
session.execute("OPEN " + dbName);
System.out.println("Database '" + dbName + "' found.");
return true;
} catch (IOException e) {
System.out.println("Database '" + dbName + "' not found.");
return false;
}
}
private static void createDatabase(ClientSession session, String dbName) throws IOException {
System.out.println("Creating database '" + dbName + "'...");
// XML de ejemplo: un contenedor "books" que almacenará documentos
String xml = "<books><book><title>Sample Book</title><author>Sample Author</author></book></books>";
session.execute("CREATE DB " + dbName + " " + '"' + xml + '"');
System.out.println("Database '" + dbName + "' created successfully.");
}
private static void createRecord(ClientSession session, String dbName) {
System.out.println("\nCreating a new record...");
System.out.println("Enter XML to insert (e.g. <book><title>New Book</title></book>): ");
String xml = scanner.nextLine();
System.out.println("Enter the target XPath for insertion (e.g. /books or /books/book[1] before): ");
String targetXPath = scanner.nextLine();
// Construir el comando de actualización.
// Nota: Es responsabilidad del usuario introducir una expresión XPath válida que seleccione EXACTAMENTE un nodo.
// Se pueden usar las palabras clave 'into', 'before', 'after', 'as first into', etc.
String command = "XQUERY insert nodes " + xml + " into " + targetXPath;
try {
session.execute(command);
System.out.println("Record inserted successfully into database '" + dbName + "'.");
} catch (IOException e) {
System.out.println("Error during insert: " + e.getMessage());
}
}
// Ejecuta una consulta XQuery para leer registros
private static void readRecord(ClientSession session, String dbName) {
System.out.println("\nReading records...");
System.out.print("Enter XQuery to run (e.g. //book): ");
String query = scanner.nextLine();
try {
String result = session.execute("XQUERY " + query);
System.out.println("Query result:\n" + result);
} catch (IOException e) {
System.out.println("Error during read: " + e.getMessage());
}
}
private static void updateRecord(ClientSession session, String dbName) {
System.out.println("\nUpdating a record...");
System.out.print("Enter XQuery update command (e.g. update replace //book[title='Old Book']/title with <title>New Title</title>): ");
String updateQuery = scanner.nextLine();
try {
session.execute("XQUERY " + updateQuery);
System.out.println("Record updated successfully.");
} catch (IOException e) {
System.out.println("Error during update: " + e.getMessage());
}
}
private static void deleteRecord(ClientSession session, String dbName) {
System.out.println("\nDeleting a record...");
System.out.print("Enter XQuery delete command (e.g. delete //book[title='Old Book']): ");
String deleteQuery = scanner.nextLine();
try {
session.execute("XQUERY " + deleteQuery);
System.out.println("Record deleted successfully.");
} catch (IOException e) {
System.out.println("Error during delete: " + e.getMessage());
}
}
}
I'm using BaseX version 11.7 and here is my POM
<project xmlns=".0.0"
xmlns:xsi=";
xsi:schemaLocation=".0.0 .0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cat.fxp</groupId>
<artifactId>basex-crud-fx</artifactId>
<version>1.0-SNAPSHOT</version>
<repositories>
<repository>
<id>basex</id>
<name>BaseX Maven Repository</name>
<url>;/url>
</repository>
</repositories>
<properties>
<mavenpiler.source>11</mavenpiler.source>
<mavenpiler.target>11</mavenpiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Última versión estable -->
</properties>
<dependencies>
<dependency>
<groupId>.basex</groupId>
<artifactId>basex</artifactId>
<version>11.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
I tried to put a Thread.sleep(10000)
after starting it, but it didn't work. Maybe creating it from the program uses other credentials, I don't really know.