com.codename1.io.Preferences Java Examples

The following examples show how to use com.codename1.io.Preferences. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Message.java    From codenameone-demos with GNU General Public License v2.0 6 votes vote down vote up
public Message(JSONObject obj) {
    try {
        time = Long.parseLong(obj.getString("time"));
        senderId = obj.getString("fromId");
        recepientId = obj.getString("toId");
        message = obj.getString("message");
        name = obj.getString("name");
        picture = obj.getString("pic");
        
        // update the push id for the given user
        if(obj.has("pushId")) {
            String pushId = obj.getString("pushId");
            if(pushId != null) {
                Preferences.set("pid-" + senderId, pushId);
            }
        }
    } catch (JSONException ex) {
        // will this ever happen?
        Log.e(ex);
    }        
}
 
Example #2
Source File: StateMachine.java    From parse4cn1 with Apache License 2.0 6 votes vote down vote up
@Override
public boolean onPushReceivedBackground(JSONObject pushPayload) {
    if (handleBackgroundPush) {
        try {
            final String jsonStr = Preferences.get(KEY_APP_IN_BACKGROUND_PUSH_PAYLOAD, null);
            JSONArray existing;

            if (jsonStr == null) {
                existing = new JSONArray();
            } else {
                existing = new JSONArray(jsonStr);
            }
            existing.put(pushPayload);
            
            Preferences.set(KEY_APP_IN_BACKGROUND_PUSH_ERROR, null);
            Preferences.set(KEY_APP_IN_BACKGROUND_PUSH_PAYLOAD, existing.toString());
        } catch (JSONException ex) {
            Preferences.set(KEY_APP_IN_BACKGROUND_PUSH_ERROR, 
                    "An error occurred while trying to parse "
                    + "and cache push message '" + pushPayload 
                    + "' received in background. Error: " + ex.getMessage());
        }
    }
    return handleBackgroundPush;
}
 
Example #3
Source File: DefaultCrashReporter.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Installs a crash reporter within the system
 * @param promptUser indicates whether the user should be prompted on crash reporting
 * @param frequency the frequency with which we send the log to the server in debug mode in minutes
 * frequency must be at least 1. Any lower level automatically disables this feature
 */
public static void init(boolean promptUser, int frequency) {
    if(Preferences.get("$CN1_crashBlocked", false) || Log.getReportingLevel() == Log.REPORTING_NONE) {
        return;
    }
    if(Preferences.get("$CN1_pendingCrash", false)) {
        // we must have crashed during a report, send it.
        Log.sendLog();
        Preferences.set("$CN1_pendingCrash", false);
    }
    if(Log.getReportingLevel() == Log.REPORTING_DEBUG && frequency > 0) {
        java.util.Timer t = new java.util.Timer();
        t.schedule(new TimerTask() {
            public void run() {
                if(!Display.getInstance().isEdt()) {
                    Display.getInstance().callSerially(this);
                    return;
                }
                Log.sendLog();
            }
        }, frequency * 60000, frequency * 60000);
    }
    DefaultCrashReporter d = new DefaultCrashReporter();
    d.promptUser = promptUser && Preferences.get("$CN1_prompt", true);
    Display.getInstance().setCrashReporter(d);
}
 
Example #4
Source File: Solitaire.java    From codenameone-demos with GNU General Public License v2.0 6 votes vote down vote up
public void init(Object context) {
    try {
        theme = Resources.openLayered("/theme");
        UIManager.getInstance().setThemeProps(theme.getTheme(theme.getThemeResourceNames()[0]));
        int dpi =  Preferences.get("dpi", calculateDPI());
        cards = Resources.open("/gamedata.res",dpi);
        currentZoom = Preferences.get("zoom", defaultZoom);
    } catch(IOException e){
        e.printStackTrace();
    }
    // Pro users - uncomment this code to get crash reports sent to you automatically
    Display.getInstance().addEdtErrorHandler(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            evt.consume();
            Log.p("Exception in AppName version " + Display.getInstance().getProperty("AppVersion", "Unknown"));
            Log.p("OS " + Display.getInstance().getPlatformName());
            Log.p("Error " + evt.getSource());
            Log.p("Current Form " + Display.getInstance().getCurrent().getName());
            Log.e((Throwable)evt.getSource());
            Log.sendLog();
        }
    });
}
 
