com.apollographql.apollo.exception.ApolloHttpException: HTTP 500 Internal Server Error - apollo

I keep getting the HTTP 500 Internal Server Error in my android studio trying to call a loginQuery with apollo client for android, following this tutorial : link to apollo docs
Yet when I run the same query in graphiQL in my browser, it succeeds.
here's a picture of the error in studio :
here's my code:
String userNumber = numberInput.getText().toString();
String password = passwordInput.getText().toString();
Intent intent;
LogInQuery logInQuery = LogInQuery.builder().nationalID(userNumber).password(password).build();
apolloClient.query(logInQuery).enqueue(new ApolloCall.Callback<LogInQuery.Data>() {
#Override
public void onResponse(#NotNull Response<LogInQuery.Data> response) {
LogInQuery.Data data = response.getData();
List<Error> error = response.getErrors();
assert error != null;
String errorMessage = error.get(0).getMessage();
assert data != null;
Log.d(TAG, "onResponse: " + data.login() + "-" + data.login());
if(data.login() == null){
Log.e("Apollo", "an Error occurred : " + errorMessage);
runOnUiThread(() -> {
// Stuff that updates the UI
loading.setVisibility(View.GONE);
Toast.makeText(LogInActivity.this,
errorMessage, Toast.LENGTH_LONG).show();
});
} else {
runOnUiThread(() -> {
// Stuff that updates the UI
loading.setVisibility(View.GONE);
Toast.makeText(LogInActivity.this,
"New User Created!", Toast.LENGTH_LONG).show();
//Intent intent = new Intent(LogInActivity.this, LogInActivity.class);
//startActivity(intent);
});
}
}
#Override
public void onFailure(#NotNull ApolloException e) {
runOnUiThread(() -> {
Log.e("Apollo", "Error", e);
Toast.makeText(LogInActivity.this,
"An error occurred : " + e.getMessage(), Toast.LENGTH_LONG).show();
loading.setVisibility(View.GONE);
});
}
});
}
I can't find much on the internet to help me solve it. If it's duplicate, direct me to the correct answer.

Check your API in Postman. It's working fine or not! Please share API if possible.

Related

How to fix On error Facebook log in result in android

when I click on the button of sign in the window of choosing facebook profile appears ! but once I confirm the the profile the app crashes . And by using logs I figured out that the register call is not successful so I'have a facebook exeception which causes error , how can i find the source error ?
facebookSignInButton.setOnClickListener(View.OnClickListener {
// Login
Log.i(TAG,"CLICKED")
loginManager.logInWithReadPermissions(this, Arrays.asList("public_profile"))
Log.i(TAG,"Permissions")
loginManager.registerCallback(callbackManager,
object : FacebookCallback<LoginResult> {
override fun onSuccess(loginResult: LoginResult) {
Log.d(TAG, "Facebook token: " + loginResult.accessToken.token)
startActivity(Intent(applicationContext,MainActivity::class.java))
}
override fun onCancel() {
Log.i(TAG, "Facebook onCancel.")
}
override fun onError(error: FacebookException) {
Log.d(TAG, "Facebook onError.")
// This part is written in run console
}
})
})
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
callbackManager!!.onActivityResult(requestCode, resultCode, data)
Log.i(TAG,"RESULT"+resultCode.toString()) // this retrun -1
Log.i(TAG,"REQUEST"+requestCode.toString())
}
I expect starting a new activity while logging.
After printing the msg error the problem is in the hash key it doesn't match any key stored !
so instead if using line cmnds I just use this code in my on create function and then copy the hash key into your facebook developer app
val packageName = this.getApplicationContext().getPackageName()
val info : PackageInfo = getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
for ( signature in info.signatures) {
var md = MessageDigest.getInstance("SHA")
md.update(signature.toByteArray())
val hashKey = android.util.Base64.encodeToString(md.digest(), 0)
Log.i(TAG,"HADHKEEEY"+hashKey)
}
Log.i(TAG,"NAAAMEE"+packageName)

How to fix "Error unmarshalling response back from AWS, Response Body: Unknown error" in x.io using Unity AWS SDK for DynamoDB

