Java Code Examples for com.codename1.io.ConnectionRequest#setUrl()

The following examples show how to use com.codename1.io.ConnectionRequest#setUrl() . 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: ServerAccess.java    From codenameone-demos with GNU General Public License v2.0 7 votes vote down vote up
public static List getEntriesFromFlickrService(String tag) {
    
    try {
        ConnectionRequest req = new ConnectionRequest();
        req.setUrl("http://api.flickr.com/services/feeds/photos_public.gne");
        req.setPost(false);
        req.addArgument("tagmode", "any");
        req.addArgument("tags", tag);
        req.addArgument("format", "json");
        
        NetworkManager.getInstance().addToQueueAndWait(req);
        byte[] data = req.getResponseData();
        if (data == null) {
            throw new IOException("Network Err");
        }
        JSONParser parser = new JSONParser();
        Map response = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
        System.out.println("res" + response);
        List items = (List)response.get("items");
        return items;
    } catch (Exception e) {
    }
    return null;
}
 
Example 2
Source File: AutocompleteOverrideFilterSample.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
String[] searchLocations(String text) {        
    try {
        if(text.length() > 0) {
            if (currRequest != null) {
                //currRequest.kill();
                
            }
                
            ConnectionRequest r = new ConnectionRequest();
            currRequest = r;
            r.setPost(false);
            r.setUrl("https://maps.googleapis.com/maps/api/place/autocomplete/json");
            r.addArgument("key", apiKey.getText());
            r.addArgument("input", text);
            NetworkManager.getInstance().addToQueueAndWait(r);
            Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
            String[] res = Result.fromContent(result).getAsStringArray("//description");
            return res;
        }
    } catch(Exception err) {
        Log.e(err);
    }
    return null;
}
 
Example 3
Source File: AnalyticsService.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private static ConnectionRequest GetGARequest() {
    ConnectionRequest req = new ConnectionRequest();
    req.setUrl("https://www.google-analytics.com/collect");
    req.setPost(true);
    req.setFailSilently(true);
    req.addArgument("v", "1");
    req.addArgument("tid", instance.agent);
    if (timeout > 0) {
        req.setTimeout(timeout);
    }
    if (readTimeout > 0) {
        req.setReadTimeout(readTimeout);
    }
    long uniqueId = Log.getUniqueDeviceId();
    req.addArgument("cid", String.valueOf(uniqueId));
    return req;
}
 
Example 4
Source File: SignIn.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private void showFacebookUser(String token){
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setUrl("https://graph.facebook.com/v2.3/me");
    req.addArgumentNoEncoding("access_token", token);
    InfiniteProgress ip = new InfiniteProgress();
    Dialog d = ip.showInifiniteBlocking();
    NetworkManager.getInstance().addToQueueAndWait(req);
    byte[] data = req.getResponseData();
    JSONParser parser = new JSONParser();
    Map map = null;
    try {
        map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    String name = (String) map.get("name");
    d.dispose();
    Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), "https://graph.facebook.com/v2.3/me/picture?access_token=" + token);
    userForm.show();
}
 
Example 5
Source File: CloudStorage.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Deletes a file from the cloud storage
 * 
 * @param fileId the file id to delete
 * @return true if the operation was successful
 * @deprecated this API is currently deprecated due to Googles cloud storage deprection
 */
public boolean deleteCloudFile(String fileId) {
    if(CloudPersona.getCurrentPersona().getToken() == null) {
        CloudPersona.createAnonymous();
    }
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setFailSilently(true);
    req.setUrl(SERVER_URL + "/fileStoreDelete");
    req.addArgument("i", fileId);
    req.addArgument("t", CloudPersona.getCurrentPersona().getToken());
    NetworkManager.getInstance().addToQueueAndWait(req);
    if(req.getResponseCode() == 200) {
        return new String(req.getResponseData()).equals("OK");
    }
    return false;
}
 