Example #5
Source File: Solitaire.java    From codenameone-demos with GNU General Public License v2.0 6 votes vote down vote up
void refreshZoom(Container solitairContainer) {
    int dpi =  DPIS[currentZoom / 5];
    Preferences.set("dpi", dpi);
    Preferences.set("zoom", currentZoom);
    try {
        cards = Resources.open("/gamedata.res",dpi);
        cardImageCache.clear();
        Image cardBack = getCardImage("card_back.png");
        for(Component c : solitairContainer) {
            CardComponent crd = (CardComponent)c;
            crd.setImages(getCardImage(crd.getCard().getFileName()), cardBack);
        }
        solitairContainer.revalidate();
        solitairContainer.getParent().replace(solitairContainer.getParent().getComponentAt(0), createPlacementContainer(solitairContainer), null);
    } catch(IOException e) {
        Log.e(e);
    }        
}
 
Example #6
Source File: Login.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
public void loginSuccessful() {    
    //store the access token upon login success for future use
    Preferences.set(Login.this.getClass().getName() + "Token", getAccessToken().getToken());

    if(callbackEnabled){
        if(loginCallback != null){
            loginCallback.loginSuccessful();
        }
        while (!loginCallbacksSingleUse.isEmpty()) {
            final LoginCallback cb = loginCallbacksSingleUse.remove(0);
            if (!CN.isEdt()) {
                CN.callSerially(new Runnable() {
                    public void run() {
                        cb.loginSuccessful();
                    }
                });
            } else {
                cb.loginSuccessful();
            }
        }
        return;
    }
    callbackEnabled = true;
    validateErr = null;
}
 
Example #7
Source File: GoogleLoginSample.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
public void showContactsForm(UserData data) {
    Form f = new Form("Contact Info");
    f.setToolbar(new Toolbar());
    f.getToolbar().setTitle("Contact Info");
    Form prev = CN.getCurrentForm();
    if (prev != null) {
        f.getToolbar().setBackCommand(new Command("Back") {
            public void actionPerformed(ActionEvent evt) {
                prev.show();
            }
            
        });
    }
    f.add(new Label("You are logged in as "+fullName));
    
    Button logout = new Button("Log out");
    logout.addActionListener(e->{
        GoogleConnect.getInstance().doLogout();
        Preferences.set(tokenPrefix + "tokenExpires", -1);
        Preferences.set(tokenPrefix + "token", (String)null);
        showLoginForm();
    });
    f.add(logout);
    f.show();
    
    
}
 
Example #8
Source File: GoogleLoginSample.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
public void init(Object context) {
    //Display.getInstance().setProperty("javascript.google.clientId", CLIENT_ID);
    GoogleConnect.getInstance().setClientId(CLIENT_ID);
    //GoogleConnect.getInstance().setClientSecret(CLIENT_SECRET);
    
    fullName = Preferences.get("fullName", null);
    uniqueId = Preferences.get("uniqueId", null);
    imageURL = Preferences.get("imageURL", null);
    
    //Display.getInstance().setProperty("javascript.google.clientSecret", CLIENT_SECRET);
    // use two network threads instead of one
    updateNetworkThreadCount(2);

    theme = UIManager.initFirstTheme("/theme");

    // Enable Toolbar on all Forms by default
    Toolbar.setGlobalToolbar(true);

    // Pro only feature
    Log.bindCrashProtection(true);

    addNetworkErrorListener(err -> {
        // prevent the event from propagating
        err.consume();
        if(err.getError() != null) {
            Log.e(err.getError());
        }
        Log.sendLogAsync();
        Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
    });        
}
 