I developed DynamoDB Tables for my application using unity SDK. Authentication is done using Cognito identities. When trying to read/write values to a table it is working in my local machine. But when the application is hosted in x.io I get an error.
I am not able to figure out the issue. There are not many resources to debug this error.
public void PostUserAccountDetails(UserAccounts userInfo)
{
DbContext.LoadAsync<UserAccounts>(userInfo.mailID, (result) =>
{
if (result.Exception == null)
{
var user = result.Result as UserAccounts;
Debug.Log(user == null ? true : false);
if (user == null)
{
Debug.Log("mail id is new");
signupText.text = "The mail id has never been used before";
DbContext.SaveAsync<UserAccounts>(userInfo, (res) =>
{
if (res.Exception == null)
{
Debug.Log("signed up successfully");
signupText.text = "signed up successfully";
}
else
{
Debug.Log("error while signing up");
signupText.text = "error while signing up";
}
});
}
else
{
Debug.Log("This mail id has already been used");
signupText.text = "This mail id has already been used";
}
}
else
{
Debug.Log(result.Exception.Message);
signupText.text = result.Exception.Message;
}
});
}
I get the error message
"Error unmarshalling response back from AWS, Response Body: Unknown error"

Spring WebFlux project that connects to ElasticSearch Unit Testing

I am currently working on a Spring WebFlux project that connects to ElasticSearch. I have a Rest Service that in turn calls a method in the Service Layer that connects to the ES. I am having trouble writing UnitTests for my Service Layer. Any help would be appreciated as this is the first time I am working with Reactive Programming. Below are the code snippets for my Controller and Service methods.
Controller Code :
#GetMapping(path = "/api/apis/services/{id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<ClassA> serviceApis(#PathVariable final String serviceKey) {
return apiService.getDataForService(serviceKey);
}
Service Layer :
#PreAuthorize("isFullyAuthenticated()")
public Flux<ClassA> getDataForService(
final String id) {
IdentityToken token = GSLSecurityContext.getCurrentUserIdentityToken();
if (token == null) {
return Flux.error(new Exception("No token found"));
}
String securityQueryJson = getSecurityShould(token);
String queryToRun = QUERY
.replace("XXX_SIZE_XXX", config.getValueAsString("scroll.size"))
.replace("XXX_SECURITY_SHOULD_XXX", securityQueryJson)
.replace("XXX_SERVICE_KEY_XXX", id);
WebClient client = ClientUtil.getDataLakeWebClient(config);
Flux<ClassA> response = getData(client, queryToRun);
return response;
}
The getData code is as below :
protected Flux<ClassA> getData(
final WebClient client,
final String queryToRun) {
String scrollTimeoutQuery = "?scroll=" + config.getValueAsString("scroll.timeout");
long timeout = config.getValueAsLong("query.timout");
return Flux.generate(
() -> null,
(scrollId, sink) -> {
ClassAWrapper lastWrapper = null;
if (scrollId == null) {
Mono<ClassAWrapper> wrapper = client.post()
.uri(getSearchURI() + scrollTimeoutQuery)
.body(BodyInserters.fromObject(queryToRun)).retrieve()
.bodyToMono(ClassAWrapper.class)
.onErrorMap(original -> new Exception("Unable to retrieve from elastic search for query " + queryToRun, original))
.log();
try {
lastWrapper = wrapper.block(Duration.ofSeconds(timeout));
} catch (IllegalStateException ex) {
LOG.error("Timedout after " + timeout + " seconds while getting data from elastic search for query " + queryToRun);
lastWrapper = null;
} catch (Exception ex) {
LOG.error("Error in getting message details",ex);
lastWrapper = null;
}
} else {
String scrollQuery = "{\"scroll\" : \"" + config.getValueAsString("scroll.timeout") + "\", \"scroll_id\" : \"" + scrollId + "\"}";
Mono<ClassAWrapper> wrapper = client.post()
.uri("_search/scroll")
.body(BodyInserters.fromObject(scrollQuery)).retrieve()
.bodyToMono(ClassAWrapper.class)
.onErrorMap(original -> new Exception("Unable to retrieve next page of data from elastic search", original))
.log();
try {
lastWrapper = wrapper.block(Duration.ofSeconds(timeout));
} catch (IllegalStateException ex) {
LOG.error("Timeout after " + timeout + " seconds while getting data from elastic search for query " + queryToRun);
lastWrapper = null;
} catch (Exception ex) {
LOG.error("Error in getting message details",ex);
lastWrapper = null;
}
}
if (lastWrapper == null || lastWrapper.getResult() == null || lastWrapper.getResult().getDetails().isEmpty()) {
sink.next(new ClassA());
sink.complete();
return null;
}
sink.next(lastWrapper.getResult());
return lastWrapper.getScrollId();
}
);
}
Here, queryToRun is the ES query to be executed. config is the configuration. I need to test the method "getDataForService()".

