Java Code Examples for com.codename1.io.Util#cleanup()

The following examples show how to use com.codename1.io.Util#cleanup() . 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: FacebookRESTService.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
protected void readResponse(InputStream input) throws IOException {
    //BufferedInputStream i = new BufferedInputStream(new InputStreamReader(input, ));
    BufferedInputStream i;
    if(input instanceof BufferedInputStream){
        i = (BufferedInputStream) input;
    }else{
        i = new BufferedInputStream(input);
    }
    i.setYield(-1);
    InputStreamReader reader = new InputStreamReader(i, "UTF-8");
    JSONParser.parse(reader, this);
    Util.cleanup(reader);
    if(stack.size() > 0){
        fireResponseListener(new NetworkEvent(this, stack.elementAt(0)));
    }
}
 
Example 2
Source File: CloudStorage.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
protected void readResponse(InputStream input) throws IOException  {
    DataInputStream di = new DataInputStream(input);

    for(int iter = 0 ; iter  < objects.length ; iter++) {
        try {
            if(di.readBoolean()) {
                objects[iter].setLastModified(di.readLong());
                objects[iter].setValues((Hashtable)Util.readObject(di));
            }
            objects[iter].setStatus(CloudObject.STATUS_COMMITTED);
        } catch (IOException ex) {
            Log.e(ex);
        }
    }

    Util.cleanup(di);

    returnValue = RETURN_CODE_SUCCESS;
}
 
Example 3
Source File: FileEncodedImage.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public byte[] getImageData() {
    if(data != null) {
        return data;
    }
    InputStream i = null;
    try {
        byte[] imageData = new byte[(int) FileSystemStorage.getInstance().getLength(fileName)];
        i = FileSystemStorage.getInstance().openInputStream(fileName);
        Util.readFully(i, imageData);
        if(keep) {
            data = imageData;
        }
        return imageData;
    } catch (IOException ex) {
        Log.e(ex);
        return null;
    } finally {
        Util.cleanup(i);
    }
}
 
Example 4
Source File: Capture.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Invokes the camera and takes a photo synchronously while blocking the EDT, the sample below
 * demonstrates a simple usage and applying a mask to the result</p>
 * <script src="https://gist.github.com/codenameone/b18c37dfcc7de752e0e6.js"></script>
 * <img src="https://www.codenameone.com/img/developer-guide/graphics-image-masking.png" alt="Picture after the capture was complete and the resulted image was rounded. The background was set to red so the rounding effect will be more noticeable" />
 * 
 * @param width the target width for the image if possible, some platforms don't support scaling. To maintain aspect ratio set to -1
 * @param height the target height for the image if possible, some platforms don't support scaling. To maintain aspect ratio set to -1
 * @return the photo file location or null if the user canceled
 */
public static String capturePhoto(int width, int height) {
    CallBack c = new CallBack();
    if("ios".equals(Display.getInstance().getPlatformName()) && (width != -1 || height != -1)) {
        // workaround for threading issues in iOS https://github.com/codenameone/CodenameOne/issues/2246
        capturePhoto(c);
        Display.getInstance().invokeAndBlock(c);
        if(c.url == null) {
            return null;
        }
        ImageIO scale = Display.getInstance().getImageIO();
        if(scale != null) {
            try {
                String path = c.url.substring(0, c.url.indexOf(".")) + "s" + c.url.substring(c.url.indexOf("."));
                OutputStream os = FileSystemStorage.getInstance().openOutputStream(path);
                scale.save(c.url, os, ImageIO.FORMAT_JPEG, width, height, 1);
                Util.cleanup(os);
                FileSystemStorage.getInstance().delete(c.url);
                return path;
            } catch (IOException ex) {
                Log.e(ex);
            }
        }
    } else {
        c.targetWidth = width;
        c.targetHeight = height;
        capturePhoto(c);
        Display.getInstance().invokeAndBlock(c);
    }
    return c.url;
}
 
