Android Retrofit 2.0: no response to HTTP call - retrofit

I am an Android developer, I am working with Retrofit. The first day I had a response but the second day the response did not come, why I will working after I can uninstall and install the app then only it will work why, how to I resolve it please help me...
private void HomeWorks() {
HomeWorkApi homeWorkApi =
MissReportServer.getClient().create(HomeWorkApi.class);
Call<VrrittamResponse<ArrayList<HomeWork>>> call =
homeWorkApi.getHomeWork(access_token);
call.enqueue(new Callback<VrrittamResponse<ArrayList<HomeWork>>>() {
#Override
public void onResponse(Call<VrrittamResponse<ArrayList<HomeWork>>> call, Response<VrrittamResponse<ArrayList<HomeWork>>> response) {
try {
ArrayList<HomeWork> homeWork = response.body().getContent();
if (homeWork != null && !homeWork.isEmpty()) {
recyclerView.setAdapter(new HomeWorkAdapter(homeWork,
R.layout.list_item_homework, getActivity()));
}
else {
ExceptionHandle.alertDialogNotShow(getActivity());
}
}
catch (Exception ex){
ExceptionHandle.alertDialogNotShow(getActivity());
}
}
#Override
public void onFailure(Call<VrrittamResponse<ArrayList<HomeWork>>> call, Throwable t) {
Log.e("TAG",t.getMessage());
ExceptionHandle.alertDialogShow(getActivity());
}
});
}

Related

Send Data to HTML Template through Spring AOP?

I'd like to wrap all the controller methods using Spring AOP for Error Handling.
But, How to send e.getMessage() in catch block to ${errorMessage} in error.html properly?
Thanks for the response!
#Pointcut("within(com.test.mvc.controller.*) && #within(org.springframework.stereotype.Controller)")
public void controllerLayer() {
}
#Pointcut("execution(public String *(..))")
public void publicMethod() {
}
#Pointcut("controllerLayer() && publicMethod()")
public void controllerPublicMethod() {
}
#Around("controllerPublicMethod()")
public String processRequest(ProceedingJoinPoint joinPoint) {
try {
return (String) joinPoint.proceed();
} catch (Throwable e) {
LOGGER.info("{}", e.getMessage());
return "error.html";
}
}
<body>
<h1>Something went wrong!</h1>
<h3 th:text="'Error Message: ' + ${errorMessage}"></h3>
</body>
Following aspect can set the request attribute to display errorMessage.
#Around("controllerPublicMethod()")
public Object processRequest(ProceedingJoinPoint joinPoint) {
Object object=null;
try {
object = joinPoint.proceed();
} catch (Throwable e) {
RequestContextHolder.getRequestAttributes().setAttribute("errorMessage",e.getMessage(),0); // scope 0 - request , 1 - session
return "error.html";
}
return object;
}
I recommend you please explore the possibilities of #ControllerAdvice

Write unit test cases for Servlet

I want to write the testcase to fetch the real path of this application-jars and procedd further. Can someone please help to write the testcase.
I am new to unit testing so not sure how to write test cases for servlets .
public void init(ServletConfig config) throws ServletException {
try {
Properties props = loadProperties();
info("Loaded properties: " + jnlpprops);
String appsStr = checkAppsExists(props);
supportedApps = Arrays.asList(appsStr.split(","));
applicationjars = config.getServletContext().getRealPath("application-jars");
if (applicationjars == null) {
throw new ServletException("Cannot find path for application jars");
}
populateJarFileNames(applicationjars);
} catch (ServletException e) {
throw e;
} finally {
}
}

Mobile map package returns null for map

I downloaded Arcgis sample mmpk file and even I made a mmpk myself.
In both files I have 1 map(checked by debug) but when I try load the map (with codes in Esri guide page) it returns null for map.
Good to say that I can show online map in my map view and android studio shows no warning or error.
import static n.k.masoud.sbmap.R.id.mapView;
public class ActivityMain extends AppCompatActivity {
private MapView mMapView;
private ArcGISMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMapView = (MapView) findViewById(mapView);
code and file from main site
try {File mmpkFile = new File(Environment.getExternalStorageDirectory(),"devlabs-package.mmpk");
String mmpkPath = mmpkFile.getAbsolutePath();
final MobileMapPackage mobileMapPackage=new MobileMapPackage(mmpkPath);
mobileMapPackage.addDoneLoadingListener(new Runnable() {
#Override
public void run() {
this if gets false
if (mobileMapPackage.getLoadStatus() == LoadStatus.LOADED) {
showMessage(String.format("Number of maps = %d", mobileMapPackage.getMaps().size()));
map = mobileMapPackage.getMaps().get(0);
} else {
dealWithLoadFailure();
}
}
});
mobileMapPackage.loadAsync();
}
catch (Exception err){
Log.e("TAG", "onCreate: "+err);
}
map.addDoneLoadingListener(new Runnable() {
#Override
public void run() {
if (map.getLoadStatus() == LoadStatus.LOADED) {
Log.e("TAG", "run: map loaded ok" );
// Once map is loaded, can check its properties and content
if (map.getBookmarks().size() > 0) {
}
} else {
dealWithLoadFailure();
}
}
});
map.loadAsync();
As I told part below works correctly
// for online maps
// ArcGISMap map = new ArcGISMap(Basemap.Type.TOPOGRAPHIC, 29.453826, 60.852134,12);
mMapView.setMap(map);
mMapView.addLayerViewStateChangedListener(new LayerViewStateChangedListener() {
#Override
public void layerViewStateChanged(LayerViewStateChangedEvent layerViewStateChangedEvent) {
// Each layer may have more than one layer view state.
StringBuilder layerStatuses = new StringBuilder();
for (LayerViewStatus status : layerViewStateChangedEvent.getLayerViewStatus()) {
if (layerStatuses.length() > 0) {
layerStatuses.append(",");
} layerStatuses.append(status.name());
}
showMessage(String.format("Layer '%s' status=%s", layerViewStateChangedEvent.getLayer().getName(), layerStatuses.toString()));
} });
}
#Override
protected void onPause(){
mMapView.pause();
super.onPause();
}
#Override
protected void onResume(){
super.onResume();
mMapView.resume();
}
}
if the line
if (mobileMapPackage.getLoadStatus() == LoadStatus.LOADED)
is returning false, then the mobile map package is not loaded and won't contain any maps.
In your dealWithLoadFailure() function you can retrieve the load error:
mobileMapPackage.getLoadError()
and see what it is. It should tell you what the error causing the load failure is.
One of my friends tried this way but didn't got any result just like me.
So he changed the official guide code to this and got well response.
I think he got code from Internet , so I don't know about it's copyright permission.
private void setupMobileMap() {
if (mMapView != null) {
File mmpkFile = new File(Environment.getExternalStorageDirectory(), "devlabs-package.mmpk");
final MobileMapPackage mapPackage = new MobileMapPackage(mmpkFile.getAbsolutePath());
mapPackage.addDoneLoadingListener(new Runnable() {
#Override
public void run() {
// Verify the file loaded and there is at least one map
if (mapPackage.getLoadStatus() == LoadStatus.LOADED && mapPackage.getMaps().size() > 0) {
mMapView.setMap(mapPackage.getMaps().get(0));
} else {
// Error if the mobile map package fails to load or there are no maps included in the package
//setupMap();
//Log for Error
}
}
});
mapPackage.loadAsync();
}
}

