Search in sources :

Example 6 with CodenameOneImplementation

use of com.codename1.impl.CodenameOneImplementation in project CodenameOne by codenameone.

the class Image method createIndexed.

/**
 * Creates an indexed image with byte data this method may return a native indexed image rather than
 * an instance of the IndexedImage class
 *
 * @param width image width
 * @param height image height
 * @param palette the color palette to use with the byte data
 * @param data byte data containing palette offsets to map to ARGB colors
 * @deprecated try to avoid using indexed images explicitly
 */
public static Image createIndexed(int width, int height, int[] palette, byte[] data) {
    IndexedImage i = new IndexedImage(width, height, palette, data);
    CodenameOneImplementation impl = Display.impl;
    if (impl.isNativeIndexed()) {
        return new Image(impl.createNativeIndexed(i));
    }
    return i;
}
Also used : CodenameOneImplementation(com.codename1.impl.CodenameOneImplementation)

Example 7 with CodenameOneImplementation

use of com.codename1.impl.CodenameOneImplementation in project CodenameOne by codenameone.

the class ConnectionRequest method performOperation.

/**
 * Performs the actual network request on behalf of the network manager
 */
void performOperation() throws IOException {
    if (shouldStop()) {
        return;
    }
    if (cacheMode == CachingMode.OFFLINE) {
        InputStream is = getCachedData();
        if (is != null) {
            readResponse(is);
            Util.cleanup(is);
        } else {
            responseCode = 404;
            throw new IOException("File unavilable in cache");
        }
        return;
    }
    CodenameOneImplementation impl = Util.getImplementation();
    Object connection = null;
    input = null;
    output = null;
    redirecting = false;
    try {
        String actualUrl = createRequestURL();
        if (timeout > 0) {
            connection = impl.connect(actualUrl, isReadRequest(), isPost() || isWriteRequest(), timeout);
        } else {
            connection = impl.connect(actualUrl, isReadRequest(), isPost() || isWriteRequest());
        }
        if (shouldStop()) {
            return;
        }
        initConnection(connection);
        if (httpMethod != null) {
            impl.setHttpMethod(connection, httpMethod);
        }
        if (isCookiesEnabled()) {
            Vector v = impl.getCookiesForURL(actualUrl);
            if (v != null) {
                int c = v.size();
                if (c > 0) {
                    StringBuilder cookieStr = new StringBuilder();
                    Cookie first = (Cookie) v.elementAt(0);
                    cookieSent(first);
                    cookieStr.append(first.getName());
                    cookieStr.append("=");
                    cookieStr.append(first.getValue());
                    for (int iter = 1; iter < c; iter++) {
                        Cookie current = (Cookie) v.elementAt(iter);
                        cookieStr.append(";");
                        cookieStr.append(current.getName());
                        cookieStr.append("=");
                        cookieStr.append(current.getValue());
                        cookieSent(current);
                    }
                    impl.setHeader(connection, cookieHeader, initCookieHeader(cookieStr.toString()));
                } else {
                    String s = initCookieHeader(null);
                    if (s != null) {
                        impl.setHeader(connection, cookieHeader, s);
                    }
                }
            } else {
                String s = initCookieHeader(null);
                if (s != null) {
                    impl.setHeader(connection, cookieHeader, s);
                }
            }
        }
        if (checkSSLCertificates && canGetSSLCertificates()) {
            sslCertificates = getSSLCertificatesImpl(connection, url);
            checkSSLCertificates(sslCertificates);
            if (shouldStop()) {
                return;
            }
        }
        if (isWriteRequest()) {
            progress = NetworkEvent.PROGRESS_TYPE_OUTPUT;
            output = impl.openOutputStream(connection);
            if (shouldStop()) {
                return;
            }
            if (NetworkManager.getInstance().hasProgressListeners() && output instanceof BufferedOutputStream) {
                ((BufferedOutputStream) output).setProgressListener(this);
            }
            if (requestBody != null) {
                if (shouldWriteUTFAsGetBytes()) {
                    output.write(requestBody.getBytes("UTF-8"));
                } else {
                    OutputStreamWriter w = new OutputStreamWriter(output, "UTF-8");
                    w.write(requestBody);
                }
            } else {
                buildRequestBody(output);
            }
            if (shouldStop()) {
                return;
            }
            if (output instanceof BufferedOutputStream) {
                ((BufferedOutputStream) output).flushBuffer();
                if (shouldStop()) {
                    return;
                }
            }
        }
        timeSinceLastUpdate = System.currentTimeMillis();
        responseCode = impl.getResponseCode(connection);
        if (isCookiesEnabled()) {
            String[] cookies = impl.getHeaderFields("Set-Cookie", connection);
            if (cookies != null && cookies.length > 0) {
                ArrayList cook = new ArrayList();
                int clen = cookies.length;
                for (int iter = 0; iter < clen; iter++) {
                    Cookie coo = parseCookieHeader(cookies[iter]);
                    if (coo != null) {
                        cook.add(coo);
                        cookieReceived(coo);
                    }
                }
                impl.addCookie((Cookie[]) cook.toArray(new Cookie[cook.size()]));
            }
        }
        if (responseCode == 304 && cacheMode != CachingMode.OFF) {
            cacheUnmodified();
            return;
        }
        if (responseCode - 200 < 0 || responseCode - 200 > 100) {
            readErrorCodeHeaders(connection);
            // redirect to new location
            if (followRedirects && (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307)) {
                String uri = impl.getHeaderField("location", connection);
                if (!(uri.startsWith("http://") || uri.startsWith("https://"))) {
                    // relative URI's in the location header are illegal but some sites mistakenly use them
                    url = Util.relativeToAbsolute(url, uri);
                } else {
                    url = uri;
                }
                if (requestArguments != null && url.indexOf('?') > -1) {
                    requestArguments.clear();
                }
                if ((responseCode == 302 || responseCode == 303)) {
                    if (this.post && shouldConvertPostToGetOnRedirect()) {
                        this.post = false;
                        setWriteRequest(false);
                    }
                }
                impl.cleanup(output);
                impl.cleanup(connection);
                connection = null;
                output = null;
                if (!onRedirect(url)) {
                    redirecting = true;
                    retry();
                }
                return;
            }
            responseErrorMessge = impl.getResponseMessage(connection);
            handleErrorResponseCode(responseCode, responseErrorMessge);
            if (!isReadResponseForErrors()) {
                return;
            }
        }
        responseContentType = getHeader(connection, "Content-Type");
        if (cacheMode == CachingMode.SMART || cacheMode == CachingMode.MANUAL) {
            String last = getHeader(connection, "Last-Modified");
            String etag = getHeader(connection, "ETag");
            Preferences.set("cn1MSince" + createRequestURL(), last);
            Preferences.set("cn1Etag" + createRequestURL(), etag);
        }
        readHeaders(connection);
        contentLength = impl.getContentLength(connection);
        timeSinceLastUpdate = System.currentTimeMillis();
        progress = NetworkEvent.PROGRESS_TYPE_INPUT;
        if (isReadRequest()) {
            input = impl.openInputStream(connection);
            if (shouldStop()) {
                return;
            }
            if (input instanceof BufferedInputStream) {
                if (NetworkManager.getInstance().hasProgressListeners()) {
                    ((BufferedInputStream) input).setProgressListener(this);
                }
                ((BufferedInputStream) input).setYield(getYield());
            }
            if (!post && cacheMode == CachingMode.SMART && destinationFile == null && destinationStorage == null) {
                byte[] d = Util.readInputStream(input);
                OutputStream os = FileSystemStorage.getInstance().openOutputStream(getCacheFileName());
                os.write(d);
                os.close();
                readResponse(new ByteArrayInputStream(d));
            } else {
                readResponse(input);
            }
            if (shouldAutoCloseResponse()) {
                input.close();
            }
            input = null;
        }
    } finally {
        // always cleanup connections/streams even in case of an exception
        impl.cleanup(output);
        impl.cleanup(input);
        impl.cleanup(connection);
        timeSinceLastUpdate = -1;
        input = null;
        output = null;
        connection = null;
    }
    if (!isKilled()) {
        Display.getInstance().callSerially(new Runnable() {

            public void run() {
                postResponse();
            }
        });
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) OutputStreamWriter(java.io.OutputStreamWriter) Vector(java.util.Vector) CodenameOneImplementation(com.codename1.impl.CodenameOneImplementation)

Example 8 with CodenameOneImplementation

use of com.codename1.impl.CodenameOneImplementation in project CodenameOne by codenameone.

the class EncodedImage method getInternal.

/**
 * Returns the actual image represented by the encoded image, this image will
 * be cached in a weak/soft reference internally. This method is useful to detect
 * when the system actually created an image instance. You shouldn't invoke this
 * method manually!
 *
 * @return drawable image instance
 */
protected Image getInternal() {
    if (cache != null) {
        Image i = (Image) Display.getInstance().extractHardRef(cache);
        if (i != null) {
            return i;
        }
    }
    Image i;
    try {
        byte[] b = getImageData();
        i = Image.createImage(b, 0, b.length);
        if (opaqueChecked) {
            i.setOpaque(opaque);
        }
        CodenameOneImplementation impl = Display.impl;
        impl.setImageName(i.getImage(), getImageName());
    } catch (Exception err) {
        Log.e(err);
        i = Image.createImage(5, 5);
    }
    cache = Display.getInstance().createSoftWeakRef(i);
    return i;
}
Also used : IOException(java.io.IOException) CodenameOneImplementation(com.codename1.impl.CodenameOneImplementation)

Example 9 with CodenameOneImplementation

use of com.codename1.impl.CodenameOneImplementation in project CodenameOne by codenameone.

the class Component method laidOut.

/**
 * This is a callback method to inform the Component when it's been laidout
 * on the parent Container
 */
protected void laidOut() {
    if (!isCellRenderer()) {
        CodenameOneImplementation ci = Display.impl;
        if (ci.isEditingText()) {
            return;
        }
        Form f = getComponentForm();
        int ivk = getInvisibleAreaUnderVKB();
        if (isScrollableY() && getScrollY() > 0 && getScrollY() + getHeight() > getScrollDimension().getHeight() + ivk) {
            setScrollY(getScrollDimension().getHeight() - getHeight() + ivk);
        }
        if (isScrollableX() && getScrollX() > 0 && getScrollX() + getWidth() > getScrollDimension().getWidth()) {
            setScrollX(getScrollDimension().getWidth() - getWidth());
        }
        if (!isScrollableY() && getScrollY() > 0) {
            setScrollY(0);
        }
        if (!isScrollableX() && getScrollX() > 0) {
            setScrollX(0);
        }
        updateNativeOverlay();
    }
}
Also used : Point(com.codename1.ui.geom.Point) CodenameOneImplementation(com.codename1.impl.CodenameOneImplementation)

Example 10 with CodenameOneImplementation

use of com.codename1.impl.CodenameOneImplementation in project CodenameOne by codenameone.

the class Component method paintInternal.

final void paintInternal(Graphics g, boolean paintIntersects) {
    Display d = Display.getInstance();
    CodenameOneImplementation impl = d.getImplementation();
    if (!isVisible()) {
        return;
    }
    if (paintLockImage != null) {
        if (paintLockImage instanceof Image) {
            Image i = (Image) paintLockImage;
            g.drawImage(i, getX(), getY());
        } else {
            Image i = (Image) d.extractHardRef(paintLockImage);
            if (i == null) {
                i = Image.createImage(getWidth(), getHeight());
                int x = getX();
                int y = getY();
                setX(0);
                setY(0);
                paintInternalImpl(i.getGraphics(), paintIntersects);
                setX(x);
                setY(y);
                paintLockImage = d.createSoftWeakRef(i);
            }
            g.drawImage(i, getX(), getY());
        }
        return;
    }
    impl.beforeComponentPaint(this, g);
    paintInternalImpl(g, paintIntersects);
    impl.afterComponentPaint(this, g);
}
Also used : Point(com.codename1.ui.geom.Point) CodenameOneImplementation(com.codename1.impl.CodenameOneImplementation)

Aggregations

CodenameOneImplementation (com.codename1.impl.CodenameOneImplementation)9 Point (com.codename1.ui.geom.Point)3 IOException (java.io.IOException)2 CodenameOneThread (com.codename1.impl.CodenameOneThread)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 OutputStreamWriter (java.io.OutputStreamWriter)1 ArrayList (java.util.ArrayList)1 Enumeration (java.util.Enumeration)1 Vector (java.util.Vector)1