Forgive me if this is a stupid question, I've been doing iphone and android for a while now and recently I need to develop for the web.
I'm using parse.com to handle my server requests. According to their documentation, I can do a subclass like this.
//A complex subclass of Parse.Object
var Monster = Parse.Object.extend("Monster", {
// Instance methods
hasSuperHumanStrength: function () {
return this.get("strength") > 18;
},
// Instance properties go in an initialize method
initialize: function (attrs, options) {
this.sound = "Rawr"
}
}, {
// Class methods
spawn: function(strength) {
var monster = new Monster();
monster.set("strength", strength);
return monster;
}
});
var monster = Monster.spawn(200);
alert(monster.get('strength')); // Displays 200.
alert(monster.sound); // Displays Rawr.
Ultimately I'm trying to translate the following code from Java to JS.
/**
* #author XujieSong
*
*/
#ParseClassName("_User")
public class SHUser extends ParseUser {
/**
* SHUser is a subclass of ParseUser
* Class name _User
*/
/**
* Default constructor
*/
public SHUser() {
}
/**
* Create a SHUser object with known objectId
* This method only returns a SHUser without data
* #param userID the objectId of the SHUser
* #return user a reference to a SHUser
*/
public SHUser(String userId) {
this.setObjectId(userId);
}
/**
* Create a new SHUser with attributes
* #param userName
* #param password
* #param email
* #param displayName
* #param installation
* #param profileImage
* #return user a new user
*/
public SHUser(String userName, String password, String email, String displayName) {
this.setUsername(userName);
this.setPassword(password);
this.setEmail(email);
this.setDisplayName(displayName);
}
}
And this is what I have got so far,
var SHUser = Parse.Object.extend("_User", {
/**
* Instance properties go in an initialize method
* #param {userId}
* #return {[type]}
*/
SHUser: function () {
},
/**
* Instance properties go in an initialize method
* #param {userId}
* #return {[type]}
*/
SHUser: function (userId) {
this.id = userId;
},
/**
* Instance properties go in an initialize method
* #param {userName}
* #param {password}
* #param {email}
* #param {displayName}
* #return {[type]}
*/
SHUser: function (userName, password, email, displayName) {
this.setUsername(userName);
this.setPassword(password);
this.setEmail(email);
this.setDisplayName(displayName);
}
}, {
// Class methods
});
after
var user = new SHUser(userId);
window.alert(Shelf.seller.id);
I got undefined.
So here's the question. Is it possible to have a default constructor, then a few customized constructors like the way it is in Java? Is it a good practice to do so? Thank you.
After further digging in Backbone.js, I've found the answer.
Turns out there's no need for any additional coding.
var SHUser = Parse.Object.extend("_User", {
/**
* Instance properties go in an initialize method
*/
initialize: function (attr, options) {
},
}, {
// Class methods
});
It's a backbone.js model, so when initializing, just pass the parameters in and it would work.
var seller = new SHUser({"id": sellerId});
And that's it!
For more information please refer to backbonejs.org
Related
Hi sorry for the vague title. I have a specific issue with the Amazon IAP API that you will see in the bottom of the post.
I implemented the API in the simplest way possible, that is I just imported their sample IAP app and pasted all of it in my app. I think the only thing that needs to be changed from the sample app is the SKU and marketplace.
This is a class called MySku.java from the sample app:
package com.amazon.sample.iap.entitlement;
/**
*
* MySku enum contains all In App Purchase products definition that the sample
* app will use. The product definition includes two properties: "SKU" and
* "Available Marketplace".
*
*/
public enum MySku {
// The only entitlement product used in this sample app
LEVEL2("com.amazon.sample.iap.entitlement.level2", "US");
private final String sku;
private final String availableMarkpetplace;
/**
* Returns the MySku object from the specified Sku and marketplace value.
*
* #param sku
* #param marketplace
* #return
*/
public static MySku fromSku(final String sku, final String marketplace) {
if (LEVEL2.getSku().equals(sku) && (marketplace == null || LEVEL2.getAvailableMarketplace().equalsIgnoreCase(marketplace))) {
return LEVEL2;
}
return null;
}
/**
* Returns the Sku string of the MySku object
*
* #return
*/
public String getSku() {
return this.sku;
}
/**
* Returns the Available Marketplace of the MySku object
*
* #return
*/
public String getAvailableMarketplace() {
return this.availableMarkpetplace;
}
private MySku(final String sku, final String availableMarkpetplace) {
this.sku = sku;
this.availableMarkpetplace = availableMarkpetplace;
}
}
So I have to change the sku and availableMarketplace. I know my in-app product's sku so I set it, but what do I change availableMarketPlace to so that my app allows all marketPlaces instead of just the US one?
you need to declare each SKU for each availableMarkpetplace, like this>
LEVEL2("com.amazon.sample.iap.entitlement.level2", "US"),
LEVEL2_MX("com.amazon.sample.iap.entitlement.level2", "MX");
And for the MySku function as follows>
public static MySku fromSku(final String sku, final String marketplace) {
for (MySku mySku : values()) {
if (mySku.getSku().equals(sku) &&
(null == marketplace || mySku.getAvailableMarketplace().equals(marketplace))) {
return mySku;
}
}
return null;
}
Don Pec
We are trying to run some standard Java code to send a message via Javamail from a 3rd part application, problem we have is there is a bug in the application meaning it isn't able to use inner classes.
Before anyone asks, please don't ask to fix the application, as it's not within our control. The company who owns the application has suggested others resolve the issue by creating a separate class, instead of using the inner class of RecipientType within setRecipients.
We have tried to no avail to get this to work, creating a new class for RecipientType, although we are having trouble referencing it as it's not a method within setRecipients.
Would be grateful if anyone has an idea of how to get round having to use an inner class within MimeMessage? Is there a way we can hard code this?
Additional info:
This is what we are calling in the application
// new MIME message, version 1.0:
javax.mail.Message message = new javax.mail.internet.MimeMessage(session);
message.setHeader("MIME-Version" , "1.0" );
message.setFrom(new javax.mail.internet.InternetAddress(fromEmailAddress, fromEmailPersonal ));
message.setRecipients(javax.mail.Message.RecipientType.TO, javax.mail.internet.InternetAddress.parse( recipientEmailAddress ));
message.setSubject( emailSubject );
message.setText(emailBody);
javax.mail.Transport.send(message);
This is the section of Message.java that is failing
/**
* This inner class defines the types of recipients allowed by
* the Message class. The currently defined types are TO,
* CC and BCC.
*
* Note that this class only has a protected constructor, thereby
* restricting new Recipient types to either this class or subclasses.
* This effectively implements an enumeration of the allowed Recipient
* types.
*
* The following code sample shows how to use this class to obtain
* the "TO" recipients from a message.
* <blockquote><pre>
*
* Message msg = folder.getMessages(1);
* Address[] a = m.getRecipients(Message.RecipientType.TO);
*
* </pre></blockquote>
*
* #see javax.mail.Message#getRecipients
* #see javax.mail.Message#setRecipients
* #see javax.mail.Message#addRecipients
*/
public static class RecipientType implements Serializable {
/**
* The "To" (primary) recipients.
*/
public static final RecipientType TO = new RecipientType("To");
/**
* The "Cc" (carbon copy) recipients.
*/
public static final RecipientType CC = new RecipientType("Cc");
/**
* The "Bcc" (blind carbon copy) recipients.
*/
public static final RecipientType BCC = new RecipientType("Bcc");
/**
* The type of recipient, usually the name of a corresponding
* Internet standard header.
*
* #serial
*/
protected String type;
private static final long serialVersionUID = -7479791750606340008L;
/**
* Constructor for use by subclasses.
*
* #param type the recipient type
*/
protected RecipientType(String type) {
this.type = type;
}
/**
* When deserializing a RecipientType, we need to make sure to
* return only one of the known static final instances defined
* in this class. Subclasses must implement their own
* <code>readResolve</code> method that checks for their known
* instances before calling this super method.
*
* #return the RecipientType object instance
* #exception ObjectStreamException for object stream errors
*/
protected Object readResolve() throws ObjectStreamException {
if (type.equals("To"))
return TO;
else if (type.equals("Cc"))
return CC;
else if (type.equals("Bcc"))
return BCC;
else
throw new InvalidObjectException(
"Attempt to resolve unknown RecipientType: " + type);
}
#Override
public String toString() {
return type;
}
}
This is the custom class we tried to implement in place of the inner class, labelled RecipientType
import javax.mail.*;
import javax.activation.*;
import java.lang.*;
import java.io.*;
import java.util.*;
import java.text.ParseException;
public class RecipientType implements Serializable {
/**
* The "To" (primary) recipients.
*/
public static final RecipientType TO = new RecipientType("To");
/**
* The "Cc" (carbon copy) recipients.
*/
public static final RecipientType CC = new RecipientType("Cc");
/**
* The "Bcc" (blind carbon copy) recipients.
*/
public static final RecipientType BCC = new RecipientType("Bcc");
/**
* The type of recipient, usually the name of a corresponding
* Internet standard header.
*
* #serial
*/
protected String type;
private static final long serialVersionUID = -7479791750606340008L;
/**
* Constructor for use by subclasses.
*
* #param type the recipient type
*/
protected RecipientType(String type) {
this.type = type;
}
/**
* When deserializing a RecipientType, we need to make sure to
* return only one of the known static final instances defined
* in this class. Subclasses must implement their own
* <code>readResolve</code> method that checks for their known
* instances before calling this super method.
*
* #return the RecipientType object instance
* #exception ObjectStreamException for object stream errors
*/
protected Object readResolve() throws ObjectStreamException {
if (type.equals("To"))
return TO;
else if (type.equals("Cc"))
return CC;
else if (type.equals("Bcc"))
return BCC;
else
throw new InvalidObjectException(
"Attempt to resolve unknown RecipientType: " + type);
}
#Override
public String toString() {
return type;
}
}
This is how we tried implementing the custom class
message.setRecipients(RecipientType.TO,
javax.mail.internet.InternetAddress.parse( recipientEmailAddress ));
We get the following error:
Unable to parse expression; undefined method: addRecipient for class: javax.mal.Message (line: 29, col:2)
Trying to print the username in the method printShortSummary in the MessagePost class. The username is private in the Post class. Doing this for educational purposes. Still getting error that the username is private in Post.
import java.util.ArrayList;
/**
* This class stores information about a news feed post in a
* social network. Posts can be stored and displayed. This class
* serves as a superclass for more specific post types.
*
* #author Michael Kölling and David J. Barnes
* #version 0.2
*/
public class Post
{
private String username; // username of the post's author
private long timestamp;
private int likes;
private ArrayList<String> comments;
/**
* Constructor for objects of class Post.
*
* #param author The username of the author of this post.
*/
public Post(String author)
{
username = author;
timestamp = System.currentTimeMillis();
likes = 0;
comments = new ArrayList<>();
}
public void getUserName()
{
getUserName();
}
/**
* Record one more 'Like' indication from a user.
*/
public void like()
{
likes++;
}
/**
* Record that a user has withdrawn his/her 'Like' vote.
*/
public void unlike()
{
if (likes > 0) {
likes--;
}
}
/**
* Add a comment to this post.
*
* #param text The new comment to add.
*/
public void addComment(String text)
{
comments.add(text);
}
/**
* Return the time of creation of this post.
*
* #return The post's creation time, as a system time value.
*/
public long getTimeStamp()
{
return timestamp;
}
/**
* Display the details of this post.
*
* (Currently: Print to the text terminal. This is simulating display
* in a web browser for now.)
*/
public void display()
{
System.out.println(username);
System.out.print(timeString(timestamp));
if(likes > 0) {
System.out.println(" - " + likes + " people like this.");
}
else {
System.out.println();
}
if(comments.isEmpty()) {
System.out.println(" No comments.");
}
else {
System.out.println(" " + comments.size() + " comment(s). Click here to view.");
}
}
/**
* Create a string describing a time point in the past in terms
* relative to current time, such as "30 seconds ago" or "7 minutes ago".
* Currently, only seconds and minutes are used for the string.
*
* #param time The time value to convert (in system milliseconds)
* #return A relative time string for the given time
*/
private String timeString(long time)
{
long current = System.currentTimeMillis();
long pastMillis = current - time; // time passed in milliseconds
long seconds = pastMillis/1000;
long minutes = seconds/60;
if(minutes > 0) {
return minutes + " minutes ago";
}
else {
return seconds + " seconds ago";
}
}
}
import java.util.ArrayList;
/**
* This class stores information about a post in a social network news feed.
* The main part of the post consists of a (possibly multi-line)
* text message. Other data, such as author and time, are also stored.
*
* #author Michael Kölling and David J. Barnes
* #version 0.2
*/
public class MessagePost extends Post
{
private String message; // an arbitrarily long, multi-line message
/**
* Constructor for objects of class MessagePost.
*
* #param author The username of the author of this post.
* #param text The text of this post.
*/
public MessagePost(String author, String text)
{
super(author);
message = text;
}
public static void printShortSummary()
{
Post.getUserName();
System.out.print ("Message postfrom" + username);
}
/**
* Return the text of this post.
*
* #return The post's message text.
*/
public String getText()
{
return message;
}
}
You should be calling getUserName() but obviously cannot because it returns void and causes a Stack Overflow exception if called:
public void getUserName()
{
getUserName();
}
This should be
public String getUserName()
{
return userName;
}
And then that's how you access the user name from the subclass.
After that you would modify this method to be:
public static void printShortSummary()
{
//Post.getUserName();
System.out.print ("Message postfrom" + getUserName());
}
The portion where you have Post.getUserName(); doesn't make any sense, it's not a static method and can't be referenced in that manner.
If you don't have access to Post class or you don't wanna change Post class, you can use java Reflection API to access private members in any class
Ex:
public void printShortSummary() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field field = Post.class.getDeclaredField("username");
field.setAccessible(true);
System.out.print("Message post from " + field.get(this).toString());
}
Note : Anyway this not the object oriented way
I am working on adding support for property observations for my open source library droidQuery, however the propertyChange method is not being called in my tests. What do I need to do to get this to work? Here is my code:
ViewObserver.java
package self.philbrown.droidQuery;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import android.view.View;
/**
* Provides Property Change Listening to simulate bindings
* #author Phil Brown
*
*/
public class ViewObserver implements PropertyChangeListener
{
/** The function to call when the interface's method is invoked. */
private Function function;
/**
* Constructor
* #param droidQuery an instance of droidQuery
* #param function the function to call when the value changes. Will include a {#link Observation}
* Object with information about the KVO operation.
*/
public ViewObserver(Function function)
{
this.function = function;
}
#Override
public void propertyChange(PropertyChangeEvent event) //<-- This is never reached!
{
Observation observation = new Observation(event);
function.invoke($.with((View) event.getSource()), observation);
}
/**
* Represents an observation event that occured.
*/
public static class Observation
{
/** The old value prior the this Observation */
public Object oldValue;
/** The new value */
public Object newValue;
/** The name of the property that has changed from {#code oldValue} to {#code newValue}. */
public String property;
/**
* Constructor. Private since it is only used locally.
* #param event
*/
private Observation(PropertyChangeEvent event)
{
oldValue = event.getOldValue();
newValue = event.getNewValue();
property = event.getPropertyName();
}
}
}
Relevant portions of droidQuery.java (the rest available on github):
/** Used for Property Change Listening to simulate KVO Binding in droidQuery */
private static Map<View, Map<String, WeakReference<Observer>>> observers;
//The constructor has this:
//if (observers == null)
// observers = new HashMap<View, Map<String, WeakReference<Observer>>>();
/**
* Observe changes to the given property and respond to modification events. This requires
* a getter and setter method for the given property on the selected views. Passing "*" will
* add the property observer for all of the fields in each selected view. For example:
* <pre>
* $.with(myButton).observe("selected", new Function() {
* #Override
* public void invoke($ droidQuery, Object... params) {
* Observation ob = (Observation) params[0];
* Log.i("$", ob.property + " changed to " + ob.newValue);
* }
* });
* </pre>
* #param property name of the property to observe. If set to "*", all fields will be observed.
* #param onPropertyChanged the Function to call when the given property has changed. The argument
* passed to {#code onPropertyChanged} will be an instance of {#link ViewObserver.Observation},
* and will contain the old value, new value, and the property name. The given instance of droidQuery
* will have the observing view selected.
*/
public $ observe(String property, Function onPropertyChanged)
{
for (View view : views)
{
Map<String, WeakReference<Observer>> kvo = observers.get(view);
if (kvo == null)
{
kvo = new HashMap<String, WeakReference<Observer>>();
}
WeakReference<Observer> ref = kvo.get(property);
if (ref != null && ref.get() != null)
{
if (property.equals("*"))
ref.get().support.removePropertyChangeListener(ref.get().kvo);
else
ref.get().support.removePropertyChangeListener(property, ref.get().kvo);
}
Observer observer = new Observer();
observer.support = new PropertyChangeSupport(view);
observer.kvo = new ViewObserver(onPropertyChanged);
ref = new WeakReference<Observer>(observer);
if (property.equals("*"))
observer.support.addPropertyChangeListener(observer.kvo);
else
observer.support.addPropertyChangeListener(property, observer.kvo);
kvo.put(property, ref);
observers.put(view, kvo);
}
return this;
}
/**
* Contains Objects pertaining to the property change listener for a view in droidQuery.
*/
public static class Observer
{
/** Manages property observers registered to receive events */
public PropertyChangeSupport support;
/** The property observer */
public ViewObserver kvo;
}
I don't really know exactly how to word this but basically I need to get the child class instance of an Actor without assigning it (if that makes since?). Is this possible?
package org.game.world.entity.actor;
import java.util.HashMap;
import java.util.Map;
import org.game.world.entity.Entity;
import org.game.world.entity.actor.npc.NPC;
import org.game.world.entity.actor.player.Player;
import org.game.world.entity.actor.player.PlayerData;
public abstract class Actor extends Entity {
/**
* The type of Actor this Entity should be
* recognized as.
*/
private final ActorType actorType;
/**
* A map of ActionStates, not necessarily 'Attributes'.
*/
private final Map<ActionState, Boolean> actionState = new HashMap<ActionState, Boolean>();
/**
* Constructs a new Actor {#Entity}.
*/
public Actor(ActorType actorType) {
this.actorType = actorType;
actionState.putAll(ActionState.DEFAULT_ACTION_STATES);
}
/**
* Gets the status of a {#Actor} ActionSate.
* #param state The ActionState.
* #return The ActionState flag.
*/
public boolean getActionState(ActionState state) {
return actionState.get(state);
}
/**
* Sets a {#Actor} ActionState flag.
* #param state The ActionState.
* #param flag The flag true:false.
*/
public void setActionState(ActionState state, boolean flag) {
actionState.put(state, flag);
}
/**
* Resets all ActionState's for this Actor.
*/
public void setDefaultActionStates() {
actionState.putAll(ActionState.DEFAULT_ACTION_STATES);
}
/**
* Checks if this Actor is a specific ActorType (i.e NPC)
* #param actorType The ActorType
* #return
*/
public boolean isActorType(ActorType actorType) {
return this.actorType == actorType;
}
/**
* The type of Actor.
*/
public static enum ActorType {
PLAYER,
NPC
}
}
An Actor type.
package org.game.world.entity.actor.player;
import org.game.world.entity.Location;
import org.game.world.entity.actor.Actor;
import org.game.world.entity.actor.SkillLink;
/**
* This class represents a Player {#Actor} in the world.
*
* #author dillusion
*
*/
public class Player extends Actor {
/**
* This Player objects unique set of stored
* data.
*/
private final PlayerData playerData;
/**
* Creates a new Player object in the world.
* #param playerData The set of data unique to this Player.
*/
public Player(PlayerData playerData) {
super(ActorType.PLAYER);
this.playerData = playerData;
}
/**
* Gets the players name.
* #return The name.
*/
public String getName() {
return playerData.name;
}
/**
* Gets the players password.
* #return The password.
*/
public String getPassword() {
return playerData.password;
}
/**
* Gets the players permission level.
* #return The permission.
*/
public Permission getPermission() {
return playerData.permission;
}
/**
* Gets the players SkillLink instance.
* #return The SkillLink.
*/
public SkillLink getSkillLink() {
return playerData.skillLink;
}
#Override
public Location getLocation() {
return playerData.location;
}
#Override
public Location setLocation(Location location) {
return playerData.location = location;
}
}
But let's say I have multiple 'Actors'. I don't want to have to cast if I don't need to.
Sorry if I didn't explain this very well.
I dont know what are you questioning about here - so what i have figured out that you might want to do is to use Player as Actor right? Well that is possible by Java standard and inheritance
Actor temp=new Actor(){//implementing abstract methods if any}
Actor player=new Player(); //that is still fine as Actor is common superclas for player and actor
Player another=(Player)player; // thats just fine after typecasting
////but
another=player; // compile error, type mismatch
another=(Player)temp; // ClassCastException but no compilation error;
But still you can use different Actors and Players as Actors.