Example 6
Source File: GoogleConnect.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected boolean validateToken(String token) {
    //make a call to the API if the return value is 40X the token is not 
    //valid anymore
    final boolean[] retval = new boolean[1];
    retval[0] = true;
    ConnectionRequest req = new ConnectionRequest() {
        @Override
        protected void handleErrorResponseCode(int code, String message) {
            //access token not valid anymore
            if (code >= 400 && code <= 410) {
                retval[0] = false;
                return;
            }
            super.handleErrorResponseCode(code, message);
        }

    };
    req.setPost(false);
    req.setUrl("https://www.googleapis.com/plus/v1/people/me");
    req.addRequestHeader("Authorization", "Bearer " + token);
    NetworkManager.getInstance().addToQueueAndWait(req);
    return retval[0];

}
 
Example 7
Source File: TwitterRESTService.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Logs in to twitter as an application
 * 
 * @param consumerKey the key to login with
 * @param consumerSecret the secret to to login with
 * @return the authorization token
 */
public static String initToken(String consumerKey, String consumerSecret) {
    ConnectionRequest auth = new ConnectionRequest() {
        protected void readResponse(InputStream input) throws IOException  {
            JSONParser p = new JSONParser();
            Hashtable h = p.parse(new InputStreamReader(input));
            authToken = (String)h.get("access_token");
            if(authToken == null) {
                return;
            }
        }
    };
    auth.setPost(true);
    auth.setUrl("https://api.twitter.com/oauth2/token");
    
    // YOU MUST CHANGE THIS IF YOU BUILD YOUR OWN APP
    String encoded = Base64.encodeNoNewline((consumerKey + ":" + consumerSecret).getBytes());
    auth.addRequestHeader("Authorization", "Basic " + encoded);
    auth.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
    auth.addArgument("grant_type", "client_credentials");
    NetworkManager.getInstance().addToQueueAndWait(auth);
    return authToken;
}
 
Example 8
Source File: ParsePutCommand.java    From parse4cn1 with Apache License 2.0 5 votes vote down vote up
@Override
void setUpRequest(ConnectionRequest request) throws ParseException {
    setupDefaultHeaders();
    request.setPost(true);
    request.setHttpMethod("PUT");
    request.setUrl(getUrl(endPoint, objectId));
}
 
Example 9
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 10
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * log out the current user
 */
public static void logOut(){
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setUrl("https://www.facebook.com/logout.php?access_token="+token+"&confirm=1&next="+redirectURI);
    NetworkManager.getInstance().addToQueueAndWait(req);
    token = null;
}
 
Example 11
Source File: AddToQueueAndWaitOffEDTDeadlockTest.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean runTest() throws Exception {
    
    Thread t2 = new Thread(()-> {
        ConnectionRequest req = new ConnectionRequest();
        req.setUrl("https://www.codenameone.com");
        long start = System.currentTimeMillis();
        System.out.println("About to send request");
        NetworkManager.getInstance().addToQueueAndWait(req);
        System.out.println("Request complete");
        latency = System.currentTimeMillis()-start;
        
    });
    
    Runnable task = ()->{
        t2.start();
        synchronized(lock) {
            System.out.println("On edt sleeping");
            Util.sleep(5000);
            System.out.println("On edt finished sleeping");
        }
    };
    
    callSeriallyAndWait(task);
    t2.join();
    assertTrue(latency > 0 && latency < 4000, "Network request should return in less than 5000ms. It must be locking");
    return true;
}
 
Example 12
Source File: CloudStorage.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Deletes all the cloud files before the given time stamp for the given
 * development account. Notice that this method is meant for internal use 
 * and not for distributable apps since it includes your developer account.
 * This method works in a background server process and returns immediately.
 * @param timestamp the timestamp since epoch (as in System.currentTimemillis).
 * @param developerAccount your developer email
 * @param developerPassword your developer password
 * @deprecated this API is currently deprecated due to Googles cloud storage deprection
 */