WinRun4J - service not stopping

I'm using this to install my application as a windows service. Everything works fine except the service does not stop;
#Override
public int serviceMain(String[] strings) throws ServiceException {
try {
System.out.println("BootService: init");
System.out.println("BootService: service loop start");
while (ws.isServiceRunning()) {
System.out.println("BootService: loop");
ws.serviceHandler();
}
System.out.println("BootService: stopped");
return 0;
} catch (Exception ex) {
throw new ServiceException(ex);
}
}
#Override
public int serviceRequest(int control) throws ServiceException {
try {
switch (control) {
case SERVICE_CONTROL_SHUTDOWN:
case SERVICE_CONTROL_STOP:
if (ws!=null) {
ws.stopService();
}
break;
}
return 0;
} catch (WindowsServiceException ex) {
throw new ServiceException(ex);
}
}
My service backend code is stopped by the call to serviceRequest(), which in turn makes the loop in serviceMain() exit. I see the message "BootService: stopped" in my logs, yet the Window Control Panel Services Applet just sits says "Stopping service...", but it never does.
What would stop the service from stopping even though I'm sure it has exited the serviceMain() without error?
I donĀ“t know if you could solve it, but I had a simmilar problem and I fixed it by adding a timer that called System.exit(0)
public int serviceMain(String[] args) throws ServiceException {
while (!shutdown) {
try {
if (!myservice.isRunning()) {
(new Thread(new LaucherRunnable(args))).start();
}
Thread.sleep(6000);
} catch (InterruptedException e) {
}
}
periodicRunner.stop();
Timer t = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
t.setRepeats(false);
t.start();
return 0;
}

GWT: unable to access xml

I'm trying to access a XML file from client side in GWT. But it looks like the sendRequest method is not getting fired at all.
I'm able to see the xml in the browser. Do I need to do any thing in the server side?
Any help is appreciated.
Here's my code
String xmlurl = "http://localhost:8888/test.xml";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(xmlurl));
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
System.out.println(exception);
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
System.out.println(response.getText());
} else {
System.out.println(response.getStatusCode());
}
}
});
} catch (RequestException e) {
System.out.println("exception"+e);
}
I tried the following code too, but have the same problem. The developer tool shows response status as 200 and correct response text. Only, its not working in the code.
String xmlurl = "http://127.0.0.1:8888/test.xml";
httpGetFile(xmlurl, new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
xmlData = "Error";
}
public void onSuccess(String xmlText) {
xmlData = xmlText;
}
});
public static void httpGetFile(final String url, final AsyncCallback<String> callback) {
final RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url);
rb.setCallback(new RequestCallback() {
public void onResponseReceived(Request request, Response response) {
try {
System.out.println("dafadfdf");
final int responseCode = response.getStatusCode() / 100;
if (url.startsWith("file:/") || (responseCode == 2)) {
callback.onSuccess(response.getText());
} else {
callback.onFailure(new IllegalStateException("HttpError#" + response.getStatusCode() + " - " + response.getStatusText()));
}
} catch (Throwable e) {
callback.onFailure(e);
}
}
public void onError(Request request, Throwable exception) {
callback.onFailure(exception);
}
});
try {
rb.send();
} catch (RequestException e) {
callback.onFailure(e);
}
}
Always Use logging instead of System.out.print statements https://developers.google.com/web-toolkit/doc/latest/DevGuideLogging
Step 1 - Add logging statements to failure, success and try catch statements. Clean up the exception.
Step 2 - "Parsing the XML" should be done inside the "onSuccess" method of the rb callback.
You do not need a RequestBuilder at all to access an XML file. You can use an ExternalTextResource for this:
https://developers.google.com/web-toolkit/doc/latest/DevGuideClientBundle#TextResource

Resources