com.codename1.io.ConnectionRequest Java Examples

The following examples show how to use com.codename1.io.ConnectionRequest. 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: 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 #3
Source File: ReactDemo.java    From codenameone-demos with GNU General Public License v2.0 6 votes vote down vote up
public void start() {
    if(current != null){
        current.show();
        return;
    }
    placeholder = EncodedImage.createFromImage(Image.createImage(53, 81, 0), false);
    Form react = new Form("React Demo", new BorderLayout());
    react.add(BorderLayout.CENTER, new InfiniteContainer() {
        public Component[] fetchComponents(int index, int amount) {
            try {
                Collection data = (Collection)ConnectionRequest.fetchJSON(REQUEST_URL).get("movies");
                Component[] response = new Component[data.size()];
                int offset = 0;
                for(Object movie : data) {
                    response[offset] = createMovieEntry(Result.fromContent((Map)movie));
                    offset++;
                }
                return response;
            } catch(IOException err) {
                Dialog.show("Error", "Error during connection: " + err, "OK", null);
            }
            return null;
        }
    });
    react.show();
}
 
Example #4
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes the request synchronously
 * 
 * @param type the type of the business object to create
 * @return Response Object
 */ 
public Response<List<PropertyBusinessObject>> getAsPropertyList(Class type) {
    ConnectionRequest request = createRequest(true);
    fetched = true;
    CN.addToQueueAndWait(request);
    Map response = ((Connection)request).json;
    try {
        List<Map> lst = (List<Map>)response.get("root");
        List<PropertyBusinessObject> result = new ArrayList<PropertyBusinessObject>();
        for(Map m : lst) {
            PropertyBusinessObject pb = (PropertyBusinessObject)type.newInstance();
            pb.getPropertyIndex().populateFromMap(m);
            result.add(pb);
        }
        return new Response(request.getResponseCode(), result, request.getResponseErrorMessage());
    } catch(Exception err) {
        Log.e(err);
        throw new RuntimeException(err.toString());
    }
}
 
Example #5
Source File: Progress.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Binds the progress UI to the completion of this request
 *
 * @param title the title of the progress dialog
 * @param request the network request pending
 * @param showPercentage shows percentage on the progress bar
 */
public Progress(String title, ConnectionRequest request, boolean showPercentage) {
    super(title);
    this.request = request;
    SliderBridge b = new SliderBridge(request);
    b.setRenderPercentageOnTop(showPercentage);
    b.setRenderValueOnTop(true);
    setLayout(new BoxLayout(BoxLayout.Y_AXIS));
    addComponent(b);
    Command cancel = new Command(UIManager.getInstance().localize("cancel", "Cancel"));
    if(Display.getInstance().isTouchScreenDevice() || getSoftButtonCount() < 2) {
        // if this is a touch screen device or a blackberry use a centered button
        Button btn = new Button(cancel);
        Container cnt = new Container(new FlowLayout(CENTER));
        cnt.addComponent(btn);
        addComponent(cnt);
    } else {
        // otherwise use a command
        addCommand(cancel);
    }
    setDisposeWhenPointerOutOfBounds(false);
    setAutoDispose(false);
    NetworkManager.getInstance().addProgressListener(this);
}
 
Example #6
Source File: Ads.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * HTML ad received from the server
 * @param ad the ad to set
 */
public void setAd(String ad) {
    HTMLComponent html = new HTMLComponent(new AsyncDocumentRequestHandlerImpl() {

        protected ConnectionRequest createConnectionRequest(DocumentInfo docInfo, IOCallback callback, Object[] response) {
            ConnectionRequest req = super.createConnectionRequest(docInfo, callback, response);
            req.setFailSilently(true);
            req.addResponseCodeListener(new ActionListener() {

                public void actionPerformed(ActionEvent evt) {
                    //do nothing, just make sure the html won't throw an error
                }
            });
            return req;
        }
    });
    html.setSupressExceptions(true);
    html.setHTMLCallback(this);
    html.setBodyText("<html><body><div align='center'>" + ad + "</div></body></html>");
    replace(getComponentAt(0), html, null);
    revalidate();
    html.setPageUIID("Container");
    html.getStyle().setBgTransparency(0);
}
 
