Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Rest service doesn't find @GET Method (Jersey Rest service in Gradle).

+1
−1

I have to implement a JSON based REST web service for querying literature. Ordinary users should be able to query data and process it in their clients. The "main user" can adapt database entries via the server or add new entries. The server should accept queries and fetch the corresponding data from the database and then deliver it to the requesting client. The clients should be implemented using JavaFX, transform the requested data in Java objects and present their content to the user.

Pretty much everything up until the part where the client has to present the data works just fine. But for some reason every time the result the client gets is empty.

While debugging the Clientmethod, I always get error 404, so it seems it doesn't find my @GET.

Dataprocessing class:

public class DataProcessing {

    private final Client client;
    private final String base_uri;

    public DataProcessing(String uri) {
        this.client = ClientBuilder.newClient();
        this.base_uri = uri;
    }

    public JsonObject get(String uri){
        WebTarget target = getTarget("GET", uri);
        Response response = target.request().accept(MediaType.APPLICATION_JSON).get();
        JsonObject result = response.readEntity(javax.json.JsonObject.class);
        System.out.println(target);
        return result;
    }
    private WebTarget getTarget(String crud, String uri) {
        System.out.println(base_uri + uri);
        return client.target (base_uri + uri);
    }

}

Rest class:

@Path("select")
public class LiteraturRest {

    Boolean empty;
    static DatabaseCreator dbs = DatabaseCreator.getInstance();

    private ArrayList<Book> books = new ArrayList<>();



    @GET
    @Path("all")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getAll() {
        JsonObject json;
        try{
            json = search(dbs.allBooks());
        }
        catch (SQLException e) {
            throw new RuntimeException(e);
        }
        System.out.println("jsjsjsjsjssj: " + json);
        return Response.ok(json).build();
    }

