In my new android app based on parse, I would prefer pinning all sub-elements myself / not automatically, as pinning a certain sub-element would result in infinite recursion or just does not make sens in my context.
Is there a way to pin and unpin an object not recursively?
I am already able to pin an object not recursively, but it is not such a pretty way:
Method m = ParseObject.class.getDeclaredMethod("pinInBackground", String.class, boolean.class);
m.setAccessible(true);
Object object = m.invoke(parseobject, pintag, false);
if(object instanceof Task) {
Task task = (Task) object;
return task;
}
Is there any normal way to achieve this?
And is it somehow possible to unpin an object without this recursion mentioned in the Javadoc?
Removes the object and every object it points to in the local datastore, recursively.
As there is apparently at the time no solution for my problem implemented in the Parse-SDK-Android,
I implemented some functions myself.
Currently the pull request is still not merged.
If someone needs a fast solution, feel free to use my branch:
implementation 'com.github.thomax-it.Parse-SDK-Android:parse:1.21.1'
Related
What I am trying to do?
I am trying to add try/catch block in start and end of a particular method.
Why am I overriding asm.ClassWriter.getCommonSuperClass(String class1,String class2)?
I am using flag COMPUTE_FRAMES, and because of that, asm.ClassWriter.getCommonSuperClass() this class is being called and it is trying to load some classes again using class.ForName(), and saying classNotFoundException. I read somewhere to override this method and make sure it gets these two classes loaded. I got hold of Instrumentation object and got all loaded classes, but there are still some classes which are not loaded and this method throws NullPointer Exception..
Any suggesstions how to override it?
EDITED THE QUESTION BASED ON BELOW RESPONSE
What I understand here is :
1. There is no need to use COMPUTE_FRAMES instead of COMPUTE_MAXS, if I am trying to add a try/catch block for method content.
2. If I want to just add try/catch block for method content,(assume jdk8 only) then i just need to write try/catch block ASM part and rest should fall in place.
For a method which is called from a thread:
public void execute()throws IOException{
//some code
}
Below code should add try/catch block and should not give any java verify error?:
private Label startFinally = new Label();
public void visitMaxs(int maxStack, int maxLocals) {
Label endFinally = new Label();
visitTryCatchBlock(startFinally, endFinally, endFinally, "java/lang/Exception");
visitLabel(endFinally);
visitFrame(F_NEW, 0, null, 1, new Object[]{"java/lang/Exception"});
visitVarInsn(ASTORE, 1);
visitVarInsn(ALOAD, 1);
visitMethodInsn(INVOKEVIRTUAL, "java/lang/Exception", "printStackTrace", "()V", false);
visitInsn(RETURN);
}
public void visitCode() {
mv.visitLabel(startFinally);
super.visitCode();
}
When you start having to deal with getCommonSuperClass you are entering the very issue that stack map frames were designed to solve. Instead of letting the verifier do such a common superclass search, the frames derived from information available to the compiler should tell which type to assume and verifying the correctness is cheaper than performing this search.
But, of course, if you use a framework like ASM and let it conveniently calculate all these frames from scratch without the information available to the compiler, you end up doing that expensive operation and even have to assist ASM in case the types are not available to a simple Class.forName call (or you want avoid the loading of the classes).
You should note two important things:
You don’t have to load these classes. This method intentionally provides two strings and expect a result string. If you have meta information available that allow you to determine the common super type based on the name, you can use it
When you use Instrumentation to search for the name among all loaded classes, you might miss the class because it might not have been loaded yet. Even worse, you could get the wrong class in a more complex scenario when classes with the same name have been loaded by different ClassLoaders
At this time you should think about whether adhering to the original intent of using the already known information to generate the right frame is an option. When you instrument a class of a version where stack map frames are mandatory, all frames beside the one required for your exception handler are already present. And for older class files without frames, you don’t need to compute them anyway.
When you chain a ClassReader with a ClassWriter it will not only replicate members and instructions but also the stack map frames, unless you specify COMPUTE_FRAMES which causes ASM to drop all visited frames and recalculate them from scratch. So the first thing to do is to change COMPUTE_FRAMES back to COMPUTE_MAXS and then insert visitFrame calls as needed.
For covering the entire method with one exception handler, we need exactly one frame, for the entry of the handler (assuming there are no branches inside the handler itself). We already know that the operand stack consist of a sole reference to the exception itself—that’s always the case for exception handlers. Since the guarded code spans the entire method, no additional local variables introduced inside the method are available, so only this (if the method is not static) and the parameters are available—unless the method’s code reuses them for other purposes (ordinary Java code usually doesn’t). But the good news is, you don’t have to deal with them unless you want to use them.
So let’s assume we want to cover the entire method with an exception handler which will catch the exception, print its stack trace and return (assuming void). Then, we don’t need any local variables and the entire code, applied after completely visiting the original code, looks like:
Label endFinally = new Label();
visitTryCatchBlock(startFinally, endFinally, endFinally, "java/lang/Exception");
visitLabel(endFinally);
visitFrame(F_NEW, 0, null, 1, new Object[]{"java/lang/Exception"});
visitVarInsn(ASTORE, 1);
visitVarInsn(ALOAD, 1);
visitMethodInsn(INVOKEVIRTUAL, "java/lang/Exception", "printStackTrace", "()V", false);
visitInsn(RETURN);
The logic is
visitFrame(F_NEW, // not derived from a previous frame
0, null, // no local variables
1, new Object[]{"java/lang/Exception"} // one exception on the stack
);
Of course, the type of the exception on the stack must match the type of the visitTryCatchBlock or be a super type of it. Note that the local variable we’re going to introduce after entering the handler is irrelevant. If you want to re-throw instead of returning, just replace
visitInsn(RETURN);
with
visitVarInsn(ALOAD, 1);
visitInsn(ATHROW);
and the logic regarding the stack map frame doesn’t change.
I'm trying my best to adhere to some strict design patterns while developing my current code base, as I am hoping I will be working on it for quite a while to come and I want it to be as flexible and clean as possible. However, in trying to combine all these design patterns to solve the current problem I am facing, I am running into some issues I'm hoping someone can advise me a bit on.
I'm working on some basic homebrewn GUI widgets that are to provide some generic click/drag/duplication behavior. On the surface, the user clicks the widget, then drags it somewhere. Having dragged it far enough, the widget will 'appear' to clone itself and leave the user dragging this new copy.
The Prototype design pattern obviously enters the foray to make this duplication functionality generalizable for many types of widgets. For most objects, the story ends there. The Prototype object is virtually an identical copy of the duplicated version the user ends up dragging.
However, one of the objects I want to duplicate has some fairly big resources attached to it, so I don't want to load them until the user actually decides to click and drag, and subsequently duplicate, that particular object. Enter Lazy initialization. But this presents me with a bit of a conundrum. I cannot just let the prototype object clone itself, as it would need to have the big resources loaded before the user duplicates the dummy prototype version. I'm also not keen on putting some logic into the object which, upon being cloned/duplicated, checks what's going on and decides if it should load in these resources. Instead, a helpful person suggested I create a kind of shell object and when it gets cloned, it were to return this more derived version containing the resources allowing for me to both use RAII and lazy initialization.
But I'm having some trouble implementing this, and I'm starting to wonder if I can even do it the way I'm thinking it should be done. Right now it looks like this:
class widgetSpawner : public widget {
public:
widgetSpawner();
~widgetSpawner();
private:
widget* mPrototypeWidget; // Blueprint with which to spawn new elements
};
class widgetAudioShell : public widget {
public:
widgetAudioShell(std::string pathToAudioFile);
widgetAudioShell( const widgetAudioShell& other );
~widgetAudioShell();
virtual widgetAudio* clone() const { return new widgetAudio(*this); };
private:
std::string mPathToAudioFile;
};
class widgetAudio : public widgetAudioShell {
public:
widgetAudio(AudioEngineAudioTrack &aTrack);
widgetAudio( const widgetAudio& other );
widgetAudio( const widgetAudioShell& other );
~widgetAudio();
virtual widgetAudio* clone() const { return new widgetAudio(*this); };
private:
AudioEngineAudioTrack &mATrack;
};
Obviously, this is not workable as the shell doesn't know the object that's using it to derive a new class. So it cannot return it via the clone function. However, if I keep the two inheritance-wise independent (as in they both inherit from widget), then the compiler complains about lack of co-variance which I think makes sense? Or maybe it's because I am again having the trouble of properly defining one before the other.
Essentially widgetAudioShell needs to know about widgetAudio so it can return a 'new' copy. widgetAudio needs to know about widgetAudioShell so it can read it's member functions when being created/cloned.
If I am not mistaken, this circular dependency is there because of my like of using references rather than pointers, and if I have to use pointers, then suddenly all my other widgets need to do the same which I'd find quite hellish. I'm hoping someone who's had their fingers in something similar might provide some wisdom?
I will explain with an example. My GWT project has a Company module, which lets a user add, edit, delete, select and list companies.
Of these, the add, edit and delete operations lands back the user on the CompanyList page.
Thus, having three different events - CompanyAddedEvent, CompanyUpdatedEvent and CompanyDeletedEvent, and their respective event handlers - seems overkill to me, as there is absolutely not difference in their function.
Is it OK to let a single event manage the three operations?
One alternative I think is to use some event like CompanyListInvokedEvent. However, somewhere I think its not appropriate, is the event actually is not the list being invoked, but a company being added/updated/deleted.
If it had been only a single module, I would have get the task done with three separate events. But other 10 such modules are facing this dilemma. It means 10x3 = 30 event classes along with their 30 respective handlers. The number is large enough for me to reconsider.
What would be a good solution to this?
UPDATE -
#ColinAlworth's answer made me realize that I could easily use Generics instead of my stupid solution. The following code represents an event EntityUpdatedEvent, which would be raised whenever an entity is updated.
Event handler class -
public class EntityUpdatedEvent<T> extends GwtEvent<EntityUpdatedEventHandler<T>>{
private Type<EntityUpdatedEventHandler<T>> type;
private final String statusMessage;
public EntityUpdatedEvent(Type<EntityUpdatedEventHandler<T>> type, String statusMessage) {
this.statusMessage = statusMessage;
this.type = type;
}
public String getStatusMessage() {
return this.statusMessage;
}
#Override
public com.google.gwt.event.shared.GwtEvent.Type<EntityUpdatedEventHandler<T>> getAssociatedType() {
return this.type;
}
#Override
protected void dispatch(EntityUpdatedEventHandler<T> handler) {
handler.onEventRaised(this);
}
}
Event handler interface -
public interface EntityUpdatedEventHandler<T> extends EventHandler {
void onEventRaised(EntityUpdatedEvent<T> event);
}
Adding the handler to event bus -
eventBus.addHandler(CompanyEventHandlerTypes.CompanyUpdated, new EntityUpdatedEventHandler<Company>() {
#Override
public void onEventRaised(EntityUpdatedEvent<Company> event) {
History.newItem(CompanyToken.CompanyList.name());
Presenter presenter = new CompanyListPresenter(serviceBundle, eventBus, new CompanyListView(), event.getStatusMessage());
presenter.go(container);
}
});
Likewise, I have two other Added and Deleted generic events, thus eliminating entire redundancy from my event-related codebase.
Are there any suggestions on this solution?
P.S. > This discussion provides more insight on this problem.
To answer this question, let me first pose another way of thinking about this same kind of problem - instead of events, we'll just use methods.
In my tiered application, two modules communicate via an interface (notice that these methods are all void, so they are rather like events - the caller doesn't expect an answer back):
package com.acme.project;
public interface CompanyServiceInteface {
public void addCompany(CompanyDto company) throws AcmeBusinessLogicException;
public void updateCompany(CompanyDto company) throws AcmeBusinessLogicException;
public void deleteCompany(CompanyDto company) throws AcmeBusinessLogicException;
}
This seems like overkill to me - why not just reduce the size of this API to one method, and add an enum argument to simplify this. This way, when I build an alternative implementation or need to mock this in my unit tests, I just have one method to build instead of three. This gets to be clearly overkill when I make the rest of my application - why not just ObjectServiceInterface.modify(Object someDto, OperationEnum invocation); to work for all 10 modules?
One answer is that you might want want to drastically modify the implementation of one but not the others - now that you've reduced this to just one method, all of this belongs inside that switch case. Another is that once simplified in this way, the inclination often to further simplify - perhaps to combine create and update into just one method. Once this is done, all callsites must make sure to fulfill all possible details of that method's contract instead of just the one specific one.
If the receivers of those events are simple and will remain so, there may be no good reason to not just have a single ModelModifiedEvent that clearly is generic enough for all possible use cases - perhaps just wrapping the ID to request that all client modules refresh their view of that object. If a future use case arises where only one kind of event is important, now the event must change, as must all sites that cause the event to be created so that they properly populate this new field.
Java shops typically don't use Java because it is the prettiest language, or because it is the easiest language to write or find developers for, but because it is relatively easy to maintain and refactor. When designing an API, it is important to consider future needs, but also to think about what it will take to modify the current API - your IDE almost certainly has a shortcut key to find all invocations of a particular method or constructor, allowing you to easily find all places where that is used and update them. So consider what other use cases you expect, and how easily the rest of the codebase can be udpated.
Finally, don't forget about generics - for my example above, I would probably make a DtoServiceInterface to simplify matters, so that I just declare the one interface with three methods, and implement it and refer to it as needed. In the same way, you can make one set of three GwtEvent types (with *Handler interfaces and possibly Has*Handlers as well), but keep them generic for all possible types. Consider com.google.gwt.event.logical.shared.SelectionEvent<T> as an example here - in your case you would probably want to make the model object type a parameter so that handlers can check which type of event they are dealing with (remember that generics are erased in Java), or source from one EventBus for each model type.
I am making a tactical RPG game in XNA 4.0 and was wondering what the best way to go about "phases" is? What I mean by phases is creating a phase letting the player place his soldiers on the map, creating a phase for the player's turn, and another phase for the enemy's turn.
I was thinking I could create some sort of enum and set the code in the upgrade/draw methods to run accordingly, but I want to make sure this is the best way to go about it first.
Thanks!
Edit: To anaximander below:
I should have mentioned this before, but I already have something implemented in my application that is similar to what you mentioned. Mine is called ScreenManager and Screen but it works exactly in the same way. I think the problem is that I am treating screen, phase, state, etc, to be different things but in reality they are the same thing.
Basically what I really want is a way to manage different "phases" in a single screen. One of my screens called map will basically represent all of the possible maps in the game. This is where the fighting takes place etc. I want to know what is the best way to go about this:
Either creating an enum called FightStage that holds values like
PlacementPhase,PlayerPhase, etc, and then split the Draw and
Update method according to the enum
Or create an external class to manage this.
Sorry for the confusion!
An approach I often take with states or phases is to have a manager class. Essentially, you need a GamePhase object which has Initialise(), Update(), Draw() and Dispose() methods, and possibly Pause() and Resume() as well. Also often worth having is some sort of method to handle the handover. More on that later. Once you have this class, inherit from it to create a class for each phase; SoldierPlacementPhase, MovementPhase, AttackPhase, etc.
Then you have a GamePhaseManager class, which has Initialise(), Update(), Draw() and Dispose() methods, and probably a SetCurrentPhase() method of some kind. You'll also need an Add() method to add states to the manager - it'll need a way to store them. I recommend a Dictionary<> using either an int/enum or string as the key. Your SetCurrentPhase() method will take that key as a parameter.
Basically, what you do is to set up an instance of the GamePhaseManager in your game, and then create and initialise each phase object and add it to the manager. Then your game's update loop will call GamePhaseManager.Update(), which simply calls through to the current state's Update method, passing the parameters along.
Your phases will need some way of telling when it's time for them to end, and some way of handling that. I find that the easiest way is to set up your GamePhase objects, and then have a method like GamePhase.SetNextPhase(GamePhase next) which gives each phase a reference to the one that comes next. Then all they need is a boolean Exiting with a protected setter and a public getter, so that they can set Exiting = true in their Update() when their internal logic decides that phase is over, and then in the GamePhaseManager.Update() you can do this:
public void Update(TimeSpan elapsed)
{
if (CurrentPhase.Exiting)
{
CurrentPhase.HandOver();
CurrentPhase = CurrentPhase.NextPhase;
}
CurrentPhase.Update(elapsed);
}
You'll notice I change phase before the update. That's so that the exiting phase can finish its cycle; you get odd behaviour otherwise. The CurrentPhase.HandOver() method basically gets the current phase to pass on anything the next phase needs to know to carry on from the right point. This is probably done by having it call NextPhase.Resume() internally, passing it any info it needs as parameters. Remember to also set Exiting = false in here, or else it'll keep handing over after only one update loop.
The Draw() methods are handled in the same way - your game loop calls GamePhaseManager.Draw(), which just calls CurrentPhase.Draw(), passing the parameters through.
If you have anything that isn't dependent on phase - the map, for example - you can either have it stored in the GamePhaseManager and call its methods in GamePhaseManager's methods, you can have the phases pass it around and have them call its methods, or you can keep it up at the top level and call it's methods alongsideGamePhaseManager's. It depends how much access the phases need to it.
EDIT
Your edit shows that a fair portion of what's above is known to you, but I'm leaving it there to help anyone who comes across this question in future.
If already you have a manager to handle stages of the game, my immediate instinct would be to nest it. You saw that your game has stages, and built a class to handle them. You have a stage that has its own stages, so why not use the stage-handling code you already wrote? Inherit from your Screen object to have a SubdividedScreen class, or whatever you feel like calling it. This new class is mostly the same as the parent, but it also contains its own instance of the ScreenManager class. Replace the Screen object you're calling map with one of these SubdividedScreen objects, and fill its ScreenManager with Screen instances to represent the various stages (PlacementPhase, PlayerPhase, etc). You might need a few tweaks to the ScreenManager code to make sure the right info can get to the methods that need it, but it's much neater than having a messy Update() method subdivided by switch cases.
I'm trying to put a HashMap<Object, List<Object>> into my dataModel, but when i call the template.process() method, I get the following exception:
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
at java.util.HashMap$KeyIterator.next(HashMap.java:828)
at freemarker.template.SimpleCollection$SimpleTemplateModelIterator.next(SimpleCollection.java:142)
at freemarker.core.IteratorBlock$Context.runLoop(IteratorBlock.java:157)
at freemarker.core.Environment.visit(Environment.java:351)
at freemarker.core.IteratorBlock.accept(IteratorBlock.java:95)
at freemarker.core.Environment.visit(Environment.java:196)
at freemarker.core.MixedContent.accept(MixedContent.java:92)
at freemarker.core.Environment.visit(Environment.java:196)
at freemarker.core.IteratorBlock$Context.runLoop(IteratorBlock.java:172)
at freemarker.core.Environment.visit(Environment.java:351)
at freemarker.core.IteratorBlock.accept(IteratorBlock.java:95)
at freemarker.core.Environment.visit(Environment.java:196)
at freemarker.core.MixedContent.accept(MixedContent.java:92)
at freemarker.core.Environment.visit(Environment.java:196)
at freemarker.core.Environment.process(Environment.java:176)
at freemarker.template.Template.process(Template.java:232)
After looking over some articles and older questions, I've tried to use a ConcurrentHashMap instead, to the same result. I've also tried making a copy using new HashMap<Object, List<Object>>(oldHashMap). Are there any other common fixes to this problem I could try?
EDIT: I know the general cause of ConcurrentModificationExceptions. Please only reply if you can help me understand why the framework Freemarker is throwing these exceptions, mkay? =)
Thanks!
The ConcurrentModificationException is caused by using an invalid iterator after the underlying collection has been changed. The only way to fix this is not changing the collection you are iterating over. In most cases this is not caused by multi-threading.
Simple Example:
//throws an exception in the second iteration
for(String s: list){
list.remove(s);//changes the collection
}
fix 1, not supported by all iterators:
Iterator<String> iter = list.iterator();
while(iter.hasNext()){
iter.next();
iter.remove();//iterator still valid
}
fix 2:
List<String> toRemove = ...;
for(String s: list){
toRemove.add(s);
}
list.removeAll(toRemove);
The exception means that, while you're iterating over the map, something has changed the map's contents.
Your best course of action is figure out what that "something" is. For example, it could be another thread, or it could be that you have a foreach loop and modify the map from within the loop.
It is very hard to give advice on how to best fix the problem until we understand what exactly is causing it and what the desired behaviour is.
You'll get this kind of problem on List and Map when doing something like this:
List<A> list = ...; //a list with few elements
for(A anObject : list){
list.add(anotherObject); //modify list inside the loop
}
The same goes with maps. The solution is to look for possible places where you might be modifying the map inside the loop over that map. Or if you are using a multi-threaded application, then it's possible that another thread is looping over the map while you are modifying it (or visa-versa). In such case you'll need to synchronize access to the map in both places: looping code and map modifying code.
There some info on it in the Java API for TreeMap here.
The iterators returned by the iterator
method of the collections returned by
all of this class's "collection view
methods" are fail-fast: if the map is
structurally modified at any time
after the iterator is created, in any
way except through the iterator's own
remove method, the iterator will throw
a ConcurrentModificationException.
Thus, in the face of concurrent
modification, the iterator fails
quickly and cleanly, rather than
risking arbitrary, non-deterministic
behavior at an undetermined time in
the future.
Note that the fail-fast behavior of an
iterator cannot be guaranteed as it
is, generally speaking, impossible to
make any hard guarantees in the
presence of unsynchronized concurrent
modification. Fail-fast iterators
throw ConcurrentModificationException
on a best-effort basis. Therefore, it
would be wrong to write a program that
depended on this exception for its
correctness: the fail-fast behavior of
iterators should be used only to
detect bugs.
Synchronise access to the hashmap so that only one thread can be accessing the hashmap at once.