Thought the WriteResult.getLastError() should return null, if the delete
operation was successful.
It returns this
{ "n" : 1 , "connectionId" : 200 , "wtime" : 0 , "err" : null , "ok" : 1.0}
The BatchData Document was deleted successfully, but getLastError() is not null.
How should I write the code to know, if the delete was unsuccessful, in the following snippet:
try {
Query<BatchData> queryDeleteBatchData = mongo.createQuery(BatchData.class);
queryDeleteBatchData.field("uuid").equal(theBatch.uuid);
queryDeleteBatchData.field("senderUuid").equal(on.uuid);
WriteResult del = mongo.delete(queryDeleteBatchData);
if(del.getLastError() != null){
logger.error("ERROR");
}
} catch (Exception e) {
logger.error("ERROR" );
}
The getLastError() command is doing the correct thing. It's telling you that the action was successful (ok:1.0) and that no error occurred ("err":null).
For more details check out the recently updated docs.
getLastError() also has some functionality related to journaling and replication that you may want to investigate.
Edit:
In response to the first comment:
...
if(del.getLastError().ok != 1.0){
logger.error("ERROR");
}
} catch (Exception e) {
logger.error("ERROR" );
}
Related
I am trying to store multiple types of Records in Cosmo DB using batch operation. But I am getting 400 status in CosmoBatchResponse object and errorMessage is null. Internally , one item is giving 400 , all the other operations have a 424 status code (failed dependency). From this [document] https://learn.microsoft.com/en-us/rest/api/cosmos-db/http-status-codes-for-cosmosdb I can see there could be many reason of 400 , but if errorMessage is null then how to find what went wrong . Also , same msg is getting stored via create call ,facing issue while batch save only.
PartitionKey partitionKey = new PartitionKey("customerNo");
CosmosBatch batch = CosmosBatch.createCosmosBatch(partitionKey);
batch.createItemOperation(customer);
I have tried to store via create method only looping on CosmosItemOperation and it is getting stored.
CosmosBatchResponse response=paymentRepository.createBatch(cosmosBatch);
for(CosmosItemOperation itemOp:cosmosBatch.getOperations()) {
System.out.println(paymentRepository.create(itemOp.getItem(),""));// Here it is getting stored.
}
public CosmosBatchResponse createBatch(CosmosBatch cosmosBatch) {
CosmosBatchResponse response = null;
try {
response = container.executeCosmosBatch(cosmosBatch);
System.out.println(response.isSuccessStatusCode()); -- returns false
System.out.println(response.getErrorMessage()); -- returns null
return response;
} catch (final Exception e) {
int statusCode = CosmosUtils.getCosmosStatusCode(e);
if (CONFLICT_RESOURCE == statusCode) {
log.error(
"CosmosCreateDocumentException: Resource already exists for Document : {}",
response.getErrorMessage());
}
shouldRetryOnException(e);
log.error(
"CosmosCreateDocumentException for Document {} - {}, {}", cosmosBatch, e.getMessage(), e);
throw new GenericRepositoryException(e.getMessage(), e);
}
}
I'm implementing a custom camera using cameraX library. I'm working on focusing and I did below things
viewFinder.setOnTouchListener { v, event ->
return#setOnTouchListener when (event.action) {
MotionEvent.ACTION_DOWN -> {
true
}
MotionEvent.ACTION_UP -> {
// The below code is for focusing
val factory = SurfaceOrientedMeteringPointFactory(
viewFinder.width.toFloat(),
viewFinder.height.toFloat()
)
val point = factory.createPoint(event.x, event.y)
try {
val action = FocusMeteringAction.Builder(point, FocusMeteringAction.FLAG_AF)
.apply {
disableAutoCancel() //focus only when the user tap the preview
}.build()
val future = cameraControl?.startFocusAndMetering(action)
future?.addListener(Runnable {
--->line 66 val result = future?.get()
println("log result ---> $result")
}, cameraExecutor)
} catch (e: CameraInfoUnavailableException) {
println("log error ---> $e")
}
true
}
else -> false // Unhandled event.
}
}
Now, It is some what focusing the point I touched and it's not too accurate but it's ok. And while focusing after 5 to 6 times the app was crashing and closing.
FATAL EXCEPTION: pool-2-thread-1
...
...
java.lang.Error: java.util.concurrent.ExecutionException: androidx.camera.core.CameraControl$OperationCanceledException: Cancelled by another startFocusAndMetering()
...
...
...MainActivity$onCreate$2$1.run(MainActivity.kt:66)
I'm not getting why it's crashing and it is not frequently crashing. Sometimes it will crash and some times not.
Edit 1 :-
I got to know that when I tap focus multiple times this is happening. So, before start of focusing I need to clear the previous focus if in progress. But, how to clear previous focus I'm not getting.
Edit 2 :-
I tried this cameraControl?.cancelFocusAndMetering(), I just put it at first line of try block. but still problem exists.
Apologies for the java code here. But from my experience the future?.get() needs to be wrapped in a try, catch
future.addListener(() -> {
try
{
FocusMeteringResult result = (FocusMeteringResult) future.get();
if(result.isFocusSuccessful())
{
// Focus has succeeded
}
else
{
// Focus has failed
}
}
catch (ExecutionException e) // Thrown exceptions
{
e.printStackTrace();
}
catch (InterruptedException e) // Thrown exceptions
{
e.printStackTrace();
}
}
I just removed This block
future?.addListener(Runnable {
val result = future?.get()
println("log result ---> $result")
}, cameraExecutor)
and it's working fine. But I don't know is it right or wrong.
If anyone knows? please answer. currently I'm marking this as answer as it worked.
I am taking the foursquare sample java code and the same sample values from git and running in my local machine, but getting the following exception.
Here is my code:
String ll = args.length > 0 ? args[0] : "44.3,37.2";
try {
FourSquareSampleMain fourSquareSample = new FourSquareSampleMain();
fourSquareSample.searchVenues(ll);
} catch (FoursquareApiException e) {
// TODO: Error handling
e.printStackTrace();
}
}
public void searchVenues(String ll) throws FoursquareApiException {
// First we need a initialize FoursquareApi.
FoursquareApi foursquareApi = new FoursquareApi("CLIENT_ID",
"CLIENT_SECRET", null);
// After client has been initialized we can make queries.
Result<VenuesSearchResult> result = foursquareApi.venuesSearch(ll, null, null, null, null, null, null, null,
null, null, null, null, null);
if (result.getMeta().getCode() == 200) {
CompactVenue[] venueList = result.getResult().getVenues();
System.out.println("Compact Venue List size : " + venueList.length);
// if query was ok we can finally we do something with the data
for (CompactVenue venue : venueList) {
// TODO: Do something we the data
System.out.println("Venue Name : " + venue.getName());
}
System.out.println("End of IF Loop: ");
} else {
// TODO: Proper error handling
System.out.println("Error occured: ");
System.out.println(" code: " + result.getMeta().getCode());
System.out.println(" type: " + result.getMeta().getErrorType());
System.out.println(" detail: " + result.getMeta().getErrorDetail());
}
}
The size of the venueList is always "0", but when I debugged it , it throws the below exception:
"org.eclipse.debug.core.DebugException: com.sun.jdi.ClassNotLoadedException: Type has not been loaded occurred while retrieving component type of array."
But strange when I changed the latitude and longitude value,
String ll = "-33.883056 , 151.216667";// latlong surry hills sydney
I get the below exception:
fi.foyt.foursquare.api.FoursquareApiException: org.json.JSONException: JSONObject["icon"] not a string.
at fi.foyt.foursquare.api.JSONFieldParser.parseEntity(JSONFieldParser.java:143)
at fi.foyt.foursquare.api.JSONFieldParser.parseValue(JSONFieldParser.java:194)
at fi.foyt.foursquare.api.JSONFieldParser.parseEntity(JSONFieldParser.java:141)
at fi.foyt.foursquare.api.JSONFieldParser.parseEntities(JSONFieldParser.java:57)
at fi.foyt.foursquare.api.FoursquareApi.venuesSearch(FoursquareApi.java:1017)
at FourSquareSampleMain.searchVenues(FourSquareSampleMain.java:57)
at FourSquareSampleMain.main(FourSquareSampleMain.java:43)
Caused by: org.json.JSONException: JSONObject["icon"] not a string.
at org.json.JSONObject.getString(JSONObject.java:658)
at fi.foyt.foursquare.api.JSONFieldParser.parseValue(JSONFieldParser.java:202)
at fi.foyt.foursquare.api.JSONFieldParser.parseEntity(JSONFieldParser.java:141)
What am I missing here? please suggest.
I found a workaround for that. It's a patch, but it works. Details:
Info was taken from this post where same issue was identified and fixed
Take a look that diff that resolve the issue: https://github.com/wallabyfinancial/foursquare-api-java/compare/master...ganchix:master
Copy those 3 raw classes (Category, GeoCodeFeature and Icon) as they are and add them into your porject under the package fi.foyt.foursquare.api.entities and that's it
Note 1: when you replace classes (same package and class name) in yur project, the clasloader will use yours instead of the classes provided by the jar dependency, so, there is a quick fix.
I did that and it worked like a charm
Note 2: As soon as the sdk is updated, you should remove this patch and upgrade the sdk dependency
Hope it helps
Please what exactly am i doing wrong.
I have checked and checked but all to no avail.
I have also checked previous code but I am not getting an error so my code works fine but just slight error somewhere.
The code is running fine and assertTrue is behaving as expected but when I put it in the try/catch, I only get the log in the catch block, even when text was found.
I believe that if the assertTrue found the text, it should go to the next line of code in the try block and pass the test rather than the catch block. Don't get me wrong, I am not getting any error just that it's printing out the wrong message.
Code below including print out message in console.
public boolean verifyTextPresent(String value) throws Exception {
Thread.sleep(5000);
try{
boolean txtFound = driver.getPageSource().contains(value);
log.log(value + " : text Found, .......continue");
return txtFound;
}catch(Exception e)
{
log.log(value + " :NOT Found, check element again ot Contact developer.");
return false;
}
}
public static void verifySignOutBtn() throws Exception
{
log.header("VERIFY IF SIGN_OUT EXIST AND CLICKABLE.........");
callMethod.myAccountPageNative(CONSTANTElements.SIGN_IN_LINK);
Thread.sleep(2000);
log.header("LOCATE SIGN_OUT BTN, AND CLICK ......");
callMethod.elementPresent_Click(By.cssSelector(CONSTANTElements.SIGN_OUT_BTN));
Thread.sleep(4000);
log.header("VERIFY SIGN_OUT NAVIGATES TO HOME PAGE WHEN CLICKED......");
try{
Assert.assertTrue(callMethod.verifyTextPresent("SIGN IN"), "SIGN IN");
log.log("User Successfully Signed Out.......");
log.log("Test Passed!...");
//callMethod.close();
}
catch(Throwable e)
{
log.log("User NOT Successfully Signed Out.... Contact developer.");
log.log("Test Failed!...");
//callMethod.close();
}
callMethod.close();
}
}
Msg in console:
SIGN IN : text Found, .......continue
User NOT Successfully Signed Out.... Contact developer.
Test Failed!...
The confusing part is that why is it printing out the catch block instead of the next line in the try block?
Shouldn't it be the other way around?
Assert.assertTrue("Message if it is false", callMethod.verifyTextPresent("SIGN IN"));
The only possible explanation is that verifyTextPresent(String value) returns false (you never actually check the value of boolean txtFound) and assertTrue fails (throwing an AssertionError which is not handled well in your catch block). To find out, replace this
log.log(value + " : text Found, .......continue");
for example with this line
log.log(value + " : text Found, ......." + txtFound);
or just print the stacktrace in catch block.
i want to put if else or switch statement which is more suitable for checking employee count before commit.where i put my if else or switch code . i want restriction on employee if count is 5 then its show message "reached maximum employee limites" otherwise allow commit.
i am new in java plz someone help me to solve this
public String cmdSave_action()
{
// my code before
{
DeptSet result;
try {
dbo.connect();
result =
dbo.execSQL("select count(*) from empmasterinfo where mainid='ORGElement' and designationid='?') "
(inputText_ORGElement.getValue() != null ?
""));
result = dbo.execSQL(sSQL);
catch (Exception e) {
System.out.println(e.getMessage());
finally
{
dbo.close();
}
return null;
}}}
// my code above
{
Global.PerformIteratorAction(this.bindings, "Commit");
AdfFacesContext afContext = AdfFacesContext.getCurrentInstance();
afContext.getProcessScope().put("EmployeeID",
Global.getCurrRowFieldValue("EmpmasterinfoViewIterator",
"Employeeid"));
if (afContext.getProcessScope().get("AddEdit").toString().equals("0"))
{
Global.PerformIteratorAction(this.bindings,
"EPR_TRANSFER_APPLICANT_INFO");
Global.PerformIteratorAction(this.bindings, "eprGenerateApPlan");
}
return null;
}}
My Error Log
Error(149,12): 'try' without 'catch' or 'finally'
Error(154,36): , expected
Error(157,34): field SQL not found in class hcm.view.backing.empprofile.EmployeeMasterInfo_Add
Error(159,11): illegal start of expression
Error(159,11): ; expected
E:\HCM\ViewController\src\hcm\view\backing\empprofile\dbo.java
Error(13,16): method does not return a value
Please close Your try catch block properly
try{
}catch(Exception e){
}finally{
}
And Read this
catch and finally are within try block
try {
//code
}
catch(Exception e) {
System.out.println(e.getMessage());
}
finally {
dbo.close();
}
Using an IDE will help you with indentation and proper formatting while writing code. e.g Eclipse.
For the first error close the try-catch blocks properly
And for the second error: Since your method is declared as public String cmdSave_action(), you should return a String value at the end of the method. The return statement is missing in your code.