ksoap2 evelope.getResponse gets a nullpointerException - exception

Ok, here is my Problem:
I am sending a soap-Request and i get a valid answer, everything is correctly working and i get the valid output within the responsedump.
But calling evelope.getResponse() in:
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//adding parameters
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.setAddAdornments(false);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject so = (SoapObject) envelope.getResponse();
throws this exception:
Caused by: java.lang.NullPointerException
at org.ksoap2.serialization.SoapSerializationEnvelope.getResponse(SoapSerializationEnvelope.java:521)
the Error is within the getResponse
from the source of ksoap2:
/**
* Response from the soap call. Pulls the object from the wrapper object and returns it.
*
* #since 2.0.3
* #return response from the soap call.
* #throws SoapFault
*/
public Object getResponse() throws SoapFault {
if (bodyIn instanceof SoapFault) {
throw (SoapFault) bodyIn;
}
KvmSerializable ks = (KvmSerializable) bodyIn; <-- Line 521
if (ks.getPropertyCount()==0) {
return null;
} else if(ks.getPropertyCount()==1) {
return ks.getProperty(0);
} else {
Vector ret = new Vector();
for(int i=0;i<ks.getPropertyCount();i++){
ret.add(ks.getProperty(i));
}
return ret;
}
}

try this instead of SoapObject
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

Related

Control character error, possibly incorrectly encoded

