how to wait for ParseCloud.callFunctionInBackgroud - parse-platform

I have a Utility function which I use to check if user has done few operations or not. If not, Then I need to send the results back to MainActivity.
public static boolean checkUserIsDone(String receiverPhoneNumber, String senderNumber ) {
hasApp = false;
HashMap<String, Object> parseParams = new HashMap<>();
parseParams.put("phoneNumber", receiverPhoneNumber);
parseParams.put("senderNumber", senderNumber);
ParseCloud.callFunctionInBackground("GetUserByPhoneNumber", parseParams, new FunctionCallback<String>() {
public void done(String result, ParseException e) {
if (e == null && result.equals("success")) {
hasApp = true;
} else {
hasApp = false;
Log.e("Error: ", e.getMessage());
}
}
});
return hasApp;
}

Related

Migrating Apache Struts Action to Spring Rest Controller

I have a webpage whose backend is in Java and the framework is very old (Apache Struts Framework)
The webpage contains buttons textboxes and tables which we can fill and press Add , delete and edit button
All this code is currently written in Action file in java
We need to convert this code and put it in a new Controller file (Rest Controller)
Action files will still be present we just need them till loading JSP onto the page
Once JSP is loaded every button click,event handler (i.e. Add, delete, edit) should be handled by controller
Earlier button clicks were going to Action like formSubmit
We will still need to keep the Action file because we are using Struts framework so we will require action file
Giving an example of two files of how they look after migration -
Apache Struts Action Code-
public final ActionForward updateUserDetails(final ActionMapping mapping,
final ActionForm form, final HttpServletRequest request,
final HttpServletResponse response) throws IOException {
UserAdminForm uForm = (UserAdminForm) form;
UserAdminVO vo = userManager.getUserByUserPk(Integer.parseInt(uForm.getUserPK()));
String olddiscoverId = vo.getDiscoverId();
String oldDiscoverAccess = vo.getDiscoverAccess();
try {
if(!ISC.SUPER_USER_ROLE.equals(workContext.getRole()) && !workContext.getUser().equalsIgnoreCase(uForm.getUserID())) {
manager.logError("** Possible breach: Logged in user[" + workContext.getUser() + "] is attempting to update details for " + uForm.getUserID() + ". **");
processErrorMessages(CConstant.USER_MISSMATCH_FOR_UPDATE_OPERATION,
request);
return mapping.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
setLandingPageAndOtherDetailsForUserUpdate(uForm, vo);
if (manager.isDebugEnabled()) {
manager.logDebug("User admin VO from user form =" + vo);
manager.logDebug("Old user id : " + uForm.getOldUserID()
+ " New User id : " + uForm.getUserID());
}
DiscoverResponse discoverResponse = null;
if("true".equalsIgnoreCase(globalSysParamManager.getParamValue(ENABLE_DISCOVER_SYSTEM_FEATURE))){
discoverResponse = updateDiscoverAccess(oldDiscoverAccess, olddiscoverId, vo);
if(discoverResponse!=null && CConstant.ERROR_STR.equalsIgnoreCase(discoverResponse.getResult())){
vo.setDiscoverAccess(oldDiscoverAccess);
}
}
userManager.updateUser(vo);
syncOtherUsersWithDiscover(vo);
refreshWorkContext(vo);
processSuccessMessage(CConstant.USER_UPDATE_SUCCESS, discoverResponse, request);
} catch (BusinessServiceException e) {
manager.logError("Error in User Update Action", e);
ActionMessages messages = new ActionMessages();
messages.add(
ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(e.getErrorCode(), new Object[] { e
.getMessage() }));
saveErrors(request, messages);
} catch (BusinessServiceCommonsException e) {
manager.logError("Error in User Update Action", e);
ActionMessages messages = new ActionMessages();
messages.add(
ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(e.getErrorCode(), new Object[] { e
.getMessage() }));
saveErrors(request, messages);
}
try {
loadCarparks(uForm, vo);
request.getSession(false).setAttribute(PARK_FOR_LOCATION,
uForm.getCarparkList());
} catch (BusinessServiceException e) {
manager.logError("Error in User Display Action ", e);
processBusinessServiceException(e, request);
}
if ("true".equals(uForm.getPasswordExpired())) {
response.sendRedirect(request.getContextPath()
+ "/logout.cprms?doLogout=true");
return null;
}
return mapping.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
Rest Controller Code -
#PutMapping
public ResponseEntity<Object> updateUser(#RequestBody UserAdminForm userAdminForm, HttpServletRequest request){
List<String> errorMessages = validateUserDetails(userAdminForm);
if(!errorMessages.isEmpty()){
return new ResponseEntity<>(errorMessages, HttpStatus.BAD_REQUEST);
}
ICWorkContext workContext = ControllerUtility.initializeWorkContext(userAdminForm.getLocationId(),request);
var userAdminVO = userManager.getUser(userAdminForm.getUserID());
String oldDiscoverId = userAdminVO.getDiscoverId();
String oldDiscoverAccess = userAdminVO.getDiscoverAccess();
DiscoverResponse discoverResponse = null;
try {
if(!ISC.SUPER_USER_ROLE.equals(workContext.getRole()) && !workContext.getUser().equalsIgnoreCase(userAdminForm.getUserID())) {
LOGGER.logError("** Possible breach: Logged in user[" + workContext.getUser() + "] is attempting to update details for " + userAdminForm.getUserID() + ". **");
String errorMessage = messages.getMessage(CConstant.USER_MISSMATCH_FOR_UPDATE_OPERATION);
return new ResponseEntity<>(errorMessage,HttpStatus.NOT_ACCEPTABLE);
}
setLandingPageAndOtherDetailsForUserUpdate(userAdminForm, userAdminVO,workContext);
if("true".equalsIgnoreCase(globalSysParamManager.getParamValue(ENABLE_DISCOVER_SYSTEM_FEATURE))){
discoverResponse = updateDiscoverAccess(oldDiscoverAccess, oldDiscoverId, userAdminVO);
if(discoverResponse!=null && CConstant.ERROR_STR.equalsIgnoreCase(discoverResponse.getResult())){
userAdminVO.setDiscoverAccess(oldDiscoverAccess);
}
}
userManager.updateUser(userAdminVO);
syncOtherUsersWithDiscover(userAdminVO);
refreshWorkContext(userAdminVO,workContext);
} catch (Exception exception) {
LOGGER.logError("Error in Update User API", exception);
return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
}
Map<String, Object> response = new HashMap<>(2);
List<String> successMessages = new ArrayList<>(2);
successMessages.add(messages.getMessage(CConstant.USER_UPDATE_SUCCESS));
getDiscoverResponseMessage(discoverResponse, response, successMessages);
response.put(SUCCESS_MESSAGE,successMessages);
return new ResponseEntity<>(response,HttpStatus.OK);
}
I want to migrate this Action Code to Rest Controller -
public final ActionForward displayAllLeaves(final ActionMapping mapping,
final ActionForm form, final HttpServletRequest request,
final HttpServletResponse response) throws IOException,
ServletException {
boolean checkFlag = true;
LumpConfigFB lumpConfigFB = (LumpConfigFB) form;
storeProductWithoutDNAToRequest(request);
try {
LumpConfigVO lumpConfigVO = new LumpConfigVO();
if ((null == workContext.getCarparkPK())
|| "".equals(workContext.getCarparkPK())) {
BusinessServiceException businessServiceException = new BusinessServiceException(
CPRMSConstant.NO_C_ERROR);
businessServiceException
.setErrorCode(CConstant.NO_C_ERROR);
processBusinessServiceException(businessServiceException,
request);
return mapping
.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
// populateVO
populateLumpConfigVO(lumpConfigFB, lumpConfigVO);
lumpConfigManager.displayAllLeaves(lumpConfigVO);
if (((null != lumpConfigVO.getMappedLumpDefList()) && (lumpConfigVO
.getMappedLumpDefList().size() > 0))
|| ((null != lumpConfigVO.getUnmappedLumpDefList()) && (lumpConfigVO
.getUnmappedLumpDefList().size() > 0))) {
List<LumpConfigVO> mappedLumpDefList = lumpConfigVO
.getMappedLumpDefList();
HashMap<String, LumpConfigVO> lumpNameMap = new HashMap<String, LumpConfigVO>();
List<String> lumpNameList = new ArrayList<String>();
if (null != mappedLumpDefList && mappedLumpDefList.size() > 0) {
for (LumpConfigVO configVO : mappedLumpDefList) {
lumpNameList.add(configVO.getLumpName());
lumpNameMap.put(configVO.getLumpName(), configVO);
}
mappedLumpDefList.clear();
Collections.sort(lumpNameList,
String.CASE_INSENSITIVE_ORDER);
for (String lumpName : lumpNameList) {
mappedLumpDefList.add(lumpNameMap.get(lumpName));
}
lumpConfigFB.setMappedLumpDefList(mappedLumpDefList);
}
List<LumpConfigVO> unMappedLumpDefList = lumpConfigVO
.getUnmappedLumpDefList();
if (null != unMappedLumpDefList
&& unMappedLumpDefList.size() > 0) {
Collections.sort(unMappedLumpDefList, new LumpComparator());
lumpConfigFB.setUnmappedLumpDefList(unMappedLumpDefList);
}
} else {
lumpConfigFB.setMappedLumpDefList(null);
lumpConfigFB.setUnmappedLumpDefList(null);
BusinessServiceException businessServiceException = new BusinessServiceException(
CConstant.LEAF_NOT_FOUND_ERROR);
businessServiceException
.setErrorCode(CConstant.LEAF_NOT_FOUND_ERROR);
processBusinessServiceException(businessServiceException,
request);
checkFlag = false;
}
if (null != request.getAttribute("jobid")
&& !"".equals(request.getAttribute("jobid"))) {
String jobId = (String) request.getAttribute("jobid");
ActionErrors actionErrors = new ActionErrors();
ActionMessages messages = new ActionMessages();
if ("failure".equals(request.getAttribute("jobid").toString())) {
String errorCode = (String) request
.getAttribute("errorcode");
actionErrors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(errorCode));
saveErrors(request, (ActionMessages) actionErrors);
} else {
actionErrors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(CConstant.AGGR_QUEUE_SUCCESS,
jobId));
messages.add(actionErrors);
saveMessages(request, messages);
}
}
} catch (BusinessServiceException businessServiceException) {
processBusinessServiceException(businessServiceException, request);
checkFlag = false;
}
return mapping.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
I have also written a Rest Controller Code for this Action file but I am not sure If I am going right -
public class LeavesController {
#Autowired
private LumpConfigManager lumpConfigManager;
#GetMapping
public ResponseEntity<List<LumpConfigVO>> getAllLeaves(HttpServletRequest request) {
try {
LumpConfigVO lumpConfigVO = new LumpConfigVO();
if ((null == workContext.getCarparkPK())
|| "".equals(workContext.getCarparkPK())) {
throw new BusinessServiceException(CPRMSConstant.NO_CARPARK_ERROR);
}
populateLumpConfigVO(lumpConfigFB, lumpConfigVO);
lumpConfigManager.displayAllLeaves(lumpConfigVO);
if (((null != lumpConfigVO.getMappedLumpDefList()) && (lumpConfigVO
.getMappedLumpDefList().size() > 0))
|| ((null != lumpConfigVO.getUnmappedLumpDefList()) && (lumpConfigVO
.getUnmappedLumpDefList().size() > 0))) {
List<LumpConfigVO> mappedLumpDefList = lumpConfigVO
.getMappedLumpDefList();
HashMap<String, LumpConfigVO> lumpNameMap = new HashMap<String, LumpConfigVO>();
List<String> lumpNameList = new ArrayList<String>();
if (null != mappedLumpDefList && mappedLumpDefList.size() > 0) {
for (LumpConfigVO configVO : mappedLumpDefList) {
lumpNameList.add(configVO.getLumpName());
lumpNameMap.put(configVO.getLumpName(), configVO);
}
mappedLumpDefList.clear();
Collections.sort(lumpNameList,
String.CASE_INSENSITIVE_ORDER);
for (String lumpName : lumpNameList) {
mappedLumpDefList.add(lumpNameMap.get(lumpName));
}
}
List<LumpConfigVO> unMappedLumpDefList = lumpConfigVO
.getUnmappedLumpDefList();
if (null != unMappedLumpDefList
&& unMappedLumpDefList.size() > 0) {
Collections.sort(unMappedLumpDefList, new LumpComparator());
}
return ResponseEntity.ok(lumpConfigVO);
} else {
throw new BusinessServiceException(CPRMSConstant.LEAF_NOT_FOUND_ERROR);
}
} catch (BusinessServiceException businessServiceException) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, businessServiceException.getMessage(), businessServiceException);
}
}
// helper method for populating LumpConfigVO from LumpConfigFB
private void populateLumpConfigVO(LumpConfigFB lumpConfigFB, LumpConfigVO lumpConfigVO) {
// implementation here
}
// helper method for storing product without DNA to request
private void storeProductWithoutDNAToRequest(HttpServletRequest request) {
// implementation here
}
// other helper methods and properties omitted
}

