Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Roland Kalmogo
Roland Kalmogo
25,657 Points

REST API with Sparkjava: custom ApiClient

Hello everybody. I have troubles with ApiClient class provided for testing functionally sparkjava REST API. this class is here :

https://raw.githubusercontent.com/treehouse-projects/java-spark-rest-api/master/src/test/java/com/teamtreehouse/testing/ApiClient.java

My API class is like :

public class Api {

private static final String DATA_FORMAT = "application/json";
public static void main(String[] args) {
    if (args.length > 0) {
        if (args.length != 1) {
            System.out.println("Kaerengo api <port>");
            System.exit(0);
        }
        port(Integer.parseInt(args[0]));

    }
    Gson gson = new Gson();
    FormationDAO formationDAO = new HbnFormationDAO();

    post("/formations", DATA_FORMAT, (req, res) -> {
        Formation formation = gson.fromJson(req.body(), SimpleFormation.class);
        formationDAO.addFormation(formation);
        res.status(201);
        return formation;
    } , gson::toJson);

    after((req, res) -> {
        res.type(DATA_FORMAT);
    });

}

}

This is my functional test class:

public class ApiTest {

private static final String PORT = "8000";
private Gson gson;
private ApiClient client;

@BeforeClass
public static void setUpBeforeClass() throws Exception {

    String[] args = { PORT };
    Api.main(args);
}

@AfterClass
public static void tearDownAfterClass() throws Exception {
    Spark.stop();
}

@Before
public void init() {
    gson = new Gson();
    client = new ApiClient("http://localhost:" + PORT);
}

@Test
public void EtantDonneeUneRequeteDeCreationDeFormation_quandRequeteSoumise_AlorsFormationCree() {
    Map<String, String> values = new HashMap<>();
    values.put("nom", "Informatique");
    values.put("description", "La filiere magnifique");

    ApiResponse res = client.request("POST", "/formations", gson.toJson(values));

    assertEquals(201, res.getStatus());
}

}

I get this error :

java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at java.net.Socket.connect(Socket.java:538) at sun.net.NetworkClient.doConnect(NetworkClient.java:180) at sun.net.www.http.HttpClient.openServer(HttpClient.java:432) at sun.net.www.http.HttpClient.openServer(HttpClient.java:527) at sun.net.www.http.HttpClient.<init>(HttpClient.java:211) at sun.net.www.http.HttpClient.New(HttpClient.java:308) at sun.net.www.http.HttpClient.New(HttpClient.java:326) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1168) at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1104) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:998) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:932) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1282) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1257) at org.team226.kaerengo.testing.ApiClient.request(ApiClient.java:32) at org.team226.kaerengo.ApiTest.EtantDonneeUneRequeteDeCreationDeFormation_quandRequeteSoumise_AlorsFormationCree(ApiTest.java:48) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [main] INFO spark.webserver.SparkServer - >>> Spark shutting down ... [main] INFO spark.webserver.SparkServer - done

I READ SO MUCH ABOUT QUERYING WITH JAVA AND I AM STILL STRUGGLING WITH MY PROBLEM. HELP PLEASE :(

2 Answers

Roland Kalmogo
Roland Kalmogo
25,657 Points

Yes , let me change the version and I'll be back soon.

Thank you. (I'm pretty sure too the problem is there!!! :))

Roland Kalmogo
Roland Kalmogo
25,657 Points

Thank you very much. My test bar is GREEN

So happy !!!!!!!

Alexander Nikiforov
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 Points

Can you give a link to a whole project on Github so that I can download it and try to run? It is hard to find error just by looking at these lines of code.

Also in testing always put this @BeforeClass:

@BeforeClass
public static void setUpBeforeClass() throws Exception {

    String[] args = { PORT };
    Api.main(args);
    // wait until server is up and running
    Spark.awaitInitialization();
}

This could be solution to your problem, but I'm not sure. I had the problem with connection a lot. You could have connection problem because server is not yet up and running. That is why your POST request doesn't work. Try that out and give the link to github project to download if possible.

Docs for awaitInitialization: http://sparkjava.com/documentation.html#awaitinit

Roland Kalmogo
Roland Kalmogo
25,657 Points

Hello Alexander.

I am very happy to read you. here is the link to my project : https://github.com/rokal/kaerengo-core I've tried to use Spark.awaitInitialization but it seems that the method is unknown.

I'm still digging. Thanks again.

Alexander Nikiforov
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 Points

I'm pretty sure that you have to include this awaitInitialization.

try this:

import spark.Spark;
@BeforeClass
public static void setUpBeforeClass() throws Exception {

    String[] args = { PORT };
    Api.main(args);
    // wait until server is up and running
    Spark.awaitInitialization();
}

or this:

import static spark.Spark.*;
@BeforeClass
public static void setUpBeforeClass() throws Exception {

    String[] args = { PORT };
    Api.main(args);
    // wait until server is up and running
    awaitInitialization();
}

I had the same problem and this solved it. Thanks!