Example #9
Source File: DefaultCrashReporter.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void exception(Throwable t) {
    Preferences.set("$CN1_pendingCrash", true);
    if(promptUser) {
        Dialog error = new Dialog("Error");
        error.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        TextArea txt = new TextArea(errorText);
        txt.setEditable(false);
        txt.setUIID("DialogBody");
        error.addComponent(txt);
        CheckBox cb = new CheckBox(checkboxText);
        cb.setUIID("DialogBody");
        error.addComponent(cb);
        Container grid = new Container(new GridLayout(1, 2));
        error.addComponent(grid);
        Command ok = new Command(sendButtonText);
        Command dont = new Command(dontSendButtonText);
        Button send = new Button(ok);
        Button dontSend = new Button(dont);
        grid.addComponent(send);
        grid.addComponent(dontSend);
        Command result = error.showPacked(BorderLayout.CENTER, true);
        if(result == dont) {
            if(cb.isSelected()) {
                Preferences.set("$CN1_crashBlocked", true);
            }
            Preferences.set("$CN1_pendingCrash", false);
            return;
        } else {
            if(cb.isSelected()) {
                Preferences.set("$CN1_prompt", false);
            }
        }
    }
    Log.sendLog();
    Preferences.set("$CN1_pendingCrash", false);
}
 
Example #10
Source File: CloudPersona.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Logs out the current user, notice that with an anonymous user this will effectively KILL all
 * the data in the cloud!
 */
public void logout() {
    if(Preferences.get("CN1PersonaAnonymous", false)) {
        throw new RuntimeException("Anonymous personas can't be logged out!");
    }
    Preferences.delete("CN1Persona");
}
 
Example #11
Source File: CloudPersona.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates an anonymous persona that will be unique in the cloud, NEVER logout an anonymous user!
 * @return false in case login failed e.g. due to bad network connection
 */
public static boolean createAnonymous() {
    if(instance == null) {
        getCurrentPersona();
    }
    ConnectionRequest login = new ConnectionRequest();
    login.setPost(true);
    login.setUrl(CloudStorage.SERVER_URL + "/objStoreUser");
    login.addArgument("pk", Display.getInstance().getProperty("package_name", null));
    login.addArgument("bb", Display.getInstance().getProperty("built_by_user", null));
    NetworkManager.getInstance().addToQueueAndWait(login);
    if(login.getResposeCode() != 200) {
        return false;
    }
    
    ByteArrayInputStream bi = new ByteArrayInputStream(login.getResponseData());
    DataInputStream di = new DataInputStream(bi);
    
    if(instance == null) {
        instance = new CloudPersona();
    } 
    try {
        instance.persona = di.readUTF();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    Preferences.set("CN1Persona", instance.persona);
    Preferences.set("CN1PersonaAnonymous", true);
    
    Util.cleanup(di);
    
    return true;
}
 
Example #12
Source File: CloudPersona.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initializes the persona based on a token, since this method assumes binary transfer of a completed
 * token the token isn't verified in any way and the user is considered logged in.
 * @param token the token
 */
public static void createFromToken(String token) {
    if(instance == null) {
        instance = new CloudPersona();
    } 
    instance.persona = token;
    Preferences.set("CN1Persona", token);
}
 
Example #13
Source File: CloudPersona.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This method returns the currently logged in persona or a blank persona
 * (token would be null)
 * 
 * @return the current persona
 */
public static CloudPersona getCurrentPersona() {
    if(instance == null) {
        instance = new CloudPersona();
        instance.persona = Preferences.get("CN1Persona", null);
    }
    return instance;
    
}
 
Example #14
Source File: PreferencesObject.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
private void bindChangeListener(final Property pb, final String n, final Class type) {
    pb.addChangeListener(new PropertyChangeListener() {
        public void propertyChanged(PropertyBase p) {
            if(type == String.class || type == null) {
                Preferences.set(n, (String)((Property)pb).get());
                return;
            }
            if(type == Boolean.class) {
                Preferences.set(n, (Boolean)((Property)pb).get());
                return;
            }
            if(type == Double.class) {
                Preferences.set(n, (Double)((Property)pb).get());
                return;
            }
            if(type == Float.class) {
                Preferences.set(n, (Float)((Property)pb).get());
                return;
            }
            if(type == Integer.class) {
                Preferences.set(n, (Integer)((Property)pb).get());
                return;
            }
            if(type == Long.class) {
                Preferences.set(n, (Long)((Property)pb).get());
            }
        }
    });
}
 
Example #15
Source File: Login.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This method tries to validate the last access token if exists, if the 
 * last token is not valid anymore it will try to login the user in order to
 * get a fresh token
 * The method blocks until a valid token has been granted
 */ 
public void validateToken() throws IOException{
    
    String token = Preferences.get(Login.this.getClass().getName() + "Token", null);
    if(token == null || !validateToken(token)){
        AccessToken accessTok = getAccessToken();
        if (accessTok != null && accessTok.getRefreshToken() != null){
            String refreshTok = accessTok.getRefreshToken();
            RefreshTokenRequest refreshReq = createOauth2().refreshToken(refreshTok);
            try {
                System.out.println("Attempting to refresh the access token");
                AccessToken newTok = refreshReq.get(5000);
                setAccessToken(newTok);
                Preferences.set(Login.this.getClass().getName() + "Token", getAccessToken().getToken());
                return;
            } catch (Throwable t) {}
        }
        
        // At this point We'll need to attempt to login again.
        callbackEnabled = false;
        doLogin();            
        Display.getInstance().invokeAndBlock(new Runnable() {

            public void run() {
                while(!callbackEnabled){
                    Util.sleep(100);
                }
            }
        });
        if(validateErr != null){
            throw new IOException(validateErr);
        }
    }
}
 
Example #16
Source File: Login.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Logs out the current user
 */
public void doLogout(){
    if (isNativeLoginSupported()) {
        nativeLogout();
    } else {
        setAccessToken(null);
    }    
    Preferences.delete(Login.this.getClass().getName() + "Token");
}
 
Example #17
Source File: Push.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the push device key if the device was previously successfully registered for push
 * otherwise returns null
 * @return the device key that can be used to push to this specific device.
 */    
public static String getPushKey() {
    String key = Preferences.get("push_key", null);
    if(key != null) {
        if(!key.startsWith("cn1-")) {
            String pushPrefix = Display.getInstance().getProperty("cn1_push_prefix", null);
            if(pushPrefix != null) {
                return "cn1-" + pushPrefix + "-" + key;
            }
        } else {
            return key;
        }
    }
    return null;
}
 
Example #18
Source File: Push.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the push device key if the device was previously successfully registered for push
 * otherwise returns null
 * @return the device key that can be used to push to this specific device.
 * @deprecated this method sends a push using the old push servers which will be retired, you need to switch
 * to getPushKey()
 */
public static String getDeviceKey() {
    long l = Preferences.get("push_id", (long)-1);
    if(l == -1) {
        return null;
    }
    return "" + l;
}
 
Example #19
Source File: PushSimulator.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
private void registerForPushActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_registerForPushActionPerformed
    String k = Preferences.get("push_key", null);
    if(k == null || !k.startsWith("cn1")) {
        k = "cn1-simulator-" + UUID.randomUUID().toString();
        Preferences.set("push_key", k);
    }
    Executor.registerForPush(k);
}
 
