Updating value in parse table - parse-platform

I am using parse.com cloud in my android application. i want to increase a field by one
I tried using three ways.
first i tried getting object using parseQuery.get(id) but it gives no object found for update after using parseObject.increament().
ParseQuery<ParseObject> parseQuery = ParseQuery.getQuery("Waive");
try {
ParseObject object=parseQuery.get(id);
object.increment("numberOfViews");
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException arg0) {
// TODO Auto-generated method stub
if(arg0==null){
Log.e("incremented", "by one");
}
else{
Log.e("not incremented", "by one");
arg0.printStackTrace();
}
}
});
} catch (ParseException e) {
// TODO Auto-generated catch block
Log.e("exception", e+"");
e.printStackTrace();
}
second way i used.i tried using ParseObject.increament but it gives no object found for update.
ParseQuery< ParseObject> query=new ParseQuery<ParseObject>("Waive");
query.getInBackground(id, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
// TODO Auto-generated method stub
Log.e("object id", object+"");
if(e==null && object!=null){
object.increment("numberOfViews");
try {
object.save();
} catch (ParseException exp) {
// TODO Auto-generated catch block
Log.e("exception", exp.getMessage());
exp.printStackTrace();
}
}
}
});
}
third way i tried ,first of all i get the value of that field then increamented that value by one and inserted that value in table by using parseObject.put
ParseQuery< ParseObject> query=new ParseQuery("Waive");
query.getInBackground(id, new GetCallback() {
#Override
public void done(ParseObject object, ParseException e) {
// TODO Auto-generated method stub
Log.e("object id", object+"");
if(e==null && object!=null){
int tmp=(Integer)object.getNumber("numberOfViews");
object.put("numberOfViews", tmp+1);
try {
object.save();
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Log.e("exception", e1.getMessage());
e1.printStackTrace();
}
}
}
});
}
but neither of these three is working please help me out.

It is due to the permission issues. Because you are trying to update a value you are not authorized for. Make it public by editing your table security on parse.com make it public writable to update by another user too

Related

How to fix 'No way to dispatch this command to Redis Cluster because keys have different slots' in Spring

I need to use Redis Cluster in Spring. But I'm getting the following error when I use mget or del on a list of keys: 'No way to dispatch this command to Redis Cluster because keys have different slots'. Showing a part of my Component code using JedisCluster.
It works when I use single key operations but not with multiple keys.
/* Component Code */
public class RedisServiceManager {
#Value("${redis.hosts}")
String hosts;
#Autowired
JedisPoolConfig jedisPoolConfig;
private JedisCluster jedisCluster;
#PostConstruct
private void init() {
List<String> redisHosts = Arrays.asList(hosts.split(","));
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
redisHosts.forEach(redisHost -> {
jedisClusterNode.add(new HostAndPort(redisHost, 6379));
});
jedisCluster = new JedisCluster(jedisClusterNode, jedisPoolConfig);
}
// This works
public String getValueForKey(String key) {
try {
return jedisCluster.get(key);
} catch (Exception e) {
return null;
}
}
// This works
public void delKey(String cacheKey) {
try {
jedisCluster.del(cacheKey);
} catch (Exception e) {
}
}
// This doesn't work
public List<String> getValuesForAllKeys(String... keys) {
try {
return jedisCluster.mget(keys);
} catch (Exception e) {
return new ArrayList<>();
}
}
// This doesn't work
public void delAllKeys(String... keys) {
try {
jedisCluster.del(keys);
} catch (Exception e) {
}
}
}
Can someone help with this?
This is not a bug or an issue, but is the way how redis cluster works. You can find more details in the cluster documentation. But don't worry: there is a "trick": you can use hash as described here

Get queue size of ThreadPoolTaskExecutor and add to queue in Spring boot