Example #7
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 #8
Source File: SignIn.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private void showGoogleUser(String token){
    ConnectionRequest req = new ConnectionRequest();
    req.addRequestHeader("Authorization", "Bearer " + token);
    req.setUrl("https://www.googleapis.com/plus/v1/people/me");
    req.setPost(false);
    InfiniteProgress ip = new InfiniteProgress();
    Dialog d = ip.showInifiniteBlocking();
    NetworkManager.getInstance().addToQueueAndWait(req);
    d.dispose();
    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("displayName");
    Map im = (Map) map.get("image");
    String url = (String) im.get("url");
    Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), url);
    userForm.show();
}
 
Example #9
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 #10
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes the request asynchronously and writes the response to the provided
 * Callback
 * @param callback writes the response to this callback
 * @param onError the error callback
 * @return returns the Connection Request object so it can be killed if necessary
 * @deprecated use {@link #fetchAsJsonMap(com.codename1.util.OnComplete)} instead
 */ 
public ConnectionRequest getAsJsonMap(final SuccessCallback<Response<Map>> callback, final FailureCallback<? extends Object> onError) {
    final Connection request = createRequest(true);
    request.addResponseListener(new ActionListener<NetworkEvent>() {
        @Override
        public void actionPerformed(NetworkEvent evt) {
            if(request.errorCode) {
                return;
            }
            if(onError != null) {
                // this is an error response code and should be handled as an error
                if(evt.getResponseCode() > 310) {
                    return;
                }
            }
            Response res = null;
            Map response = (Map)evt.getMetaData();
            res = new Response(evt.getResponseCode(), response, evt.getMessage());
            callback.onSucess(res);
        }
    });
    bindOnError(request, onError);
    fetched = true;
    CN.addToQueue(request);       
    return request;
}
 
Example #11
Source File: SignIn.java    From codenameone-demos 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 #12
Source File: SignIn.java    From codenameone-demos with GNU General Public License v2.0 6 votes vote down vote up
private void showGoogleUser(String token){
    ConnectionRequest req = new ConnectionRequest();
    req.addRequestHeader("Authorization", "Bearer " + token);
    req.setUrl("https://www.googleapis.com/plus/v1/people/me");
    req.setPost(false);
    InfiniteProgress ip = new InfiniteProgress();
    Dialog d = ip.showInifiniteBlocking();
    NetworkManager.getInstance().addToQueueAndWait(req);
    d.dispose();
    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("displayName");
    Map im = (Map) map.get("image");
    String url = (String) im.get("url");
    Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), url);
    userForm.show();
}
 
Example #13
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private ConnectionRequest getAsBytesAsyncImpl(final Object callback) {
    final Connection request = createRequest(false);
    request.addResponseListener(new ActionListener<NetworkEvent>() {
        @Override
        public void actionPerformed(NetworkEvent evt) {
            if(request.errorCode) {
                return;
            }
            Response res = null;
            res = new Response(evt.getResponseCode(), evt.getConnectionRequest().getResponseData(), evt.getMessage());
            if(callback instanceof Callback) {
                ((Callback)callback).onSucess(res);
            } else {
                ((OnComplete)callback).completed(res);
            }
        }
    });
    fetched = true;
    CN.addToQueue(request);        
    return request;
}
 
Example #14
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes the request asynchronously and writes the response to the provided
 * Callback. This fetches JSON data and parses it into a properties business object
 * @param callback writes the response to this callback
 * @param type the class of the business object returned
 * @return returns the Connection Request object so it can be killed if necessary
 */ 
public ConnectionRequest fetchAsProperties(final OnComplete<Response<PropertyBusinessObject>> callback, final Class type) {
    final Connection request = createRequest(true);
    request.addResponseListener(new ActionListener<NetworkEvent>() {
        @Override
        public void actionPerformed(NetworkEvent evt) {
            if(request.errorCode) {
                return;
            }
            Response res = null;
            Map response = (Map)evt.getMetaData();
            try {
                PropertyBusinessObject pb = (PropertyBusinessObject)type.newInstance();
                pb.getPropertyIndex().populateFromMap(response);
                res = new Response(evt.getResponseCode(), pb, evt.getMessage());
                callback.completed(res);
            } catch(Exception err) {
                Log.e(err);
                throw new RuntimeException(err.toString());
            }
        }
    });
    fetched = true;
    CN.addToQueue(request);       
    return request;
}
 