Example #20
Source File: ToggleCommand.java    From codenameone-demos with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final void actionPerformed(ActionEvent evt) {
    state = !state;
    Preferences.set(persistenceKey, state);
    if(state) {
        setIcon(checked);
    } else {
        setIcon(unchecked);
    }
    onToggle(state);
}
 
Example #21
Source File: ToggleCommand.java    From codenameone-demos with GNU General Public License v2.0 5 votes vote down vote up
public ToggleCommand(String name, boolean defaultState, String persistenceKey) {
    super(name);
    this.persistenceKey = persistenceKey;
    Style style = UIManager.getInstance().getComponentStyle("LabelIcon");
    unchecked = FontImage.create("\ue911", style);
    checked = FontImage.create("\ue912", style);
    state = Preferences.get(persistenceKey, defaultState);
    if(state) {
        setIcon(checked);
    } else {
        setIcon(unchecked);
    }
}
 
Example #22
Source File: PhotoShare.java    From codenameone-demos with GNU General Public License v2.0 5 votes vote down vote up
ActionListener createLikeAction(final long imageId) {
    return new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                try {
                    WebServiceProxy.likePhoto(imageId, Preferences.get("key", ""));
                } catch(IOException err) {
                    err.printStackTrace();
                }
            }
        };
}
 
Example #23
Source File: PhotoShare.java    From codenameone-demos with GNU General Public License v2.0 5 votes vote down vote up
public void start() {
    if(current != null){
        current.show();
        return;
    }
    
    if(Preferences.get("loggedIn", false)) {
        showMainForm();
        return;
    }
    showLoginForm();
}
 
