Catching exception for server not available - spring-boot

I am new in spring boot and programming world .I am trying to post data on another server. I am using rest template to do that. I want to catch an exception when the server is not available .I am not sure how to do that .It would be helpful if anyone can just guide me where to look .I find so many examples but its getting more confusing.
Thanks in advance for your help.

You can use #Error Handler for this.You can use in your controller class to look around how this works when called.
#PostMapping("/hello")
public void hello(String msg)
{
RestTemplate restTemplate= new RestTemplate();
HttpEntity<String>reqEntity= new HttpEntity<>(msg);
restTemplate.postForEntity(" paste your server url here", reqEntity, String.class);
}
#ExceptionHandler(ConnectException.class)
#ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public void func()
{
System.out.println("I am not able to connect");
}
As you mentioned the server is not running so it will be handled by below mentioned function func on which #Exception handler is declared.You can read on #Exception handler.Certainly there are many different ways to do it.

Related

Spring #ControllerAdvice/ #ExceptionHandler not working

My Spring Boot Service will do a job and exit after success with 0 (there is no restcontroller), but i want it aslo to exit on every exception so i added #ControllerAdvice on a class and put this method:
#ControllerAdvice
#RequiredArgsConstructor
#Slf4j
public class ImportInekData {
final InekService inekService;
final ImportDataService dataService;
public void doTheJob(){
log.info("Fetching new list from Inek.");
UpdatedList updatedList = inekService.getUpdatedList();
List<Standort> toBeUpdated = updatedList.getToBeUpdated();
List<String> toBeDeleted = updatedList.getToBeDeleted();
log.info("List fetched with " + toBeUpdated.size() + " valid entries to be updated and " + toBeDeleted.size() + " entries marked for deletion. ");
log.info("Pushing to DB...");
dataService.importAll(toBeUpdated);
}
#EventListener
public void onStart(ContextStartedEvent start){
log.info("Application started.");
doTheJob();
log.info("Import finished.");
SpringApplication.exit(start.getApplicationContext(), () -> 0);
}
#ExceptionHandler(value = Exception.class)
public String outOnException(Exception e){
log.error("Exception occurred see logs. Stopping..");
SpringApplication.exit(context, () -> -1);
return "dying";
}
}
All is working fine but when i throw an IllegalArgumentException the #ExceptionHandler method is not called. First i had a void method with no parameter and then i began trying with String return and at least one parameter - that is not needed.
How get this working? Is there a better way for my case to react on every exception?
Controller Advices in spring is a mechanism intended to properly handle the Exceptions at the level of spring MVC.
Spring MVC in a nutshell is a web framework, and as such, it assumes that you have some kind of web endpoint that is called by the end user or maybe frontend. This endpoint is an "entry-point" to your backend code that can have services, query the database, and so forth. If during this backend flow the exception is thrown in general you don't want that the web endpoint will return 500 internal server error, so spring provides tooling for convenient mapping of these exceptions: translating them to json with a "good-looking" message, with correct HTTP code, and so forth.
If you don't have any controllers, then the whole concept of controller advices is not applicable in your flow, so there is no point in using it...
Now the real question is what exactly do you want to achieve with this exception handling?
If Application context cannot start usually spring boot application will be closed gracefully...
If you want to close the application programmatically, make sure you've read this thread

unable to access gaana api via java from mashape

i am trying to access gaana api from java side by using mashape api
i am trying from a localhost. but, i am getting issues while trying to connect gaana api.
Below is my code in one of my rest service ( I am using spring-security and java8). I am Btech-CSE final year student.
#RestController
#RequestMapping("/api/ideas")
public class IdeaController {
#RequestMapping(method = RequestMethod.GET)
public void invokeGaanaAPI() throws UnirestException {
System.out.println("hello");
// These code snippets use an open-source library.
// HttpServletResponse<JsonNode> response =
Unirest.get("https://community-gaana.p.mashape.com/index.php?subtype=most_popular&type=song")
.header("X-Mashape-Key", "iWEvla5JyCmshafdpHdjoSdtPsHPp1Ily4qjsnCEiVxbQsY5tn")
.header("Accept", "application/json")
.asJson();
Unirest.get("https://community-gaana.p.mashape.com/user.php?type=registrationtoken")
.header("X-Mashape-Key", "iWEvla5JyCmshafdpHdjoSdtPsHPp1Ily4qjsnCEiVxbQsY5tn")
.header("Accept", "application/json")
.asJson();
System.out.println("hello");
}
}
I need help to proceed in this situation. any kind of help is fine for me. i am getting data as null. so, json conversion is throwing null pointer exception.
I am passionate to do this project.
Your data is null because you haven't assigned the Unirest.get() return value to anything.
Please read the docs on using this API.

CUCM AXL API wrong SoapAction

