I am new in java development and try to learn Retrofit api i am getting exception can any one help me ? i have paste my code and output exception below kindly take a look of it
Thank you ,
package com.company;
import com.sun.deploy.util.SessionState;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Client;
import retrofit.client.Request;
import retrofit.client.Response;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
// write your code here
RetrofitInterface retrofitInterface = (RetrofitInterface)new RestAdapter.Builder().setEndpoint("http://localhost:8080/new_pro").build().create(RetrofitInterface.class);
retrofitInterface.getUser(222, new Callback<String>() {
#Override
public void success(String s, Response response) {
//System.out.print(s);
}
#Override
public void failure(RetrofitError retrofitError) {
}
});
}
}
Output
Exception in thread "main" java.lang.IllegalArgumentException: RetrofitInterface.getUser: Must have return type or Callback as last argument, not both.
at retrofit.RestMethodInfo.methodError(RestMethodInfo.java:107)
at retrofit.RestMethodInfo.parseResponseType(RestMethodInfo.java:267)
at retrofit.RestMethodInfo.<init>(RestMethodInfo.java:97)
at retrofit.RestAdapter.getMethodInfo(RestAdapter.java:213)
at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:236)
at com.sun.proxy.$Proxy0.getUser(Unknown Source)
at com.company.Main.main(Main.java:19)
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:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Previous Interface i was using
public interface RetrofitInterface {
// asynchronously with a callback
#GET("/")
Header getUser(#Query("user_id") int userId, Callback<Header> callback);
}
Modified Interface i am using and its working.
public interface RetrofitInterface {
// asynchronously with a callback
#GET("/")
void getUser(#Query("user_id") int userId, Callback<Header> callback);
}
Related
When the Task includes 2 lines opening a stream and closing it, the Task returns correctly. Its succeed method runs. But the Service' setOnSucceeded method does not run. Why?
When the 2 lines about the streaming opening and closing are commented out in the Task, we do get the expected behavior: System.out.println("in the succeed method of the Service") does print.
The Main method:
package Test;
import javafx.application.Application;
import javafx.concurrent.Worker;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
MyService pluginUpdateService = new MyService();
pluginUpdateService.setOnFailed(e -> {
System.out.println("task failed");
});
pluginUpdateService.setOnSucceeded(e -> {
System.out.println("in the succeed method of the Service"); // this does not print, when MyTask opens the stream (see code of MyTask)
});
// launching the service
if (pluginUpdateService.getState() == Worker.State.READY) {
pluginUpdateService.start();
}
}
}
The service MyService
package Test;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
public class MyService extends Service {
public MyService() {
}
#Override
protected Task createTask() {
Task updater = new MyTask();
return updater;
}
}
The task MyTask:
package Test;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javafx.concurrent.Task;
public class MyTask extends Task {
public MyTask() {
}
#Override
protected Void call() throws MalformedURLException, IOException {
InputStream in;
URL url = new URL("https://clementlevallois.net");
in = url.openStream(); // when this line is commented out, the Service does trigger its setOnSucceeded method as expected
in.close(); // when this line is commented out, the Service does trigger its setOnSucceeded method as expected
System.out.println("about to return from the call method of the Task");
return null;
}
#Override
protected void succeeded() {
super.succeeded();
System.out.println("succeeded - sent from the succeeded method of the Task");
}
#Override
protected void cancelled() {
super.cancelled();
System.out.println("cancelled");
updateMessage("Cancelled!");
}
#Override
protected void failed() {
super.failed();
System.out.println("failed");
updateMessage("Failed!");
}
}
I'm trying to mock a private method (executeGetRequest) and in the line that I'm declaring the mock that I want returned for the private method, the private method is actually being executed with null arguments, therefore throwing a NullPointerException.
VlcPlayerMinimal.java:
package com.nicobrest.kamehouse.vlcrc.model;
public class VlcPlayerMinimal {
public static void main(String[] args) {
String vlcRcStatus = new VlcPlayerMinimal().getVlcRcStatus();
System.out.println(vlcRcStatus);
}
public String getVlcRcStatus() {
Client client = new Client();
GetRequest getRequest = new GetRequest();
String vlcRcStatus = executeGetRequest(client, getRequest);
return vlcRcStatus;
}
private String executeGetRequest(Client client, GetRequest getRequest) {
return client.execute(getRequest);
}
private class Client {
public String execute(GetRequest getRequest) {
return "{status: playing, id: 1}";
}
}
private class GetRequest {
}
}
VlcPlayerMinimalTest.java:
package com.nicobrest.kamehouse.model;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import com.nicobrest.kamehouse.vlcrc.model.VlcPlayerMinimal;
import org.junit.Test;
import org.powermock.api.mockito.PowerMockito;
public class VlcPlayerMinimalTest {
#Test
public void getVlcRcStatusTest() {
VlcPlayerMinimal vlcPlayerSpy = PowerMockito.spy(new VlcPlayerMinimal());
try {
PowerMockito.doReturn("{status: stopped, id: 2}").when(vlcPlayerSpy, "executeGetRequest", any(), any());
String vlcRcStatus = vlcPlayerSpy.getVlcRcStatus();
System.out.println(vlcRcStatus);
} catch (Exception e) {
e.printStackTrace();
fail("Unexpected exception thrown.");
}
}
}
Stack trace:
java.lang.NullPointerException
at com.nicobrest.kamehouse.vlcrc.model.VlcPlayerMinimal.executeGetRequest(VlcPlayerMinimal.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1846)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:810)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:675)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:401)
at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:95)
at com.nicobrest.kamehouse.model.VlcPlayerMinimalTest.getVlcRcStatusTest(VlcPlayerMinimalTest.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...
It appears PowerMockito is actually calling the method that I'm trying to mock in the line PowerMockito.doReturn("{status: stopped, id: 2}").when(vlcPlayerSpy, "executeGetRequest", any(), any());
And it's throwing the exception because client is null, so it's calling execute(getClient) on null, but that's the method I'm trying to avoid to call in the test.
Any ideas how to fix this? I've been trying for a while without success.
I'm using Java 8, powermock 1.7.3 and junit 4.12
This Test is Succesful:
package foo.bar;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(VlcPlayerMinimal.class)
public class VlcPlayerMinimalTest {
#Test
public void getVlcRcStatusTest() {
VlcPlayerMinimal vlcPlayerSpy = PowerMockito.spy(new VlcPlayerMinimal());
try {
PowerMockito.doReturn("{status: stopped, id: 2}").when(vlcPlayerSpy, "executeGetRequest", Mockito.any(), Mockito.any());
String vlcRcStatus = vlcPlayerSpy.getVlcRcStatus();
System.out.println(vlcRcStatus);
} catch (Exception e) {
e.printStackTrace();
fail("Unexpected exception thrown.");
}
}
}
You need these Class Level Annotations:
#RunWith(PowerMockRunner.class)
#PrepareForTest(VlcPlayerMinimal.class)
Console Output:
{status: stopped, id: 2}
Hello my code makes a simple http request and returns a json. My Code works fine but when i try to extend AppCompatActivity (because i want to show the json on device screen) it gaves me multiple errors my code is below
package com.vogella.java.library.okhttp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
public class TestMain extends AppCompatActivity {
OkHttpClient client = new OkHttpClient();
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
String doPostRequest(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public static void main(String[] args) throws IOException, JSONException {
String username = "test";
String password = "123";
TestMain example = new TestMain();
String json = "";
String postResponse = example.doPostRequest("http://86.145.89.53:8080/authentication_service-dev/authenticate?username=" + username + "&password=" + password, json);
int counter = postResponse.length();
if (counter == 14) {
System.out.println("Your username or password is invalid!!");
}
if (counter > 1000) {
System.out.println("HTTP Status 401 – Unauthhorized");
}
if (counter < 1000 && counter > 14) {
System.out.println("Welcome!!");
}
}}
the errors are :
Exception in thread "main" java.lang.RuntimeException: Stub!
at android.content.Context.<init>(Context.java:20)
at android.content.ContextWrapper.<init>(ContextWrapper.java:21)
at android.view.ContextThemeWrapper.<init>(ContextThemeWrapper.java:21)
at android.app.Activity.<init>(Activity.java:22)
at android.support.v4.app.SupportActivity.<init>(SupportActivity.java:31)
at android.support.v4.app.BaseFragmentActivityGingerbread.<init>(BaseFragmentActivityGingerbread.java:37)
at android.support.v4.app.BaseFragmentActivityHoneycomb.<init>(BaseFragmentActivityHoneycomb.java:29)
at android.support.v4.app.BaseFragmentActivityJB.<init>(BaseFragmentActivityJB.java:30)
at android.support.v4.app.FragmentActivity.<init>(FragmentActivity.java:79)
at android.support.v7.app.AppCompatActivity.<init>(AppCompatActivity.java:61)
at com.vogella.java.library.okhttp.TestMain.<init>(TestMain.java:18)
at com.vogella.java.library.okhttp.TestMain.main(TestMain.java:52)
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:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
You don't use public static void main in Android dev. In the activity, you use onCreate:
#Override
public void onCreate(Bundle sis){
super.onCreate(sis);
//Move the contents of "public static void main" here
}
And delete public static void main when you have moved the code.
Android activities must have onCreate() method, when you extend any class with AppCompactAcitvity it must implement some methods
Change your code, remove main method, add onCreate() and do stuff there.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acremote);
}
Have a look at activities life cycle Link.
I have written a Java RMI chat application. There are four classes and two interfaces. Here they are:
ChatClient
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Scanner;
com.za.tutorial.rmi.server.ChatServerIF;
public class ChatClient extends UnicastRemoteObject implements ChatClientIF,Runnable {
private ChatServerIF chatServer;
private String name = null;
protected ChatClient(String name, ChatServerIF chatServer) throws RemoteException {
this.name = name;
this.chatServer = chatServer;
chatServer.registerChatClient(this);
}
public void retrieveMessage(String message) throws RemoteException {
// TODO Auto-generated method stub
System.out.println(message);
}
public void run() {
Scanner scanner = new Scanner(System.in);
String message;
while(true){
message = scanner.nextLine();
try {
chatServer.broadcastMessage(name + " : " + message);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
ChatClientDriver
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import com.za.tutorial.rmi.server.ChatServerIF;
public class ChatClientDriver {
public static void main(String[] args) throws MalformedURLException, RemoteException, NotBoundException {
String chatServerURL = "rmi://localhost/RMIChatServer";
ChatServerIF chatServer = (ChatServerIF) Naming.lookup(chatServerURL);
new Thread(new ChatClient(args[0],chatServer)).start();
}
}
ChatClientInterface
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface ChatClientIF extends Remote {
void retrieveMessage(String message) throws RemoteException;
}
ChatServer
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import com.za.tutorial.rmi.client.ChatClientIF;
public class ChatServer extends UnicastRemoteObject implements ChatServerIF {
private ArrayList<ChatClientIF> chatClients;
protected ChatServer() throws RemoteException {
chatClients = new ArrayList<ChatClientIF>();
}
public synchronized void registerChatClient(ChatClientIF chatClient)
throws RemoteException {
this.chatClients.add(chatClient);
}
public synchronized void broadcastMessage(String message) throws RemoteException {
int i = 0;
while(i < chatClients.size()){
chatClients.get(i++).retrieveMessage(message);
}
}
}
ChatServerDriver
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
public class ChatServerDriver {
public static void main(String[] args) throws RemoteException, MalformedURLException {
Naming.rebind("RMIChatServer", new ChatServer());
}
}
ChatServerInterface
import java.rmi.Remote;
import java.rmi.RemoteException;
import com.za.tutorial.rmi.client.ChatClientIF;
public interface ChatServerIF extends Remote {
void registerChatClient(ChatClientIF chatClient) throws RemoteException;
void broadcastMessage(String message) throws RemoteException;
}
When I run it on Commando, first of all I run rmic ChatClient and ChatServer, then rmiregistry. Then i run chatServerDriver which works completely fine. after that, when I run chatClientDriver with a name, I get the following error, I dont understand why :/ Can I get any solution for this?
Thanks :)
Exception in thread "main" java.rmi.NotBoundException: RMIChatServer
at sun.rmi.registry.RegistryImpl.lookup(RegistryImpl.java:136)
at sun.rmi.registry.RegistryImpl_Skel.dispatch(Unknown Source)
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:409)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:267)
at sun.rmi.transport.Transport$1.run(Transport.java:177)
at sun.rmi.transport.Transport$1.run(Transport.java:174)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
at sun.rmi.server.UnicastRef.invoke(Unknown Source)
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at java.rmi.Naming.lookup(Unknown Source)
at com.za.tutorial.rmi.client.ChatClientDriver.main(ChatClientDriver.java:15)
It also looks like you have a different address in Rebind to what is being used by the client to connect.
Naming.rebind("//localhost/RMIChatServer", new ChatServer());
There's an example implementation on the following Wikipedia page which may be worth comparing against your code.
http://en.wikipedia.org/wiki/Java_remote_method_invocation
Note that using Java 1.5+ you don't need to use rmic anymore see Do we really need to create Stub in java RMI?
I've been using the onStart method for a while and it works no problem, but when I try to override onBadRequest, I get an error:
Here's the class:
import models.User;
import play.Application;
import play.GlobalSettings;
import play.Logger;
import play.mvc.Result;
import views.html.error_page;
import static play.mvc.Results.badRequest;
public class Global extends GlobalSettings {
#Override
public void onStart(Application app){
Logger.info("Application started!");
// Check if the database is empty
if(User.find.findRowCount()==0){
Ebean.save((List) Yaml.load("initial-data.yml"));
}
}
#Override
public void onStop(Application app){
Logger.info("Application stopped!");
}
#Override
public Result onBadRequest(String uri, String error) {
Logger.info("Bad Request");
return badRequest(error_page.render());
}
}
The first two work no problem, but the third one causes the error.
Here's the API entry:
You used the old API.
Here's the API for Play 2.1.1:
http://www.playframework.com/documentation/api/2.1.1/java/play/GlobalSettings.html
Called when an action has been found, but the request parsing has failed.
Result onBadRequest(Http.RequestHeader request, java.lang.String error)
Called when an exception occurred.
Result onError(Http.RequestHeader request, java.lang.Throwable t)
This works:
#Override
public Result onError(Http.RequestHeader request, Throwable t){
Logger.error("Error thrown: " + t.getMessage());
return internalServerError(error_page.render());
}
This page was useful. I'm still confused why the API is wrong.
I hope this helps out somebody with a similar problem.