Cannot invoke "org.apache.commons.logging.Log.isDebugEnabled()" because "this.logger" is null

Here the code that I used to save data and I use #Transactional. I want to write a test for this method, but it fails.
#Transactional(rollbackFor = BadRequestException.class, propagation = Propagation.REQUIRES_NEW)
public void saveContent(ContentAbstractEntity content) {
mongoTemplate.setSessionSynchronization(SessionSynchronization.ALWAYS);
TransactionBody txnBody =
(() -> {
ContentAbstractEntity contentAbstractEntity = contentRepository.save(content);
if (content instanceof LearningContent) {
LearningContent learningContent = (LearningContent) content;
Long tutorCountInDB = tutorRepository.countBy_idIn(learningContent.getTutorIds());
if (!countryRepository.existsBySyllabuses_grades_subjects__id(
learningContent.getSubjectId()))
throw new BadRequestException("Subject is not found");
Topic topic = topicRepository.findBy_id(learningContent.getTopicId());
if (topic == null) throw new BadRequestException("Topic is not found");
List<ObjectId> lessonIds =
topic.getLessons().stream().map(m -> m.get_id()).collect(Collectors.toList());
boolean allLessonsExists =
learningContent.getLessonIds().stream().allMatch(a -> lessonIds.contains(a));
if (!allLessonsExists) throw new BadRequestException("Lessons are not mismatched");
if (tutorCountInDB != learningContent.getTutorIds().size()) {
throw new BadRequestException("Tutors are not matched");
}
}
return "Successfully inserted";
});
MongoClient client = MongoClients.create(uri);
ClientSession clientSession = client.startSession();
try {
clientSession.withTransaction(txnBody);
} catch (BadRequestException e) {
throw new BadRequestException(e.getMessage());
} finally {
clientSession.close();
}
}
I tried to write a test for the above code, but it returns an error
#Test
void whenSaveContent() throws Exception {
ContentAbstractDto contentAbstractDto = new ContentAbstractDto();
ContentAbstractEntity content = learningVideo();
if (contentAbstractDto instanceof LearningDocsDto) {
LearningDocsDto learninfDocsDto = (LearningDocsDto) contentAbstractDto;
// ToDo when a Doc Saves and Assessment saves
}
when(contentRepository.save(content)).thenReturn(content);
if (content instanceof LearningContent) {
LearningContent learningContent = (LearningContent) content;
Long tutorCountInDB = (long) learningContent.getTutorIds().size();
when(tutorRepository.countBy_idIn(learningContent.getTutorIds())).thenReturn(tutorCountInDB);
when(subjectRepository.existsBy_id(learningContent.getSubjectId())).thenReturn(true);
Topic topic = getTopic();
when(topicRepository.findBy_id(learningContent.getTopicId())).thenReturn(topic);
if (topic == null) throw new BadRequestException("Topic is not found");
List<ObjectId> lessonIds =
topic.getLessons().stream().map(m -> m.get_id()).collect(Collectors.toList());
boolean allLessonsExists =
learningContent.getLessonIds().stream().allMatch(a -> lessonIds.contains(a));
if (!allLessonsExists) throw new BadRequestException("Lessons are not mismatched");
if (tutorCountInDB != learningContent.getTutorIds().size()) {
throw new BadRequestException("Tutors are not matched");
}
}

how to implement Android In App BillingClient in Xamarin.Android Asynchronously

I am trying to implement below java code in c# referring to Android documentation
List<String> skuList = new ArrayList<> ();
skuList.add("premium_upgrade");
skuList.add("gas");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(SkuType.INAPP);
billingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(BillingResult billingResult,
List<SkuDetails> skuDetailsList) {
// Process the result.
}
});
I have here 2 questions. I thought that i would run this code on a separate thread than UI thread like below to keep my ui responsive while network connection is done. is that the correct approach? QuerySkuDetailsAsync is called async but doesnt implement as async. how should this be working and how to handle in c# because it will fire and forget but Listener to handle the response.
public async Task<List<InAppBillingProduct>> GetProductsAsync(List<string> ProductIds)
{
var getSkuDetailsTask = Task.Factory.StartNew(() =>
{
var prms = SkuDetailsParams.NewBuilder();
var type = BillingClient.SkuType.Inapp;
prms.SetSkusList(ProductIds).SetType(type);
BillingClient.QuerySkuDetailsAsync(prms.Build(), new SkuDetailsResponseListener());
return InAppBillingProducts;
});
return await getSkuDetailsTask;
}
2nd question regarding how to handle with the listener as below. How do I return value from the listener. I need return list of InAppBillingProduct object.
public class SkuDetailsResponseListener : Java.Lang.Object, ISkuDetailsResponseListener
{
public void OnSkuDetailsResponse(BillingResult billingResult, IList<SkuDetails> skus)
{
if (billingResult.ResponseCode == BillingResponseCode.Ok)
{
// get list of Products here and return
}
}
}
FYI. This is how I did it. This is not a complete code but this will give you and idea.
Listener - PCL
============
private async Task EventClicked()
{
var skuList = new List<string>();
skuList.Add("[nameofsubscriptionfoundinyourgoogleplay]");
if (await _billingClientLifecycle.Initialize(skuList, DisconnectedConnection))
{
var firstProduct = _billingClientLifecycle?.ProductsInStore?.FirstOrDefault();
if (firstProduct != null)
{
//purchase here
}
}
}
private void DisconnectedConnection()
{
//Todo.alfon. handle disconnection here...
}
Interface - PCL
===========
public interface IInAppBillingMigratedNew
{
List<InAppBillingPurchase> PurchasedProducts { get; set; }
List<InAppBillingProduct> ProductsInStore { get; set; }
Task<bool> Initialize(List<String> skuList, Action onDisconnected = null);
}
Dependency - Platform Droid
===============
[assembly: XF.Dependency(typeof(InAppBillingMigratedNew))]
public class InAppBillingMigratedNew : Java.Lang.Object, IBillingClientStateListener
, ISkuDetailsResponseListener, IInAppBillingMigratedNew
{
private Activity Context => CrossCurrentActivity.Current.Activity
?? throw new NullReferenceException("Current Context/Activity is null");
private BillingClient _billingClient;
private List<string> _skuList = new List<string>();
private TaskCompletionSource<bool> _tcsInitialized;
private Action _disconnectedAction;
private Dictionary<string, SkuDetails> _skusWithSkuDetails = new Dictionary<string, SkuDetails>();
public List<InAppBillingPurchase> PurchasedProducts { get; set; }
public List<InAppBillingProduct> ProductsInStore { get; set; }
public IntPtr Handle => throw new NotImplementedException();
public Task<bool> Initialize(List<string> skuList, Action disconnectedAction = null)
{
_disconnectedAction = disconnectedAction;
_tcsInitialized = new TaskCompletionSource<bool>();
var taskInit = _tcsInitialized.Task;
_skuList = skuList;
_billingClient = BillingClient.NewBuilder(Context)
.SetListener(this)
.EnablePendingPurchases()
.Build();
if (!_billingClient.IsReady)
{
_billingClient.StartConnection(this);
}
return taskInit;
}
#region IBillingClientStateListener
public void OnBillingServiceDisconnected()
{
Console.WriteLine($"Connection disconnected.");
_tcsInitialized?.TrySetResult(false);
_disconnectedAction?.Invoke();
}
public void OnBillingSetupFinished(BillingResult billingResult)
{
var responseCode = billingResult.ResponseCode;
var debugMessage = billingResult.DebugMessage;
if (responseCode == BillingResponseCode.Ok)
{
QuerySkuDetails();
QueryPurchases();
_tcsInitialized?.TrySetResult(true);
}
else
{
Console.WriteLine($"Failed connection {debugMessage}");
_tcsInitialized?.TrySetResult(false);
}
}
#endregion
#region ISkuDetailsResponseListener
public void OnSkuDetailsResponse(BillingResult billingResult, IList<SkuDetails> skuDetailsList)
{
if (billingResult == null)
{
Console.WriteLine("onSkuDetailsResponse: null BillingResult");
return;
}
var responseCode = billingResult.ResponseCode;
var debugMessage = billingResult.DebugMessage;
switch (responseCode)
{
case BillingResponseCode.Ok:
if (skuDetailsList == null)
{
_skusWithSkuDetails.Clear();
}
else
{
if (skuDetailsList.Count > 0)
{
ProductsInStore = new List<InAppBillingProduct>();
}
foreach (var skuDetails in skuDetailsList)
{
_skusWithSkuDetails.Add(skuDetails.Sku, skuDetails);
//ToDo.alfon. make use mapper here
ProductsInStore.Add(new InAppBillingProduct
{
Name = skuDetails.Title,
Description = skuDetails.Description,
ProductId = skuDetails.Sku,
CurrencyCode = skuDetails.PriceCurrencyCode,
LocalizedIntroductoryPrice = skuDetails.IntroductoryPrice,
LocalizedPrice = skuDetails.Price,
MicrosIntroductoryPrice = skuDetails.IntroductoryPriceAmountMicros,
MicrosPrice = skuDetails.PriceAmountMicros
});
}
}
break;
case BillingResponseCode.ServiceDisconnected:
case BillingResponseCode.ServiceUnavailable:
case BillingResponseCode.BillingUnavailable:
case BillingResponseCode.ItemUnavailable:
case BillingResponseCode.DeveloperError:
case BillingResponseCode.Error:
Console.WriteLine("onSkuDetailsResponse: " + responseCode + " " + debugMessage);
break;
case BillingResponseCode.UserCancelled:
Console.WriteLine("onSkuDetailsResponse: " + responseCode + " " + debugMessage);
break;
// These response codes are not expected.
case BillingResponseCode.FeatureNotSupported:
case BillingResponseCode.ItemAlreadyOwned:
case BillingResponseCode.ItemNotOwned:
default:
Console.WriteLine("onSkuDetailsResponse: " + responseCode + " " + debugMessage);
break;
}
}
#endregion
#region Helper Methods Private
private void ProcessPurchases(List<Purchase> purchasesList)
{
if (purchasesList == null)
{
Console.WriteLine("No purchases done.");
return;
}
if (IsUnchangedPurchaseList(purchasesList))
{
Console.WriteLine("Purchases has not changed.");
return;
}
_purchases.AddRange(purchasesList);
PurchasedProducts = _purchases.Select(sku => new InAppBillingPurchase
{
PurchaseToken = sku.PurchaseToken
})?.ToList();
if (purchasesList != null)
{
LogAcknowledgementStatus(purchasesList);
}
}
private bool IsUnchangedPurchaseList(List<Purchase> purchasesList)
{
// TODO: Optimize to avoid updates with identical data.
return false;
}
private void LogAcknowledgementStatus(List<Purchase> purchasesList)
{
int ack_yes = 0;
int ack_no = 0;
foreach (var purchase in purchasesList)
{
if (purchase.IsAcknowledged)
{
ack_yes++;
}
else
{
ack_no++;
}
}
//Log.d(TAG, "logAcknowledgementStatus: acknowledged=" + ack_yes +
// " unacknowledged=" + ack_no);
}
private void QuerySkuDetails()
{
var parameters = SkuDetailsParams
.NewBuilder()
.SetType(BillingClient.SkuType.Subs)
.SetSkusList(_skuList)
.Build();
_billingClient.QuerySkuDetailsAsync(parameters, this);
}
private void QueryPurchases()
{
if (!_billingClient.IsReady)
{
Console.WriteLine("queryPurchases: BillingClient is not ready");
}
var result = _billingClient.QueryPurchases(BillingClient.SkuType.Subs);
ProcessPurchases(result?.PurchasesList?.ToList());
}
#endregion
}