I'm working on Mobile application with codenameone linked to symfony 4, user can participate to contest of videos i have this tables users,participation,video,concour everything is working very well but when i try to participate it brings me all the data correcty but it shows me this error: Control character error, possibly incorrectly encoded i hope that someone could help Me thank you.
This is my fonction on symfony4 :
*
*
* #Route("/api/competition/participate/", name="api_competitions_participate")
* #param Request $request
* #return Response
* #throws Exception
*/
public function participateAction(Request $request)
{
$r=$request->query->get('video');
$encoders = [new XmlEncoder(), new JsonEncoder()];
$normalizers = [new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);
$video = $serializer->deserialize($r, Video::class, 'json');
$u=$this->getDoctrine()->getRepository(Users::class)->find($video->getOwner()['id']);
$video->setOwner($u);
$video->setPublishdate(new \DateTime('now'));
dump($video);
$r2=$request->query->get('participation');
$participation= $serializer->deserialize($r2, Participation::class, 'json');
$c=$this->getDoctrine()->getRepository(Concour::class)->find($participation->getConcour()['id']);
$participation->setUser($u);
$participation->setConcour($c);
$participation->setVideo($video);
$participation->setDateParticipation($video->getPublishdate());
dump($participation);
$em = $this->getDoctrine()->getManager();
$em->persist($video);
$em->persist($participation);
$em->flush();
dump($r);
return new JsonResponse();
}
and this is the function on codenameone
public void participate(Video v, Participation cp) {
Gson gson = new Gson();
String json = gson.toJson(v);
String json2 = gson.toJson(cp);
String url = Statics.BASE_URL + "/api/competition/participate/?video=" + json + "&participation=" + json2;
con.setUrl(url);
con.addResponseListener(new ActionListener<NetworkEvent>() {
#Override
public void actionPerformed(NetworkEvent evt) {
String str = new String(con.getResponseData());
System.out.println(str);
Dialog.show("Confirmation", "Your Video has been successfully added", "Ok", null);
con.removeResponseListener(this);
}
});
NetworkManager.getInstance().addToQueueAndWait(con);
I'm not familiar with Symfony so I'm not sure if this is the right answer. Also your approach of passing JSON in a get query is considered bad form by most. Normally JSON would be passed in the POST method body for REST calls.
To properly encode use this:
String url = Statics.BASE_URL + "/api/competition/participate/"
con.setUrl(url);
con.addArgument("video", json);
con.addArgument("participation", json2);
Also make sure the ConnectionRequest is constructed with false to indicate this is a GET operation and not POST.

In AS3/AIR how can I execute the result method of a responder object?

We are creating an extension for the NetConnection object. When we get an error we will retry “n” times. After “n” times we want to call the responder result method returning an error. The responder object contains two properties, both functions, however we cannot seem to see how to access those functions. Is it possible to execute the “result” function of Responder object?
An example might be;
_rspResponder:Responder = new Responder(someFunction);
// lots of code...
_rspResponder.result("Error: Connection timeout failure.\n A network connection error occurred, if needed please try to save work and restart the application.\n Otherwise just restart the application.\n");
Edit:
Based on comments below I created an extended responder like;
package com.fluorinefx
{
import flash.net.Responder;
public class PublicResponder extends Responder
{
/**
* result - Result handler function
*
* #return result
*/
private var _result:Function = null;
public function get result():Function
{
return this._result;
}
public function set result(value:Function):void
{
this._result = value;
}
/**
* status - Status (error) handler function
*
* #return status
*/
private var _status:Function = null;
public function get status():Function
{
return this._status;
}
public function set status(value:Function):void
{
this._status = value;
}
public function PublicResponder(result:Function, status:Function=null)
{
_result = _result;
_status = status;
super(result, status);
}
}
}
When I attempt to use it in my extended NetConnection like;
import com.fluorinefx.PublicResponder;
private var _rspResponder:PublicResponder;
public override function call(strCommand:String, rspResponder:Responder, ...parameters:Array):void
_rspResponder = rspResponder;
I get an implicit coercion error on the "_rspResponder = rspResponder;" line.
After “n” times we want to call the responder result method returning an error.
Is it possible to execute the result function of the Responder object?
Does something like this setup help you?
//# global vars
public var _rspResponder :Responder;
public var try_count :int = 0;
//# test it...
_rspResponder = new Responder( onResult, onError );
//# Since "result" param can be Object or String... using asterix to allow any data-type
private function onResult( result:* ) :void
{
trace( result ); try_count = 0;
}
//# no comment needed here...
private function onError( error:Object ) :void
{
try_count++;
_rspResponder = new Responder( onResult, onError ); //# retry again
//# after N retries, send custom error String to "onResult" function
if ( try_count == 5)
{
onResult( "Error: Connection timeout failure.\n A network connection error occurred, if needed please try to save work and restart the application.\n Otherwise just restart the application.\n" );
}
}

How do I get the json object in the request body in webflux?

I am trying to parse json data from request body to JsonOject.
Spring Reactive get body JSONObject using ServerRequest
// it didn't work.
JSONObject bodyData = serverRequest.bodyToMono(JSONObject.class).toProcessor().peek();
I tried it as referenced in the link above, but it didn't work.
I want to know why this is.
For the test, two router beans were created as shown below.
// router
#Bean
public RouterFunction<ServerResponse> routeJsonBodyPOST2(JsonObjectHandler jsonObjectHandler) {
return route(RequestPredicates.POST("/json/post2")
.and(accept(APPLICATION_JSON)).and(contentType(APPLICATION_JSON)), jsonObjectHandler::getStringByJsonObject);
}
#Bean
public RouterFunction<ServerResponse> routeJsonBodyPOST3(JsonObjectHandler jsonObjectHandler) {
return route(RequestPredicates.POST("/json/post3")
.and(accept(APPLICATION_JSON)).and(contentType(APPLICATION_JSON)), jsonObjectHandler::getJsonObject);
}
// handler
// I checked the json data in onNext. I understood this.
public Mono<ServerResponse> getStringByJsonObject(ServerRequest request) {
Mono<String> response = request.bodyToMono(JSONObject.class).log()
.map(jsonObject -> {
String name = (String) jsonObject.get("name");
System.out.println(name);
return name;
});
return ServerResponse.ok()
.body(response, String.class);
}
// Only onComplete is called and exits. I don't understand this.
public Mono<ServerResponse> getJsonObject(ServerRequest request) {
Mono<JSONObject> response = request.bodyToMono(JSONObject.class).log();
response.onErrorResume(error -> {
System.out.println(error);
return Mono.error(error);
}).subscribe(
jsonObject -> System.out.println("test : " + jsonObject),
error -> System.out.println(error.getMessage()),
() -> System.out.println("complete")
);
// Mono<JSONObject> jsonObjectMono = request.bodyToMono(JSONObject.class);
// jsonObjectMono.subscribe(System.out::println);
// JSONObject peek = jsonObjectMono.toProcessor().peek();
// System.out.println(peek);
// just for test.
return ServerResponse.ok().build();
}

Applitools openBase() failed with com.applitools.eyes.EyesException

I'm unable to figure out why is this code failing, I browsed through Applitools tutorials and I can't figure out what is happening here.
This is the exception being thrown:
com.applitools.eyes.EyesException: eyes.openBase() failed
at com.applitools.eyes.EyesBase.openBase(EyesBase.java:1037)
at com.applitools.eyes.selenium.SeleniumEyes.open(SeleniumEyes.java:246)
at com.applitools.eyes.selenium.Eyes.open(Eyes.java:77)
at com.applitools.eyes.selenium.Eyes.open(Eyes.java:1374)
at BaseTests.validateWindow(BaseTests.java:49)
at SearchTests.testSearchByFullTitle(SearchTests.java:11)
This is SearchTests:
import org.junit.Test;
public class SearchTests extends BaseTests {
#Test
public void testSearchByFullTitle(){
String title = "Agile Testing";
page.search(title);
validateWindow();
}
}
Validate window method:
public void validateWindow(){
eyes.open(driver, "Automation Bookstore", "neka metoda npr: "+
Thread.currentThread().getStackTrace()[2].getMethodName());
eyes.checkWindow();
eyes.close();
}
and the class throwing the exception:
protected void openBase() throws EyesException {
openLogger();
int retry = 0;
do {
try {
if (isDisabled) {
logger.verbose("Ignored");
return;
}
sessionEventHandlers.testStarted(getAUTSessionId());
validateApiKey();
logOpenBase();
validateSessionOpen();
initProviders();
this.isViewportSizeSet = false;
sessionEventHandlers.initStarted();
beforeOpen();
RectangleSize viewportSize = getViewportSizeForOpen();
viewportSizeHandler.set(viewportSize);
try {
if (viewportSize != null) {
ensureRunningSession();
}
} catch (Exception e) {
GeneralUtils.logExceptionStackTrace(logger, e);
retry++;
continue;
}
this.validationId = -1;
isOpen = true;
afterOpen();
return;
} catch (EyesException e) {
logger.log(e.getMessage());
logger.getLogHandler().close();
throw e;
}
} while (MAX_ITERATION > retry);
throw new EyesException("eyes.openBase() failed");
}
After some debugging, I found that I had a typo in my API key. After fixing that, works as expected.
In my case, the same issue was caused by using null as a value for the testName parameter.
I didn't understand it from the beginning, cause I relied on the javadoc for the open function:
/**
* Starts a test.
*
* #param driver The web driver that controls the browser hosting the application under test.
* #param appName The name of the application under test.
* #param testName The test name. (i.e., the visible part of the document's body) or {#code null} to use the current window's viewport.
* #return A wrapped WebDriver which enables SeleniumEyes trigger recording and frame handling.
*/
public WebDriver open(WebDriver driver, String appName, String testName) {
RectangleSize viewportSize = SeleniumEyes.getViewportSize(driver);
this.configuration.setAppName(appName);
this.configuration.setTestName(testName);
this.configuration.setViewportSize(viewportSize);
return open(driver);
}

grails spring security rest status 401 redirect to controller's action to throw custom error message

We are using spring-security-core:2.0-RC4, spring-security-rest:1.4.0 plugin with grails 2.4.2. Both of them are working fine. When user enters invalid credentials, spring-security-rest:1.4.0 plugin gives 401, which is configured in Config.groovy
grails.plugin.springsecurity.rest.login.failureStatusCode = 401
And here is the small snippet of console output
rest.RestAuthenticationFilter - Actual URI is /api/login; endpoint URL is /api/login
rest.RestAuthenticationFilter - Applying authentication filter to this request
credentials.DefaultJsonPayloadCredentialsExtractor - Extracted credentials from JSON payload. Username: admin#asdasdmopi.com, password: [PROTECTED]
rest.RestAuthenticationFilter - Trying to authenticate the request
authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
dao.DaoAuthenticationProvider - User 'admin#something.com' not found
rest.RestAuthenticationFilter - Authentication failed: Bad credentials
rest.RestAuthenticationFailureHandler - Setting status code to 401
context.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
Now there is no error message or response, just status 401 is send to client. Now I am trying to send a error response when there is 401 status.
Added following line in UrlMappings.groovy
"401"(controller:'unauthorized',action:'sendErrorResponse')
Created UnauthorizedController.groovy and added sendErrorResponse() as follows
def sendErrorResponse() {
try{
int errorCode = grailsApplication.config.customExceptions.account.fourZeroOne.loginNotAuthorized.errorCode
int status = grailsApplication.config.customExceptions.account.fourZeroOne.loginNotAuthorized.status
String message = grailsApplication.config.customExceptions.account.fourZeroOne.loginNotAuthorized.message
String extendedMessage = grailsApplication.config.customExceptions.account.fourZeroOne.loginNotAuthorized.extendedMessage
String moreInfo = grailsApplication.config.customExceptions.account.fourZeroOne.loginNotAuthorized.moreInfo
throw new AccountException(status,errorCode,message,extendedMessage,moreInfo)
}catch(AccountException e){
log.error e.errorResponse()
response.setStatus(e.errorResponse().status)
render e.errorResponse()
}
}
My thinking was that on 401 the controller will be called and the method will render error response, but It doesn't work.
Is my Approach right?
Any other Best practice or idea to implement this?
Any pointers in right direction are appreciated.
Thanks a ton.
You need to override grails.plugin.springsecurity.rest.RestAuthenticationFailureHandler bean with your own customized version.
It can be something like this:
#Slf4j
#CompileStatic
class CustomRestAuthenticationFailureHandler implements AuthenticationFailureHandler {
/**
* Configurable status code, by default: conf.rest.login.failureStatusCode?:HttpServletResponse.SC_FORBIDDEN
*/
Integer statusCode
MessageSource messageSource
/**
* Called when an authentication attempt fails.
* #param request the request during which the authentication attempt occurred.
* #param response the response.
* #param exception the exception which was thrown to reject the authentication request.
*/
void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.setStatus(statusCode)
response.addHeader('WWW-Authenticate', Holders.config.get("grails.plugin.springsecurity.rest.token.validation.headerName").toString())
def errorMessage
if (exception instanceof AccountExpiredException) {
errorMessage = messageSource.getMessage("springSecurity.errors.login.expired", null as Object[], LocaleContextHolder.getLocale())
} else if (exception instanceof CredentialsExpiredException) {
errorMessage = messageSource.getMessage("springSecurity.errors.login.passwordExpired", null as Object[], LocaleContextHolder.getLocale())
} else if (exception instanceof DisabledException) {
errorMessage = messageSource.getMessage("springSecurity.errors.login.disabled", null as Object[], LocaleContextHolder.getLocale())
} else if (exception instanceof LockedException) {
errorMessage = messageSource.getMessage("springSecurity.errors.login.locked", null as Object[], LocaleContextHolder.getLocale())
} else {
errorMessage = messageSource.getMessage("springSecurity.errors.login.fail", null as Object[], LocaleContextHolder.getLocale())
}
PrintWriter out = response.getWriter()
response.setContentType("aplication/json")
response.setCharacterEncoding("UTF-8");
out.print(new JsonBuilder([message: errorMessage]).toString());
out.flush();
}
}
And in your resources.groovy you should have
restAuthenticationFailureHandler(CustomRestAuthenticationFailureHandler) {
statusCode = HttpServletResponse.SC_UNAUTHORIZED
messageSource = ref("messageSource")
}