Example 5
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 6
Source File: CloudStorage.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
protected void readResponse(InputStream input) throws IOException  {        
    DataInputStream di = new DataInputStream(input);
    CloudObject[] objects = null;
    try {
        int count = di.readInt();
        if(countQuery) {
            di.close();
            returnObject = new Integer(count);
            returnValue = RETURN_CODE_SUCCESS;
            return;
        }
        if(keyQuery) {
            String[] result = new String[count];
            for(int iter = 0 ; iter  < result.length ; iter++) {
                result[iter] = di.readUTF();
            }
            returnValue = RETURN_CODE_SUCCESS;
            returnObject = result;
            return;
        }

        objects = new CloudObject[count];
        for(int iter = 0 ; iter  < objects.length ; iter++) {
            objects[iter] = new CloudObject(di.readInt());
            objects[iter].setCloudId(di.readUTF());
            objects[iter].setLastModified(di.readLong());
            objects[iter].setValues((Hashtable)Util.readObject(di));
            objects[iter].setStatus(CloudObject.STATUS_COMMITTED);
        }
        returnValue = RETURN_CODE_SUCCESS;
        returnObject = objects;
    } catch (IOException ex) {
        Log.e(ex);
        returnValue = RETURN_CODE_FAIL_SERVER_ERROR;
    } finally {
        Util.cleanup(di);
    }
}
 
Example 7
Source File: EncodedImage.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Converts an image to encoded image
 * @param i image
 * @param jpeg true to try and set jpeg, will do a best effort but this isn't guaranteed
 * @return an encoded image or null
 */
public static EncodedImage createFromImage(Image i, boolean jpeg) {
    if(i instanceof EncodedImage) {
        return ((EncodedImage)i);
    }
    ImageIO io = ImageIO.getImageIO();
    if(io != null) {
        String format;
        if(jpeg) {
            if(!io.isFormatSupported(ImageIO.FORMAT_JPEG)) {
                format = ImageIO.FORMAT_PNG; 
            } else {
                format = ImageIO.FORMAT_JPEG; 
            }
        } else {
            if(!io.isFormatSupported(ImageIO.FORMAT_PNG)) {
                format = ImageIO.FORMAT_JPEG;
            } else {
                format = ImageIO.FORMAT_PNG;
            }
        }
        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            io.save(i, bo, format, 0.9f);
            EncodedImage enc = EncodedImage.create(bo.toByteArray());
            Util.cleanup(bo);
            enc.width = i.getWidth();
            enc.height = i.getHeight();
            if(format == ImageIO.FORMAT_JPEG) {
                enc.opaque = true;
                enc.opaqueChecked = true;
            }
            enc.cache = Display.getInstance().createSoftWeakRef(i);
            return enc;
        } catch(IOException err) {
            Log.e(err);
        }            
    }
    return null;
}
 
Example 8
Source File: EncodedImage.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tries to create an encoded image from RGB which is more efficient,
 * however if this fails it falls back to regular RGB image. This method
 * is slower than creating an RGB image (not to be confused with the RGBImage class which is
 * something ENTIRELY different!).
 * 
 * @param argb an argb array
 * @param width the width for the image
 * @param height the height for the image
 * @param jpeg uses jpeg format internally which is opaque and could be faster/smaller
 * @return an image which we hope is an encoded image
 */
public static Image createFromRGB(int[] argb, int width, int height, boolean jpeg) {
    Image i = Image.createImage(argb, width, height);
    ImageIO io = ImageIO.getImageIO();
    if(io != null) {
        String format;
        if(jpeg) {
            if(!io.isFormatSupported(ImageIO.FORMAT_JPEG)) {
                return i;
            }
            format = ImageIO.FORMAT_JPEG;
        } else {
            if(!io.isFormatSupported(ImageIO.FORMAT_PNG)) {
                return i;
            }
            format = ImageIO.FORMAT_PNG;
        }
        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            io.save(i, bo, format, 0.9f);
            EncodedImage enc = EncodedImage.create(bo.toByteArray());
            Util.cleanup(bo);
            enc.width = width;
            enc.height = height;
            if(jpeg) {
                enc.opaque = true;
                enc.opaqueChecked = true;
            }
            enc.cache = Display.getInstance().createSoftWeakRef(i);
            return enc;
        } catch(IOException err) {
            Log.e(err);
        }
        
    }
    return i;
}
 