    public JsonObject search(ResultSet resultSet) throws SQLException {
        JsonObject json = null;
        try{
            Bibliothek bibliothek;
            ArrayList<Book>resultBookList= new ArrayList<>();
            empty = true;
            while(resultSet.next()){
                int id = resultSet.getInt("id");
                String titel = resultSet.getString("buchtitel");
                String autoren = resultSet.getString("autoren");
                String verlag = resultSet.getString("verlag");
                String teilgebiet = resultSet.getString("teilgebiete");
                Double preis = resultSet.getDouble("preis");

                Book book = new Book(titel,autoren,verlag,teilgebiet,id,preis);
                resultBookList.add(book);
                empty = false;
            }
            if (!empty){
                bibliothek = new Bibliothek(resultBookList);
                ObjectMapper objectMapper = new ObjectMapper();
                String JSONString = objectMapper.writeValueAsString(bibliothek);
                System.out.println("JSONString: " + JSONString);
                JsonReader jsonReader = Json.createReader(new StringReader(JSONString));
                json = jsonReader.readObject();
                System.out.println("jsonObject: " + json);
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        System.out.println(json);
        return json;
    }
}


### Client:

```java
public class ClientView extends Application {
    @Override
    public void start(Stage stage) throws IOException {
        final String BASE_URI = "http://localhost:8080/rest";
        DataProcessing dataProcessing = new DataProcessing(BASE_URI);

        final URL fxmlURL = this.getClass().getResource("/client-view.fxml");
        FXMLLoader fxmlLoader = new FXMLLoader(fxmlURL);
        final Parent root = fxmlLoader.load();

        ChoiceBox choiceBox = new ChoiceBox(FXCollections.observableArrayList("Alle", "Medieninformatik",
                "Praktische Informatik", "Rechtsinformatik", "Sozioinformatik", "Technische Informatik",
                "Theoretische Informatik", "Wirtschaftsinformatik"));
        choiceBox.setValue("Alle");
        choiceBox.setLayoutX(0);
        choiceBox.setLayoutY(0);

        TextArea searchbar = new TextArea();
        searchbar.setLayoutX(240);
        searchbar.setPrefHeight(10);
        searchbar.setPrefWidth(400);

        Button search = new Button();
        search.setLayoutX(170);
        search.setText("Search");

        TextArea output = new TextArea();
        output.setPrefWidth(500);
        output.setPrefHeight(300);
        output.setEditable(false);
        output.setLayoutX(200);
        output.setLayoutY(50);

        search.setOnMouseClicked(mouseEvent -> {
            String URI = "";
            String choice = choiceBox.getValue().toString();
            String term = "Java";

            switch(choice){
                case "Alle":
                    URI = "/select/all";
                    break;
            }
            JsonObject result = dataProcessing.get(URI);
            String outputText = "";
            if (result == null){
                System.out.println("Keine Ergebnisse gefunden");
            }
            else{
                JsonArray library = result.getJsonArray("books");
                ArrayList<JsonObject>booksArrayList = new ArrayList<>();

                for (int i = 0; i < library.size(); i++){
                    booksArrayList.add(library.getJsonObject(i));
                }

                for (int j = 0; j < booksArrayList.size(); j++){
                    String titel = booksArrayList.get(j).getString("buchtitel");
                    int id = booksArrayList.get(j).getInt("id");
                    outputText += "Titel: " + titel + "\nID: " + id;
                }
            }
            output.clear();
            output.setText(outputText);
        });

        Group components = new Group();
        components.getChildren().addAll(choiceBox,output,search,searchbar);

        stage.setTitle("Informatik Literatur!");
        stage.setScene(new Scene(components));
        stage.setResizable(true);
        stage.show();
    }
}


public class LiteraturApplication extends Application {
    private Set<Object> singletons = new HashSet<>();
    private Set <Class<?>> classes = new HashSet <>();

    public LiteraturApplication(){
        singletons.add(new LiteraturRest());
        classes.add(LiteraturRest.class);
    }

    @Override
    public Set <Class <?>> getClasses () { return classes ; }

    @Override
    public Set <Object > getSingletons () { return singletons ; }

}

Server-Main:

public class Main {
    public static void main(String[] args) throws URISyntaxException, IOException, SQLException {
        Logger.getLogger("org.glassfish").setLevel(Level.ALL);

        URI baseUri = new URI("http://localhost:8080/rest");
        ResourceConfig config = ResourceConfig.forApplicationClass(LiteraturApplication.class);
        config.register(LiteraturRest.class);
        HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, config);

        StaticHttpHandler handler = new StaticHttpHandler("web");
        handler.setFileCacheEnabled(false);

        ServerConfiguration serverConfig = server.getServerConfiguration();
        serverConfig.addHttpHandler(handler, "/");

        if(!server.isStarted()) server.start();
        System.out.println(baseUri); //Port
        System.out.println("Press ENTER to stop the server");
        System.in.read();
        DatabaseCreator dbs = DatabaseCreator.getInstance();
        LiteraturRest literaturRest = new LiteraturRest();
        literaturRest.search(dbs.allBooks());
        System.out.println("probe" + literaturRest.search(dbs.allBooks()));
        server.shutdownNow();
    }
}

Database class:

public class DatabaseCreator {

    private static DatabaseCreator dbs = new DatabaseCreator();

    private Connection connection;

    private DatabaseCreator(){
        try{
            String url = "jdbc:mysql://localhost/informatik";
            String username = "minf";
            String password= "prog3";
            this.connection = DriverManager.getConnection(url,username,password);
            createTable(connection);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }


    public static DatabaseCreator getInstance(){
        return dbs;
    }

   
    private void createTable(Connection connection){

        String path = new File("m29576_Hausarbeit_prog3\\Server\\src\\main\\resources\\csv-data\\data.csv").getAbsolutePath();

        int batchSize=20;
        try {
            String table = "CREATE TABLE IF NOT EXISTS literatur " +
                    "(buchtitel VARCHAR(200), " +
                    " autoren VARCHAR(200), " +
                    " verlag VARCHAR(200), " +
                    " teilgebiete VARCHAR(200), " +
                    " preis DOUBLE(5,2),"+
                    " id INTEGER not null )";
            Statement stmt = connection.createStatement();
            // create a new table
            stmt.executeUpdate("DROP TABLE IF EXISTS literatur");
            stmt.execute(table);

            String sql="insert into literatur(buchtitel,autoren,verlag,teilgebiete,preis,id) values (?,?,?,?,?,?)";

            PreparedStatement statement=connection.prepareStatement(sql);

            BufferedReader lineReader=new BufferedReader(new FileReader(path));

            String lineText = "";
            String splitter = ";";
            int count=0;
            int zahl=0;

            lineReader.readLine();
            while ((lineText=lineReader.readLine())!=null){
                String[] data=lineText.split(splitter);
                zahl++;

                System.out.println(Arrays.asList(data));
                System.out.println(data.length);
                System.out.println(zahl);
                String buchtitel = data[0];
                String autoren=data[1];
                String verlag=data[2];
                String teilgebiete=data[3];
                String preis=data[4];
                String id=data[5];

                statement.setString(1,buchtitel);
                statement.setString(2,autoren);
                statement.setString(3,verlag);
                statement.setString(4,teilgebiete);
                statement.setDouble(5, Double.parseDouble(preis));
                statement.setInt(6,parseInt(id));
                statement.addBatch();
                if(count%batchSize==0){
                    statement.executeBatch();
                }
            }
            lineReader.close();
            statement.executeBatch();
            //connection.close();
            System.out.println("Data has been inserted successfully.");
        } catch (SQLException | FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static String sql1 = "SELECT * from literatur";

    public ResultSet allBooks() throws SQLException {
        PreparedStatement statement = connection.prepareStatement(sql1);
        ResultSet rs = statement.executeQuery(sql1);
        return rs;
    }
History
Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

1 comment thread

Have you tried reaching the endpoint using cURL, or a browser? Did that also give a 404? (1 comment)

0 answers

Sign up to answer this question »