Example #15
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 #16
Source File: VideoPlayerSample.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
void downloadFile(final Form parent) {
    download = new ConnectionRequest("https://www.codenameone.com/files/hello-codenameone.mp4") {
        @Override
        protected void postResponse() {
            
            if(parent != getCurrentForm()) {
                if(!Dialog.show("Download Finished", "Downloading the video completed!\nDo you want to show it now?",
                        "Show", "Later")) {
                    return;
                }
                parent.show();
            }
            playVideo(parent, getAppHomePath() + "hello-codenameone.mp4");
        }
    };
    download.setPost(false);
    download.setDestinationFile(getAppHomePath() + "hello-codenameone.mp4");
    ToastBar.showConnectionProgress("Downloading video", download, null, null);
    addToQueue(download);        
}
 
Example #17
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the picture of the given facebook object id and stores it in the given List in the offset index
 * 
 * This assumes the GenericListCellRenderer style of
 * list which relies on a hashtable based model approach.
 * 
 * @param id the object id to query
 * @param targetList the list that should be updated when the data arrives
 * @param targetOffset the offset within the list to insert the image
 * @param targetKey the key for the hashtable in the target offset
 * @param toScale the scale of the image to put in the List or null
 * @param tempStorage if true place the image in a temp storage
 */
public void getPicture(String id, final Component targetList, final int targetOffset, final String targetKey,
        Dimension toScale, boolean tempStorage) throws IOException {
    checkAuthentication();

    FacebookRESTService fb = new FacebookRESTService(token, id, FacebookRESTService.PICTURE, false);
    if(toScale != null){
        fb.addArgument("width", "" + toScale.getWidth());
        fb.addArgument("height", "" + toScale.getHeight());
    }else{
        fb.addArgument("type", "small");
    }
    String cacheKey = id;
    //check if this image is a temporarey resource and it is not saved
    //already has a permanent image
    if (tempStorage && !Storage.getInstance().exists(id)) {
        cacheKey = TEMP_STORAGE + id;
    }

    ImageDownloadService.createImageToStorage(fb.requestURL(), targetList, targetOffset, targetKey, cacheKey, toScale, ConnectionRequest.PRIORITY_LOW);
}
 
Example #18
Source File: FacebookConnect.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://graph.facebook.com/v2.4/me");
    req.addArgumentNoEncoding("access_token", token);
    NetworkManager.getInstance().addToQueueAndWait(req);
    return retval[0];
}
 