I want to make SQL query to CUCM DB. I generated Java classes from WSDL with Maven jaxb2 plugin, but Cisco AXL docs advice to use wsdl2java. I've got lot of Java classes with Req/Res endings (request and response as I understand). This is my code:
public class CUCMDatabaseConnector extends WebServiceGatewaySupport{
private String SOAP_ACTION = "CUCM:DB ver=10.5";
public void updateData(){
String END_USERS_REQUEST = REQUEST,
AXLurl = "https://" + properties.getCurrentCUCM_IP() + ":8443/axl/";
ExecuteSQLQueryReq sqlRequest = new ExecuteSQLQueryReq();
sqlRequest.setSql(END_USERS_REQUEST);
WebServiceTemplate template = getWebServiceTemplate();
template.setMessageSender(NullHostnameVerifier.getMessageSender());
ExecuteSQLQueryRes sqlResponse = (ExecuteSQLQueryRes) template
.marshalSendAndReceive(
AXLurl,
sqlRequest,
new WebServiceMessageCallback() {
#Override
public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
TransportContext context = TransportContextHolder.getTransportContext();
HttpUrlConnection connection = (HttpUrlConnection) context.getConnection();
//adding required headers
connection.addRequestHeader( "SOAPAction", SOAP_ACTION);
connection.addRequestHeader("Authorization", autenString);
}
}
});
}
}
}
But when I run it, I get error:
org.springframework.ws.soap.client.SoapFaultClientException: The endpoint reference (EPR) for the Operation not found is https://IP:8443/axl/services/AXLAPIService and the WSA Action = CUCM:DB ver=10.5 executeSQLQueryReq
So, as I see, problem is CUCM AXL service has executeSQLQuery method, but not executeSQLQueryReq.
How can I make Spring putting correct method in SoapAction? Or I need to use only wsdl2java?
UPDATE
When I was generating java classes, there was also .xsd schema in the directory. jaxb2 config pointed to WSDL file, however, I've got error URI [src/main/resources/AXLAPI.wsdl] does not provide the scheme part., and It looks like plugin built classes from xsd schema, not wsdl. But this wsdl was original file downloaded from CUCM. What could be wrong?
Found this link on developers.cisco.com. This how-to advices to use AXLPort, a kind of wrapper for making SOAP request to CUCM.
Looks to me, CUCM AXL SOAP interface is not the best choice to start working with Spring WS

Receiving files form PLUpload in WICKET

Im trying to integrate PLUpload into my wicket application. First steps are looking clear. Im able to choose files and when i click the "upload"-button i receive an request on server-side in my PLUploadBehavior based on AbstractDefaultAjaxBehavior. But it does not seems to be a MultiPart request.
public abstract class PLUploadBehavior extends AbstractDefaultAjaxBehavior {
public PLUploadBehavior() {
}
#Override
public void renderHead(final Component component, IHeaderResponse response) {
super.renderHead(component, response);
response.render(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(PLUploadBehavior.class, "plupload.full.min.js"));
StringBuffer script = new StringBuffer();
//build the init-script...
response.render(OnLoadHeaderItem.forScript(script.toString()));
}
#Override
protected void respond(AjaxRequestTarget target) {
Request request = getComponent().getRequest();
//received request here, but don't know hot to access files
if (request instanceof IMultipartWebRequest) {
System.out.println("Multipart!!!");
}
}
}
I followed the tutorial for plupload and have no form in my html template. There is none in the tutorial, so i think i don't need it. Anyone an idea to access the files on server-side?
After some more coffee i found the solution to my problem. The example on wicket in action can get adapted to the use with an Behavior. Thanks to Martin Grigorov and the great Wicket Team!

Jetty HttpServletResponse can't be modified

we want to use jPlayer, an HTML5 audio player with firefox in order to play .ogg files. We noticed that there are issues with HTML5 audio and firefox considering the MEME attribute in the HTTP response. In this case, our content-type resembles "audio/ogg;charset=UTF-8". We think that removing the charset encoding might result in firefox interpreting the file correctly.
Hence, I tried the following in my spring implementation:
response.setContentType("audio/ogg");
response.setCharacterEncoding("");
The first line should not set an encoding. Nevertheless, it's already present before in the response object (recognized this while debugging). The weird thing is: the second line doesn't change anything, the character encoding is not modified. This behavior is totally contradictory to the API description.
Reference: it does not work as described in sample #2 of this post: Jetty Response with no Charset
I appreciate any ideas how-to fix the problem.
Cheers,
Chris
"Works for me..." (although you should set the char encoding to null rather than "")
I wrote some sample code (below) and ran it against 7.4.5
I get the right content type being sent through.
I'm not sure what's going wrong for you - perhaps you could post some code.
My best guess is that you're trying to set the content-type after having already sent content. Since the content type is a header, you need to set it before any of the body gets committed.
public class JettyServer
{
public static class OggServlet extends HttpServlet
{
protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException
{
File file = new File("src/main/ogg/file.ogg");
response.setContentType("audio/ogg");
response.setCharacterEncoding(null);
response.setContentLength((int) file.length());
FileInputStream in = new FileInputStream(file);
int by;
while ((by = in.read()) != -1)
{
response.getOutputStream().write(by);
}
}
}
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
ServletContextHandler handler = new ServletContextHandler();
handler.addServlet(OggServlet.class, "/audio");
server.setHandler(handler);
server.start();
}
}
I don't know if this will do anything different, but you could try bypassing the convenience method and calling setHeader method directly:
setHeader("Content-Type", "audio/ogg");
If you really are stumbling over some kind of bug in Jetty, it's worth a shot.

Resources