Example 9
Source File: CodenameOneThread.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Prints the stack trace matching the given stack
 */
public String getStack(Throwable t) {
    try {
        StringBuffer b = new StringBuffer();
        int size;
        int[] s = (int[])exceptionStack.get(t);
        if(s == null) {
            s = stack;
            size = stackPointer;
        } else {
            size = s.length;
        }
        String[] stk = new String[size];
        
        InputStream inp = Display.getInstance().getResourceAsStream(getClass(), "/methodData.dat");
        if(inp == null) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            String str = sw.toString();
            Util.cleanup(sw);
            return str;
        }
        DataInputStream di = new DataInputStream(inp);
        int totalAmount = di.readInt();
        String lastClass = "";
        for(int x = 0 ; x < totalAmount ; x++) {
            String current = di.readUTF();
            if(current.indexOf('.') > -1) {
                lastClass = current;
            } else {
                for(int iter = 0 ; iter < size ; iter++) {
                    if(s[iter] == x + 1) {
                        stk[iter] = lastClass + "." + current;
                    }
                }
            }
        }
        for(int iter = size - 1 ; iter >= 0 ; iter--) {
            b.append("at ");
            b.append(stk[iter]);
            b.append("\n");
        }
        return b.toString();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return "Failed in stack generation for " + t;
}
 
Example 10
Source File: ShareForm.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
ShareForm(final Form contacts, String title, String toShare, String txt, String image, 
        ActionListener share) {
    setTitle(title);
    setLayout(new BorderLayout());
    this.message.setText(txt);
    post.addActionListener(share);
    if(toShare != null){
        this.to.setText(toShare);
        addComponent(BorderLayout.NORTH, to);
    }
    if(image == null){
        addComponent(BorderLayout.CENTER, message);
    }else{
        Container body = new Container(new BorderLayout());
        if(txt != null && txt.length() > 0){
            body.addComponent(BorderLayout.SOUTH, message);
        }
        Label im = new Label();
        ImageIO scale = ImageIO.getImageIO();
        if(scale != null){
            InputStream is = null;
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            try {
                is = FileSystemStorage.getInstance().openInputStream(image);
                scale.save(is, os, ImageIO.FORMAT_JPEG, 200, 200, 1);
                Image i = Image.createImage(os.toByteArray(), 0, os.toByteArray().length);
                im.setIcon(i);
            } catch (IOException ex) {
                //if failed to open the image file simply put the path as text
                im.setText(image);                   
            }finally{
                Util.cleanup(os);
                Util.cleanup(is);                                    
            }
        }else{
            im.setText(image);
        }
        body.addComponent(BorderLayout.CENTER, im);            
        addComponent(BorderLayout.CENTER, body);        
    }
    addComponent(BorderLayout.SOUTH, post);
    Command back = new Command("Back") {

        public void actionPerformed(ActionEvent evt) {
            
            contacts.showBack();
        }
    };
    addCommand(back);
    setBackCommand(back);
}
 
Example 11
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 12
Source File: ImageIO.java    From CodenameOne with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Saves an image file at the given resolution, scaling if necessary
 * 
 * @param imageFilePath the image file path
 * @param response resulting image output will be written to this stream
 * @param format the format for the image either FORMAT_PNG or FORMAT_JPEG
 * @param width the width for the resulting image, use -1 to not scale
 * @param height the height of the resulting image, use -1 to not scale
 * @param quality the quality for the resulting image output (applicable mostly for JPEG), a value between 0 and 1 notice that
 * this isn't implemented in all platforms.
 */
public void save(String imageFilePath, OutputStream response, String format, int width, int height, float quality) throws IOException{
    InputStream in = FileSystemStorage.getInstance().openInputStream(imageFilePath);
    save(in, response, format, width, height, quality); 
    Util.cleanup(in);
}