Example #19
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 #20
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 #21
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private ConnectionRequest getAsStringAsyncImpl(final Object callback) {
    final Connection request = createRequest(false);
    request.addResponseListener(new ActionListener<NetworkEvent>() {
        @Override
        public void actionPerformed(NetworkEvent evt) {
            if(request.errorCode) {
                return;
            }
            Response res = null;
            try {
                res = new Response(evt.getResponseCode(), new String(evt.getConnectionRequest().getResponseData(), "UTF-8"), evt.getMessage());
                if(callback instanceof Callback) {
                    ((Callback)callback).onSucess(res);
                } else {
                    ((OnComplete<Response<String>>)callback).completed(res);
                }
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
        }
    });
    fetched = true;
    CN.addToQueue(request);        
    return request;
}
 
Example #22
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes the request synchronously
 * 
 * @return Response Object
 */ 
public Response<String> getAsString() {
    ConnectionRequest request = createRequest(false);
    fetched = true;
    CN.addToQueueAndWait(request);
    Response res = null;
    try {
        byte[] respData = request.getResponseData();
        String resp = null;
        if(respData != null) {
            resp = new String(respData, "UTF-8");
        }
        res = new Response(request.getResponseCode(), resp, 
            request.getResponseErrorMessage());
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }
    return res;
}
 
Example #23
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes the request asynchronously and writes the response to the provided
 * Callback
 * @param callback writes the response to this callback
 * @return returns the Connection Request object so it can be killed if necessary
 */ 
public ConnectionRequest fetchAsJsonMap(final OnComplete<Response<Map>> callback) {
    final Connection request = createRequest(true);
    request.addResponseListener(new ActionListener<NetworkEvent>() {
        @Override
        public void actionPerformed(NetworkEvent evt) {
            if(request.errorCode) {
                return;
            }
            Response res = null;
            Map response = (Map)evt.getMetaData();
            res = new Response(evt.getResponseCode(), response, evt.getMessage());
            callback.completed(res);
        }
    });
    fetched = true;
    CN.addToQueue(request);       
    return request;
}
 
Example #24
Source File: FullScreenAdService.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Invoked on application startup, this code will download an ad or timeout 
 */
public void showWelcomeAd() {
    if(!UIManager.getInstance().wasThemeInstalled()) {
        if(Display.getInstance().hasNativeTheme()) {
            Display.getInstance().installNativeTheme();
        }
    }
    ConnectionRequest r = createAdRequest();
    r.setPriority(ConnectionRequest.PRIORITY_HIGH);
    r.setTimeout(timeout);
    InfiniteProgress ip = new InfiniteProgress();
    Dialog ipDialog = ip.showInifiniteBlocking();
    NetworkManager.getInstance().addToQueueAndWait(r);
    if(failed()) {
        ipDialog.dispose();
        if(!allowWithoutNetwork) {
            ipDialog.dispose();
            Dialog.show("Network Error", "Please try again later", "Exit", null);
            Display.getInstance().exitApplication();
        } else {
            return;
        }
    }
    Component c = getPendingAd();
    if(c != null) {
        Form adForm = new AdForm(c);
        adForm.setTransitionInAnimator(CommonTransitions.createEmpty());
        adForm.setTransitionOutAnimator(CommonTransitions.createEmpty());
        adForm.show();
    }
}
 
Example #25
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 #26
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 #27
Source File: ParseGetCommand.java    From parse4cn1 with Apache License 2.0 5 votes vote down vote up
@Override
void setUpRequest(ConnectionRequest request) throws ParseException {
    setupDefaultHeaders();
    request.setPost(false);
    request.setHttpMethod("GET");
    request.setUrl(getUrl(endPoint, objectId));
}
 
Example #28
Source File: AsyncDocumentRequestHandlerImpl.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
protected ConnectionRequest createConnectionRequest(final DocumentInfo docInfo,
        final IOCallback callback, final Object[] response){
    return new ConnectionRequest() {

        protected void buildRequestBody(OutputStream os) throws IOException {
            if(isPost()) {
                if(docInfo.getParams() != null){
                    OutputStreamWriter w = new OutputStreamWriter(os, docInfo.getEncoding());
                    w.write(docInfo.getParams());
                }
            }
        }

        protected void handleIOException(IOException err) {
            if(callback == null) {
                response[0] = err;
            }
            super.handleIOException(err);
        }

        protected boolean shouldAutoCloseResponse() {
            return callback != null;
        }

        protected void readResponse(InputStream input) throws IOException  {
            if(callback != null) {
                callback.streamReady(input, docInfo);
            } else {
                response[0] = input;
                synchronized(LOCK) {
                    LOCK.notify();
                }
            }
        }

    };

}
 
Example #29
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Executes the request synchronously
 * 
 * @return Response Object
 */ 
public Response<Map> getAsJsonMap() {
    ConnectionRequest request = createRequest(true);
    fetched = true;
    CN.addToQueueAndWait(request);
    Map response = ((Connection)request).json;
    return new Response(request.getResponseCode(), response, request.getResponseErrorMessage());
}
 
Example #30
Source File: RSSReader.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
private void downloadImage(Hashtable h, int offset) {
    if(iconPlaceholder != null) { 
        String url = (String)h.get("thumb");
        if(url != null) {
            ImageDownloadService.createImageToStorage(url, RSSReader.this, getModel(), offset, "icon", url.replace('/', '_').replace(':', '_'), iconPlaceholder, ConnectionRequest.PRIORITY_REDUNDANT);
        }
    }
}