Example #24
Source File: SocialChat.java    From codenameone-demos with GNU General Public License v2.0 5 votes vote down vote up
public void init(Object context) {
    theme = UIManager.initFirstTheme("/theme");
    
    Style iconFontStyle = UIManager.getInstance().getComponentStyle("LargeIconFont");
    FontImage fnt = FontImage.create(" \ue80f ", iconFontStyle);
    userPlaceholder = fnt.toEncodedImage();
    mask = theme.getImage("rounded-mask.png");
    roundPlaceholder = EncodedImage.createFromImage(userPlaceholder.scaled(mask.getWidth(), mask.getHeight()).applyMask(mask.createMask()), false);
    fullName = Preferences.get("fullName", null);
    uniqueId = Preferences.get("uniqueId", null);
    imageURL = Preferences.get("imageURL", null);
    
    if(Storage.getInstance().exists("recentContacts")) {
        recentContacts = (java.util.List<String>)Storage.getInstance().readObject("recentContacts");
    }
    
    Util.register("Message", Message.class);

    Display.getInstance().addEdtErrorHandler((evt) -> {
            evt.consume();
            Log.p("Exception in AppName version " + Display.getInstance().getProperty("AppVersion", "Unknown"));
            Log.p("OS " + Display.getInstance().getPlatformName());
            Log.p("Error " + evt.getSource());
            Log.p("Current Form " + Display.getInstance().getCurrent().getName());
            Log.e((Throwable)evt.getSource());
            Log.sendLog();
        });
}
 
Example #25
Source File: PreferencesObject.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Binds the object so it's seamlessly stored in preferences 
 * @return this to enable builder pattern binding
 */
public PreferencesObject bind() {
    for(PropertyBase pb : bo.getPropertyIndex()) {
        String name = (String)pb.getClientProperty("cn1-po-name");
        if(name == null) {
            name = pb.getName();
        }
        Class type = pb.getGenericType();
        String n = prefix + name;
        if(type == String.class || type == null) {
            ((Property)pb).set(Preferences.getAndSet(n, (String)((Property)pb).get()));
            bindChangeListener((Property)pb, n, type);
            continue;
        }
        Object obj = ((Property)pb).get();
        if(type == Boolean.class) {
            ((Property)pb).set(Preferences.getAndSet(n, obj == null ? false : (Boolean)obj));
            bindChangeListener((Property)pb, n, type);
            continue;
        }
        if(type == Double.class) {
            ((Property)pb).set(Preferences.getAndSet(n, obj == null ? 0.0 : (Double)obj));
            bindChangeListener((Property)pb, n, type);
            continue;
        }
        if(type == Float.class) {
            ((Property)pb).set(Preferences.getAndSet(n, obj == null ? 0.0f : (Float)obj));
            bindChangeListener((Property)pb, n, type);
            continue;
        }
        if(type == Integer.class) {
            ((Property)pb).set(Preferences.getAndSet(n, obj == null ? 0 : (Integer)obj));
            bindChangeListener((Property)pb, n, type);
            continue;
        }
        if(type == Long.class) {
            ((Property)pb).set(Preferences.getAndSet(n, obj == null ? (long)0 : (Long)obj));
            bindChangeListener((Property)pb, n, type);
            continue;
        }
        throw new IllegalStateException("Unsupported property type in preferences: " + type.getName());
    }
    bound = true;
    return this;
}
 
Example #26
Source File: CloudPersona.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a new user if a user isn't occupying the given login already, 
 * if the user exists performs a login operation.
 * 
 * @param login a user name
 * @param password a password
 * @return true if the login is successful false otherwise
 */