redisTemplate ValueOperations increment get null

First of all, I have to say that key exists in redis,
This key is a self-increasing sequence,
But sometimes getting this key is null.
I used spring-boot: 2.0.4.0.release
My expectation is to get a self-increment of 1 at a time to generate the order number
Could you advice a solution for my scenario? Thanks!
#Override
#Transactional(rollbackFor = Exception.class)
public boolean paymentBatchMeter(UserDescriptor user, String areaCode, String newPrice) {
List<Meter> meters = meterService.findAllByFilterAndAreaCode(null, areaCode, user);
if (meters != null && meters.size() > 0) {
List<TaskValue> taskValueList = new ArrayList<>();
meters.forEach(meter -> {
if (meter.getState() == 1) {
Task task = new Task();
task.setCode(meter.getCode());
TaskValue taskValue = new TaskValue();
taskValue.setId(task.getId());
taskValue.setMeterType(meter.getMeterDicCode());
taskValue.setCode(meter.getCode());
Long orderIndex = redisTemplate.opsForValue().increment("athena:order:index", 1);
if (orderIndex == null) {
throw new IllegalStateException("error!");
}
taskValueList.add(taskValue);
Order order = new Order();
order.setCustomerId(meter.getCustomerId());
order.setCode(orderIndex.toString());
order.setCreateTime(new Date());
order.setMeterId(meter.getId());
order.setState(0);
order.setRechargeMoney(new BigDecimal(newPrice));
List<DicProjectItem> dicProjectItems = dicProjectItemMapper.getDicProjectItemAll("D10015", 1);
String dicProjectItemId = dicProjectItems.stream().filter(p -> "002".equals(p.getCode())).collect(Collectors.toList()).get(0).getId();
order.setRechargeWayDicId(dicProjectItemId);
order.setRechargeState(1);
order.setTaskId(task.getId());
order.setOperatorId(user.getId());
}
});
redisTemplate.setEnableTransactionSupport(true);
taskValueList.forEach(taskValue -> {
if ("004".equals(taskValue.getMeterType())) {
redisTemplate.convertAndSend(TOPIC, taskValue.getCode());
redisTemplate.opsForList().rightPush("athena:concentrator:meter:task:" + taskValue.getCode(), JSON.toJSONString(taskValue));
} else {
redisTemplate.opsForList().rightPush("athena:meter:task:" + taskValue.getCode(), JSON.toJSONString(taskValue));
}
});
redisTemplate.setEnableTransactionSupport(false);
return true;
}
return false;
}