public void deleteAllCloudFilesBefore(long timestamp, String developerAccount, String developerPassword) {
    if(CloudPersona.getCurrentPersona().getToken() == null) {
        return;
    }
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setFailSilently(true);
    req.setUrl(SERVER_URL + "/purgeCloudFiles");
    req.addArgument("d", "" + timestamp);
    req.addArgument("u", developerAccount);
    req.addArgument("p", developerPassword);
    NetworkManager.getInstance().addToQueue(req);
}
 
Example 13
Source File: StateMachine.java    From codenameone-demos with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void onMain_ImportJSONAction(final Component c, ActionEvent event) {
    ConnectionRequest cr = new ConnectionRequest() {
        protected void readResponse(InputStream is) throws IOException {
            JSONParser p = new JSONParser();
            Hashtable h = p.parse(new InputStreamReader(is));
            Hashtable<Object, Hashtable<String, String>> todoHash = (Hashtable<Object, Hashtable<String, String>>)h.get("todo");
            Container tasksContainer = findTasksContainer(c.getParent());
            for(Hashtable<String, String> values : todoHash.values()) {
                String photoURL = values.get("photoURL");
                String title = values.get("title");

                MultiButton mb = createEntry(values);
                todos.add(values);
                tasksContainer.addComponent(mb);


                if(photoURL != null) {
                    ImageDownloadService.createImageToStorage(photoURL, mb.getIconComponent(), 
                            title, new Dimension(imageWidth, imageHeight));
                }
            }
            Storage.getInstance().writeObject("todos", todos);        
            findTabs1(c.getParent()).setSelectedIndex(0);
            tasksContainer.animateLayout(500);
        }
    };
    InfiniteProgress i = new InfiniteProgress();
    Dialog blocking = i.showInifiniteBlocking();
    cr.setDisposeOnCompletion(blocking);
    cr.setPost(false);
    cr.setUrl("https://dl.dropbox.com/u/57067724/cn1/Course%20Material/webservice/NetworkingChapter.json");
    NetworkManager.getInstance().addToQueue(cr);
}
 
Example 14
Source File: MapsDemo.java    From codenameone-demos with GNU General Public License v2.0 5 votes vote down vote up
private String getDirections(Coord origin, Coord destination) throws IOException {
    ConnectionRequest req = new ConnectionRequest();
    req.setUrl("http://maps.googleapis.com/maps/api/directions/json");
    req.setUserAgent("Opera/8.0 (Windows NT 5.1; U; en)");
    req.setPost(false);
    req.addArgument("origin", "" + origin.getLatitude() + " " + origin.getLongitude());
    req.addArgument("destination", "" + destination.getLatitude() + " " + destination.getLongitude());
    req.addArgument("mode", "walking");
    req.addArgument("sensor", "false");
    NetworkManager.getInstance().addToQueueAndWait(req);
    JSONParser p = new JSONParser();
    Hashtable h = p.parse(new InputStreamReader(new ByteArrayInputStream(req.getResponseData())));
    System.out.println(h.toString());
    return ((Hashtable) ((Hashtable) ((Vector) h.get("routes")).firstElement()).get("overview_polyline")).get("points").toString();
}
 
Example 15
Source File: SocialChat.java    From codenameone-demos with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void fetchData(String token, Runnable callback) {
    this.token = token;
    ConnectionRequest req = new ConnectionRequest() {
        @Override
        protected void readResponse(InputStream input) throws IOException {
            JSONParser parser = new JSONParser();
            Map<String, Object> parsed = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
            name = (String) parsed.get("name");
            id = (String) parsed.get("id");
        }

        @Override
        protected void postResponse() {
            callback.run();
        }

        @Override
        protected void handleErrorResponseCode(int code, String message) {
            //access token not valid anymore
            if(code >= 400 && code <= 410){
                doLogin(FacebookConnect.getInstance(), FacebookData.this, true);
                return;
            }
            super.handleErrorResponseCode(code, message);
        }
    };
    req.setPost(false);
    req.setUrl("https://graph.facebook.com/v2.4/me");
    req.addArgumentNoEncoding("access_token", token);
    NetworkManager.getInstance().addToQueue(req);
}
 