Parse-Server Facebook login

I am running into an issue with signing up a user into Parse-Server while using Facebook.
When the user clicks on the Sign up with facebook icon this code will run..
ParseFacebookUtils.logInWithReadPermissionsInBackground(LoginRegister.this, permissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
MethodContants.showLog(TAG, "Uh oh. The user cancelled the Facebook login.", true);
} else if (user.isNew()) {
MethodContants.showLog(TAG, "User logged in through Facebook", false);
getUserDetailsFromFacebook();
} else {
MethodContants.showLog(TAG, "User logged in through Facebook", false);
Intent intent = new Intent(LoginRegister.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
}
}
});
My getUserDetailsFromFacebook() method looks like this
private void getUserDetailsFromFacebook() {
GraphRequest graphRequest = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse response) {
try {
facebookUser = jsonObject.getString("name");
MethodContants.showLog(TAG, "json name object: " + jsonObject.getString("name"), false);
} catch (JSONException e) {
MethodContants.showLog(TAG, "Error when getting facebook name: " + e.getMessage(), true);
showToast("Error saving Facebook user.");
}
try {
facebookEmail = jsonObject.getString("email");
MethodContants.showLog(TAG, "json email object: " + jsonObject.getString("email"), false);
} catch (JSONException e) {
MethodContants.showLog(TAG, "Error when getting facebook email: " + e.getMessage(), true);
showToast("Error saving Facebook email.");
}
saveNewFacebookUser();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name,email");
graphRequest.setParameters(parameters);
graphRequest.executeAsync();
}
my saveNewFacebookUser() looks like this...
private void saveNewFacebookUser() {
final ParseUser newFacebookUser = new ParseUser();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.profile_picture);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
ParseFile file = new ParseFile(AppConstants.PARSEUSER_IMAGE_FILE_NAME, image);
newFacebookUser.setUsername(facebookUser);
newFacebookUser.setEmail(facebookEmail);
newFacebookUser.put(AppConstants.PARSEUSER_FULLNAME, facebookUser);
newFacebookUser.put(AppConstants.PARSEUSER_FIRST_TIME_LOGGED_IN, "true");
newFacebookUser.put(AppConstants.PARSEUSER_PROFILE_IMAGE, file);
file.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
newFacebookUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// USER CREATED!
// TODO SEND AN EMAIL TO THE USER WITH USERNAME AND PASSWORD
Intent intent = new Intent(LoginRegister.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
} else {
MethodContants.showLog(TAG, "Facebook Error:" + e.getMessage(), true);
showToast("Facebook Error: " + e.getMessage());
}
}
});
} else {
MethodContants.showLog(TAG, "Facebook Error:" + e.getMessage(), true);
showToast("Facebook Error: " + e.getMessage());
}
}
});
}
The error is telling me that I have to use signUpInBackground and not saveInBackground. However, when I do that, I get another error that says I need to save a password for the user -> which defeats the whole purpose of the facebook login.
Any help would be much appreciated!
I found the issue.
in the saveNewFacebookUser() method, I was setting it as a brand new user.
ParseUser new = new ParseUser();
This should have been
ParseUser new = ParseUser.getCurrentUser();
I will leave this up in case anyone has issues.

error while consuming a RestFul WebService

I have created a web service -
#Path("/info")
public class RestFulService {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getPlain()
{
return " Web Service created";
}
}
When I am accessing through localhost browser is rendering - "Web Service created".
But when I am trying to consume this web service through a different app I am getting 404 error code - "Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 404
at RestConsumer.main(RestConsumer.java:28)
"
Code inside RestConsumer.java -
public static void main(String[] args) {
try {
String uri = "http://localhost:8080/RestFul/rest/info";
URL url = new URL(uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", MediaType.TEXT_PLAIN);
conn.connect();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Can anyone suggest the required change.
It is a basic setting problem in Eclipse EE Refer to this Youtube link at 6:54
It gives a step by step guide to rectify the same. Hope this helpstutorial