I have the following class which has multiple custom ThreadPoolTaskExecutors I am showing it with one in this example.
#Configuration
#EnableAsync
public class ExecutorConfig {
#Bean(name = "streetCheckerExecutor")
public Executor getStreetAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(50);
executor.setQueueCapacity(1000000);
executor.setThreadNamePrefix("streetCheckerExecutor-");
executor.initialize();
return executor;
}
}
I have the following class which gets content from the database, I want to be able to check the queue size of streetCheckerExecutor and if it's less than a certain number, to add the content to the queue
#Component
public class StreetChecker {
#Autowired
StreetRepository streetRepository;
#Autowired
StreetCheckService streetChecker;
#EventListener(ApplicationReadyEvent.class)
public void checkStreets() {
try {
List<Street> streetList = streetRepository.getStreets();
for (int i = 0; i < streetList.size(); i++) {
streetChecker.run(streetList.get(i));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("---------------------");
}
}
}
And below is the worker class
#Component
public class StreetCheckService {
#Async("streetCheckerExecutor")
public void run(Content content) {
try {
//do work
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
I am working with a lot of data and I don't want to grab everything from the database every time, but I want to check the queue size of streetCheckerExecutor and if it's less than a number, I want to get more content from the database and add it to the streetCheckerExecutor queque
Below is how I'm thinking I can do it by converting the above checkStreets to the one below
#EventListener(ApplicationReadyEvent.class)
public void checkStreets() {
while (true) {
try {
// check the queue size of streetCheckerExecutor
// if less than a number
// add to the queue
// else keep waiting and will try again in X minutes
} catch (Exception e) {
} finally {
try {
Thread.sleep(1000 * 60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
But how would I be able to get the size of the queue in the checkStreets() method?
You can just autowire in your ThreadPoolTaskExecutor and get the queue with getThreadPoolExecutor().getQueue().
#Autowire
#Qualifier("streetCheckerExecutor")
private Executor streetExecutor;
#EventListener(ApplicationReadyEvent.class)
public void checkStreets() {
while (true) {
try {
final BlockingQueue<Runnable> queue = streetExecutor.getThreadPoolExecutor().getQueue();
if(queue.size() <= 5) {
queue.add(() -> {
final List<Street> streetList = streetRepository.getStreets();
streetList.forEach(street -> {
streetChecker.run(street);
});
});
}
} catch (Exception e) {
} finally {
try {
Thread.sleep(1000 * 60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
i'm not sure this is what you meant, but something like this maybe.

"Cannot save a ParseUser that is not authenticated"

I am trying to save data in authData field android, But I am getting exception: Cannot save a ParseUser that is not authenticated" after only reading the user
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", email);
query.findInBackground(new FindCallback<ParseUser>() {
#SuppressWarnings("deprecation")
public void done(List<ParseUser> scoreList, ParseException e) {
if (e == null) {
if(scoreList.size()>0){
facebook_user = (ParseUser) scoreList.get(0);
facebook_user.isAuthenticated()
JSONObject obj = new JSONObject();
try {
obj.put("name", "xyz");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
facebook_user.put("authdata", obj);
facebook_user.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
// exception in this section //
//Cannot save a ParseUser that is not authenticated" after only reading the user//
});
}else{
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
It looks like you are attempting to modify that user with the .put() before saving:
facebook_user.put("authdata", obj);
facebook_user.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
// exception in this section //
});
If you want to change a user, you need to be logged in as the user, execute the change on Cloud Code using the masterKey, or change the user objects' ACL. Here's a SO post with a bit more info.
Let me know if you have any more questions.

Android calling AsyncTask().get() without execute()?

I'm having issues trying to understand how AsyncTask().get() actually works. I know it's a synchronous execution, However: I don't know how execute() and get() are connected.
I have this sample code from Google's docs:
// Async Task Class
class DownloadMusicfromInternet extends AsyncTask<String, String, String> {
// Show Progress bar before downloading Music
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("Task: ", "onPreExecute()");
}
// Download Music File from Internet
#Override
protected String doInBackground(String... f_url) {
for (int i = 0; i < 100; i++){
try {
Thread.sleep(100);
Log.d("Task: ", String.valueOf(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
// While Downloading Music File
protected void onProgressUpdate(String... progress) {
// Set progress percentage
Log.d("Task: ", "onProgressUpdate()");
}
// Once Music File is downloaded
#Override
protected void onPostExecute(String file_url) {
Log.d("Task: ", "onPostExecute()");
}
}
Now, from a button.onClick() I call this in 3 ways:
new DownloadMusicfromInternet().execute("");//works as expected, the "normal" way
//works the normal way, but it's synchronous
try {
new DownloadMusicfromInternet().execute("").get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
//does not work
try {
new DownloadMusicfromInternet().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
I'm confused as to how exactly execute() triggers doInBackground() and then immediately returns if get() is called, while get() has no effect on doInBackground() whatsoever.
execute() schedules the internal FutureTask (usually on a internal Executor) and returns immediately.
get() just calls FutureTask.get() on this internal future, i.e. it waits (if necessary) for the result.
So calling get() without calling execute() first waits indefinitely, as the result will never be available.
As you mentioned, when used the normal way, get() is not needed at all, as the result is handled in onPostExecute(). I didn't even know it existed before I tried to understand your question

Adobe CQ : Regarding Session in Event Listener

I have a question regarding event listener. We have a event listener which listen to delete node event and perform some activity say "send email".
While code review i found this, although this code is working fine i am not convinced with the session being handled here :
#Activate
protected void activate(ComponentContext context) {
try{
final String path="/content/dam/";
Session session = repository.loginAdministrative(repository.getDefaultWorkspace());
observationManager = session.getWorkspace().getObservationManager();
observationManager.addEventListener(this, Event.PROPERTY_REMOVED, path, true, null, null, true);
checkOutProperty = OsgiUtil.toString(context.getProperties()
.get(ASSET_LOCK_PROPNAME_UPDATE), ASSET_LOCK_PROPNAME_DEFAULT);
if (session != null && session.isLive()) {
session.save();
}
} catch (RepositoryException e) {
if(LOG.isErrorEnabled()){
LOG.error("Error Occured in activate method of Property Removed Listener class:" + e.getMessage());
}
}catch (Exception e) {
if(LOG.isErrorEnabled()){
LOG.error("Error Occured in activate method of Property Removed Listener class:"+e.getMessage());
}
}
}
#Deactivate
protected void deactivate(ComponentContext componentContext) {
try {
if (observationManager != null) {
observationManager.removeEventListener(this);
}
} catch (RepositoryException e) {
if(LOG.isErrorEnabled()){
LOG.error("Error Occured " + e);
}
} catch (Exception e) {
if(LOG.isErrorEnabled()){
LOG.error(e.getMessage());
}
}
}
Questions:
Best practice would be to create session object private to this class and should be logout in deactivate method?
Once an event is added in Observation Manager, do we really need session object? I was expecting if we should logout from session there.
EventListener are a bit cumbersome here. I fought many battles with JCR Sessions and Sling ResourceResolvers within them. The problem is, you need to keep the Session active as long as the Event Listener is active. So the only thing missing in your code is a logout on deactivate.
I created an AbstractEventListener which takes care of this and provides the following two methods and has two private members:
private Session session;
private ObservationManager observationManager;
protected void addEventListener(final EventListener eventListener,
final int eventTypes, final String path, final String[] nodeTypes) {
try {
session = getRepositorySession();
observationManager = session.getWorkspace().getObservationManager();
observationManager.addEventListener(eventListener, eventTypes,
path, true, null, nodeTypes, true);
} catch (RepositoryException e) {
LOGGER.error("Repository error while registering observation: ", e);
}
}
protected void removeEventListener(final EventListener eventListener) {
if (observationManager != null) {
try {
observationManager.removeEventListener(eventListener);
} catch (RepositoryException e) {
LOGGER.error(
"Repository error while unregistering observation: ", e);
} finally {
logoutSession(session);
}
}
}
And then in the actual EventListener I just call them:
protected void activate(ComponentContext context) {
addEventListener(this, Event.PROPERTY_ADDED| Event.PROPERTY_CHANGED, "/content/mysite", null);
}
}
protected void deactivate(ComponentContext componentContext) {
removeEventListener(this);
}

Resources