Java Code Examples for com.codename1.io.Preferences#set()

The following examples show how to use com.codename1.io.Preferences#set() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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;
}