public static boolean createOrLogin(String login, String password) {
    if(instance == null) {
        getCurrentPersona();
        if(instance.persona != null) {
            return true;
        }
    }
    ConnectionRequest loginRequest = new ConnectionRequest();
    loginRequest.setPost(true);
    loginRequest.setUrl(CloudStorage.SERVER_URL + "/objStoreUser");
    loginRequest.addArgument("l", login);
    loginRequest.addArgument("p", password);
    loginRequest.addArgument("pk", Display.getInstance().getProperty("package_name", null));
    loginRequest.addArgument("bb", Display.getInstance().getProperty("built_by_user", null));
    NetworkManager.getInstance().addToQueueAndWait(loginRequest);
    if(loginRequest.getResposeCode() != 200) {
        return false;
    }
    
    ByteArrayInputStream bi = new ByteArrayInputStream(loginRequest.getResponseData());
    DataInputStream di = new DataInputStream(bi);
    
    try {
        if(di.readBoolean()) {
            if(instance == null) {
                instance = new CloudPersona();
            } 
            instance.persona = di.readUTF();
            Preferences.set("CN1Persona", instance.persona);
            Util.cleanup(di);
        } else {
            Util.cleanup(di);
            return false;
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return true;
}
 
Example #27
Source File: SolitaireLayout.java    From codenameone-demos with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void layoutContainer(Container parent) {
    int componentCount = parent.getComponentCount();
    if (componentCount < 1) {
        return;
    }
    int tableaDepthIncrement = Display.getInstance().convertToPixels(2, false);
    for (int iter = 0; iter < TABLEAU_DEPTH.length; iter++) {
        TABLEAU_DEPTH[iter] = 0;
    }
    // we assume all components are exactly the same size (cards)
    Component cmp = parent.getComponentAt(0);
    Style stl = cmp.getStyle();
    int cmpWidth = cmp.getPreferredW() + stl.getMargin(Component.LEFT) + stl.getMargin(Component.RIGHT);
    int cmpHeight = cmp.getPreferredH() + stl.getMargin(Component.TOP) + stl.getMargin(Component.BOTTOM);
    int width = parent.getLayoutWidth() - parent.getSideGap() - parent.getStyle().getPadding(false, Component.RIGHT) - parent.getStyle().getPadding(false, Component.LEFT);
    int height = parent.getLayoutHeight() - parent.getBottomGap() - parent.getStyle().getPadding(false, Component.BOTTOM) - parent.getStyle().getPadding(false, Component.TOP);
    int x = parent.getStyle().getPadding(parent.isRTL(), Component.LEFT);
    int y = parent.getStyle().getPadding(false, Component.TOP);
    int deck1X = x;
    
    int tableauWidth = width / 7;
    int deck2X = deck1X + tableauWidth;

    boolean draw3 = Preferences.get("3cards", false);
    FOUNDATION_POSITIONS_X[3] = x + width - tableauWidth;
    FOUNDATION_POSITIONS_X[2] = FOUNDATION_POSITIONS_X[3] - tableauWidth;
    FOUNDATION_POSITIONS_X[1] = FOUNDATION_POSITIONS_X[2] - tableauWidth;
    FOUNDATION_POSITIONS_X[0] = FOUNDATION_POSITIONS_X[1] - tableauWidth;
    
    // place the tableau a bit below the top cards but not at the complete bottom.
    int tableauY = y + cmpHeight;
    for (Component currentCmp : parent) {
        Constraint cons = (Constraint) getComponentConstraint(currentCmp);
        if (cons != null) {
            currentCmp.setWidth(cmpWidth);
            currentCmp.setHeight(cmpHeight);
            switch (cons.pos) {
                case DECK:
                    currentCmp.setY(y);
                    if (cons.offset == 0) {
                        currentCmp.setX(deck1X);
                    } else {
                        currentCmp.setX(deck2X);
                    }
                    break;
                case FOUNDATION:
                    currentCmp.setY(y);
                    currentCmp.setX(FOUNDATION_POSITIONS_X[cons.offset]);
                    break;
                case TABLEAU:
                    currentCmp.setY(tableauY + TABLEAU_DEPTH[cons.offset]);
                    TABLEAU_DEPTH[cons.offset] += tableaDepthIncrement;
                    currentCmp.setX(cons.offset * tableauWidth);
                    
                    // special case for the drop targets for the foundation, we want them to stretch all the way down...
                    if(!(currentCmp instanceof CardComponent)) {
                        currentCmp.setHeight(height - currentCmp.getY());
                    }
                    break;
            }
        } 
    }
    
    // shift right the top 2 deck card in draw 3 cards mode
    if(draw3) {
        int found = 0;
        for(int iter = parent.getComponentCount() - 1 ; iter >= 0 ; iter--) {
            Component c = parent.getComponentAt(iter);
            Constraint con = (Constraint)getComponentConstraint(c);
            if(con.pos == Position.DECK && con.offset == 1) {
                c.setX(c.getX() + Display.getInstance().convertToPixels((2 - found) * 2, true));
                found++;
                if(found == 2) {
                    break;
                }
            }
        }
    }
}
 
Example #28
Source File: WebPushTest.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
void createPushForm() {
    Form f = new Form("Test Push", new BorderLayout());
    TextField serverUrl = new TextField("https://push.codenameone.com/push/push");
    String nexus5XEmulatorId = "cn1-fcm-c_t22hK-weg:APA91bGNa2hP9SHLBhUmLmzY1ANyjCH2ydEQz0JUFlMPFUHDAUfTQysC1r9K6I7jdk5LN6mEP5k5IWvyQX4dvubbHeY1KWQRKb-aYuXaHHHg2U3XGH1xXXa7xfJbsCf7nB0vu1aWhOg_4M4Z-znC2X5a0tpYf59QmA";
                              //APA91bHWiuoPMA4OgIr3ZyVgSjVmnh4H0BQ4jhB3hblIAZfmMs-SfRN1tb4662MudPEULjIkl8P_oTrQ14sKgowz4Q45n6iaPl1GwXb_9HbtlAQDAlnX60Eo4SamzZJkB_6kcnsEMKt_
    String iphoneId = "cn1-ios-c76b23de81f6389f37d2621f000b7f01c52e5c1d6f1f947b199a7c2d8844f713";
    
    
    TextArea targetId = new TextArea(Preferences.get("targetId", ""));
    targetId.addActionListener(e->Preferences.set("targetId", targetId.getText()));
    TextField pushType = new TextField(Preferences.get("pushType", "99"));
    pushType.addActionListener(e->Preferences.set("pushType", pushType.getText()));
    TextField payload = new TextField(Preferences.get("payload", "<push type=\"0\" body=\"Hello\" category=\"fo\"/>"));
    payload.addActionListener(e->Preferences.set("payload", payload.getText()));
    TextField gcmServerKey = new TextField(Preferences.get("gcmServerKey", ""));
    gcmServerKey.setHint("FCM_SERVER_API_KEY");
    gcmServerKey.addActionListener(e->Preferences.set("gcmServerKey", gcmServerKey.getText()));
    
    TextField tokenField = new TextField(Preferences.get("token", ""));
    tokenField.setHint("Enter your CN1 Token");
    tokenField.addActionListener(e->{
        Preferences.set("token", tokenField.getText());
    });
    
    targetId.setRows(4);
    targetId.getAllStyles().setFgColor(0x0);
    targetId.getAllStyles().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL));
    Button send = new Button("Send");
    send.addActionListener(e->{
        /*
        boolean result = new Push("E729F5CE-DCE8-4D63-B517-85112994EC66", payload.getText(), targetId.getText())
                .gcmAuth(gcmServerKey.getText())
                .apnsAuth(IOS_DEV_CERT_URL, IOS_DEV_CERT_PASS, false)
                .pushType(Integer.parseInt(pushType.getText()))
                .wnsAuth("xxxxx", "xxxxxxxx")
                .send()
                //.sendAsync()
                ;
        
        System.out.println("Push sent.  Result: "+result);
        */
        ConnectionRequest req = new ConnectionRequest();
        req.setUrl(serverUrl.getText());
        req.addArgument("token", tokenField.getText());
        req.addArgument("device", targetId.getText());
        req.addArgument("body", payload.getText());
        req.addArgument("type", pushType.getText());
        req.addArgument("auth", gcmServerKey.getText());
        req.addArgument("cert", IOS_DEV_CERT_URL);
        req.addArgument("certPassword", IOS_DEV_CERT_PASS);
        req.addArgument("sid", "ms-app://xxxxxxxxx");
        req.addArgument("client_secret", "xxxxxxxxx");
        req.setHttpMethod("POST");
        req.setPost(true);
        NetworkManager.getInstance().addToQueueAndWait(req);
        System.out.println(req.getResponseCode());
        try {
            System.out.println(new String(req.getResponseData(), "UTF-8"));
        } catch (Throwable t) {Log.e(t);}
               
        
        //new Push("E729F5CE-DCE8-4D63-B517-85112994EC66", payload.getText(), targetId.getText())
        //        .wnsAuth("ms-app://s-1-15-2-2674027049-292503787-1918612089-438606370-903203898-836476968-4131729547", "2S37cRtqCR3vQVqhfrFBA2w6PAsWwZ/m")
        //        .send();
        
    });
    
    Container center = BoxLayout.encloseY(new Label("Server URL"), serverUrl,
            new Label("Target ID"), targetId, new Label("Push Type"), pushType, new Label("Payload"), payload, new Label("GCM Server Key"), gcmServerKey, new Label("Codename One Token"), tokenField, send);
    center.setScrollableY(true);
    f.add(BorderLayout.CENTER, center);
    f.show();
    
}
 