Camera Problems

I have run into a few problems when trying to get the camera to work accordingly... The camera Demo Works on the 8520 device (Has a memory Card) but does not work on the 9780 device (Has No Memory Card) the error given
ERROR Class java.lang.ArrayOutOfBoundsException :index 0>=0
My code Sample:
public class MyScreen extends MainScreen{
Player _p;
VideoControl _videoControl;
FileConnection fileconn;
String PATH;
String GetfileName;
LabelField GetPhotofileName = new LabelField("",LabelField.FOCUSABLE){
protected boolean navigationClick(int status, int time){
Dialog.alert("Clicked");
return true;
}
};
public static boolean SdcardAvailabulity() {
String root = null;
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements()) {
root = (String) e.nextElement();
if( root.equalsIgnoreCase("sdcard/") ) {
}else if( root.equalsIgnoreCase("store/") ) {
}
}
class MySDListener implements FileSystemListener {
public void rootChanged(int state, String rootName) {
if( state == ROOT_ADDED ) {
if( rootName.equalsIgnoreCase("sdcard/") ) {
}
} else if( state == ROOT_REMOVED ) {
}
}
}
return true;
}
protected boolean invokeAction(int action){
boolean handled = super.invokeAction(action);
if(SdcardAvailabulity()){
PATH = System.getProperty("fileconn.dir.memorycard.photos")+"Image_"+System.currentTimeMillis()+".jpg";//here "str" having the current Date and Time;
} else {
// PATH = System.getProperty("file:///store/home/user/pictures/")+"Image_"+System.currentTimeMillis()+".jpg";
PATH = System.getProperty("fileconn.dir.photos")+"Image_"+System.currentTimeMillis()+".jpg";
}
if(!handled){
if(action == ACTION_INVOKE){
try{
byte[] rawImage = _videoControl.getSnapshot(null);
System.out.println("----------1");
fileconn=(FileConnection)Connector.open(PATH);
System.out.println("----------2");
if(fileconn.exists()){
fileconn.delete();
System.out.println("----------3");
}
fileconn.create();
System.out.println("----------4");
OutputStream os=fileconn.openOutputStream();
System.out.println("----------5");
os.write(rawImage);
GetfileName =fileconn.getName();
System.out.println("----------6");
System.out.println("GetfileName----------"+GetfileName);
fileconn.close();
System.out.println("----------7");
os.close();
Status.show("Image is Captured",200);
GetPhotofileName.setText(GetfileName);
System.out.println("----------8");
if(_p!=null)
_p.close();
System.out.println("----------9");
}catch(Exception e){
if(_p!=null){
_p.close();
}
if(fileconn!=null){
try{
fileconn.close();
}catch (IOException e1){
//if the action is other than click the trackwheel(means go to the menu options) then we do nothing;
}
}
}
}
}
return handled;
}
public MyScreen(){
setTitle("Camera App");
try{
System.out.println("Debug------------10");
_p = javax.microedition.media.Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
_p.realize();
_videoControl = (VideoControl) _p.getControl("VideoControl");
System.out.println("Debug------------11");
if (_videoControl != null){
Field videoField = (Field) _videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
_videoControl.setDisplayFullScreen(true);
System.out.println("Debug------------12");
_videoControl.setVisible(true);
_p.start();
System.out.println("Debug------------13");
if(videoField != null){
add(videoField);
System.out.println("Debug------------14");
}
}
}catch(Exception e){
if(_p!=null) {
_p.close();
}
Dialog.alert(e.toString());
}
add(GetPhotofileName);
}
}
on the 8520 (Has a Memory Card) the code works fine on the 9780 (Has no Memory Card) the the code stops at "System.out.println("debug---1")", can anyone please tell me if you can see any problem with my code???
public static boolean SdcardAvailabulity() {
String root = null;
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements()) {
root = (String) e.nextElement();
if( root.equalsIgnoreCase("sdcard/") ) {
return true;
}else if( root.equalsIgnoreCase("store/") ) {
return false;
}
}
class MySDListener implements FileSystemListener {
public void rootChanged(int state, String rootName) {
if( state == ROOT_ADDED ) {
if( rootName.equalsIgnoreCase("sdcard/") ) {
}
} else if( state == ROOT_REMOVED ) {
}
}
}
return true;
}
This is the sollution, My "SD card availability" code only returned true which caused the picture not to save when the blackberry had no memory card inserted. # Eugen Martynov Please read through the code and you will see it is there :)

Resources