Example 16
Source File: ParseUploadCommand.java    From parse4cn1 with Apache License 2.0 5 votes vote down vote up
@Override
void setUpRequest(ConnectionRequest request) throws ParseException {
    setupDefaultHeaders();
    request.setPost(true);
    request.setHttpMethod("POST");
    request.setUrl(getUrl(endPoint, null));

    if (contentType != null) {
        addHeader(ParseConstants.HEADER_CONTENT_TYPE, contentType);
    }
}
 
Example 17
Source File: ParseDownloadCommand.java    From parse4cn1 with Apache License 2.0 5 votes vote down vote up
@Override
void setUpRequest(ConnectionRequest request) throws ParseException {
    request.setPost(false);
    request.setHttpMethod("GET");
    request.setUrl(url);

    if (contentType != null) {
        request.addRequestHeader(ParseConstants.HEADER_CONTENT_TYPE, contentType);
    }
}
 
Example 18
Source File: CloudStorage.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Deletes all the cloud files under this user, notice that this method
 * is asynchronous and a background server process performs the actual deletion
 * @deprecated this API is currently deprecated due to Googles cloud storage deprection
 */
public void deleteAllCloudFilesForUser() {
    if(CloudPersona.getCurrentPersona().getToken() == null) {
        return;
    }
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setFailSilently(true);
    req.setUrl(SERVER_URL + "/purgeCloudFiles");
    req.addArgument("own", CloudPersona.getCurrentPersona().getToken());
    req.addArgument("u", Display.getInstance().getProperty("built_by_user", ""));
    NetworkManager.getInstance().addToQueue(req);
}
 
Example 19
Source File: ParsePostCommand.java    From parse4cn1 with Apache License 2.0 5 votes vote down vote up
@Override
void setUpRequest(ConnectionRequest request) throws ParseException {
    setupDefaultHeaders();
    request.setPost(true);
    request.setHttpMethod("POST");
    request.setUrl(getUrl(endPoint, objectId));
}
 
Example 20
Source File: VServAds.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected Component getPendingAd() {
    if(imageURL == null) {
        return null;
    }
    if(renderNotify != null && renderNotify.length() > 0) {
        ConnectionRequest c = new ConnectionRequest();
        c.setFailSilently(true);
        c.setUrl(renderNotify);
        c.setPost(false);
        NetworkManager.getInstance().addToQueue(c);
    }
    if("image".equalsIgnoreCase(contentType)) {
        Button adComponent = new Button(){

            public void setIcon(Image icon) {
                if(icon != null && isScaleMode()){
                    icon = icon.scaledWidth(Display.getInstance().getDisplayWidth());
                }
                super.setIcon(icon);
            }
            
        };
        adComponent.setUIID("Container");
        adComponent.getStyle().setBgColor(backgroundColor);
        adComponent.getStyle().setOpacity(0xff);
        ImageDownloadService imd = new ImageDownloadService(imageURL, adComponent);
        NetworkManager.getInstance().addToQueueAndWait(imd);
        /*adComponent.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                Display.getInstance().execute(getAdDestination());
            }
        });*/
        return adComponent;
    } else {
        WebBrowser wb = new WebBrowser();
        if(wb.getInternal() instanceof BrowserComponent) {
            BrowserComponent bc = (BrowserComponent)wb.getInternal();
            bc.setBrowserNavigationCallback(new BrowserNavigationCallback() {
                public boolean shouldNavigate(final String url) {
                    unlock(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            Display.getInstance().execute(url);
                        }
                    });
                    return false;
                }
            });
        }
        wb.setURL(imageURL);
        return wb;
    }
}