Example #29
Source File: SocialChat.java    From codenameone-demos with GNU General Public License v2.0 4 votes vote down vote up
void doLogin(Login lg, UserData data, boolean forceLogin) {
    if(!forceLogin) {
        if(lg.isUserLoggedIn()) {
            showContactsForm(data);
            return;
        }

        // if the user already logged in previously and we have a token
        String t = Preferences.get(tokenPrefix + "token", (String)null);
        if(t != null) {
            // we check the expiration of the token which we previously stored as System time
            long tokenExpires = Preferences.get(tokenPrefix + "tokenExpires", (long)-1);
            if(tokenExpires < 0 || tokenExpires > System.currentTimeMillis()) {
                // we are still logged in
                showContactsForm(data);
                return;
            } 
        }
    }
    lg.setCallback(new LoginCallback() {
        @Override
        public void loginFailed(String errorMessage) {
            Dialog.show("Error Logging In", "There was an error logging in: " + errorMessage, "OK", null);
        }

        @Override
        public void loginSuccessful() {
            // when login is successful we fetch the full data
            data.fetchData(lg.getAccessToken().getToken(), ()-> {
                // we store the values of result into local variables
                uniqueId = data.getId();
                fullName = data.getName();
                imageURL = data.getImage();
                
                // we then store the data into local cached storage so they will be around when we run the app next time
                Preferences.set("fullName", fullName);
                Preferences.set("uniqueId", uniqueId);
                Preferences.set("imageURL", imageURL);
                Preferences.set(tokenPrefix + "token", lg.getAccessToken().getToken());
                
                // token expiration is in seconds from the current time, we convert it to a System.currentTimeMillis value so we can
                // reference it in the future to check expiration
                Preferences.set(tokenPrefix + "tokenExpires", tokenExpirationInMillis(lg.getAccessToken()));
                showContactsForm(data);
            });
        }
    });
    lg.doLogin();
}
 
Example #30
Source File: GoogleLoginSample.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
void doLogin(Login lg, UserData data, boolean forceLogin) {
    if(!forceLogin) {
        if(lg.isUserLoggedIn()) {
            showContactsForm(data);
            return;
        }

        // if the user already logged in previously and we have a token
        String t = Preferences.get(tokenPrefix + "token", (String)null);
        if(t != null) {
            // we check the expiration of the token which we previously stored as System time
            long tokenExpires = Preferences.get(tokenPrefix + "tokenExpires", (long)-1);
            if(tokenExpires < 0 || tokenExpires > System.currentTimeMillis()) {
                // we are still logged in
                showContactsForm(data);
                return;
            }
        }
    }

    lg.setCallback(new LoginCallback() {
        @Override
        public void loginFailed(String errorMessage) {
            Dialog.show("Error Logging In", "There was an error logging in: " + errorMessage, "OK", null);
        }

        @Override
        public void loginSuccessful() {
            // when login is successful we fetch the full data
            data.fetchData(lg.getAccessToken().getToken(), ()-> {
                // we store the values of result into local variables
                uniqueId = data.getId();
                fullName = data.getName();
                imageURL = data.getImage();

                // we then store the data into local cached storage so they will be around when we run the app next time
                Preferences.set("fullName", fullName);
                Preferences.set("uniqueId", uniqueId);
                Preferences.set("imageURL", imageURL);
                Preferences.set(tokenPrefix + "token", lg.getAccessToken().getToken());

                // token expiration is in seconds from the current time, we convert it to a System.currentTimeMillis value so we can
                // reference it in the future to check expiration
                Preferences.set(tokenPrefix + "tokenExpires", tokenExpirationInMillis(lg.getAccessToken()));
                showContactsForm(data);
            });
        }
    });
    lg.doLogin();
}