Search in sources :

Example 21 with Property

use of com.codename1.rad.models.Property in project CodenameOne by codenameone.

the class CSSTheme method load.

public static CSSTheme load(URL uri) throws IOException {
    try {
        System.setProperty("org.w3c.css.sac.parser", "org.w3c.flute.parser.Parser");
        InputSource source = new InputSource();
        InputStream stream = uri.openStream();
        String stringContents = Util.readToString(stream);
        // The flute parser chokes on properties beginning with -- so we need to replace these with cn1 prefix
        // for CSS variable support.
        stringContents = stringContents.replaceAll("([\\(\\W])(--[a-zA-Z0-9\\-]+)", "$1cn1$2");
        // Flute chokes on embedded var() functions inside an rgb or rgba function.  Hoping to support it by changing the
        // function name to cn1rgb() and cn1rgba() respectively.
        stringContents = stringContents.replaceAll("\\brgb\\(", "cn1rgb(");
        stringContents = stringContents.replaceAll("\\brgba\\(", "cn1rgba(");
        source.setCharacterStream(new CharArrayReader(stringContents.toCharArray()));
        source.setURI(uri.toString());
        source.setEncoding("UTF-8");
        ParserFactory parserFactory = new ParserFactory();
        Parser parser = parserFactory.makeParser();
        final CSSTheme theme = new CSSTheme();
        theme.baseURL = uri;
        parser.setErrorHandler(new ErrorHandler() {

            @Override
            public void warning(CSSParseException csspe) throws CSSException {
                System.out.println("CSS Warning: " + csspe.getLocalizedMessage() + " on line " + csspe.getLineNumber() + " col: " + csspe.getColumnNumber() + " of file " + csspe.getURI());
            }

            @Override
            public void error(CSSParseException csspe) throws CSSException {
                System.out.println("CSS Error: " + csspe.getLocalizedMessage() + " on line " + csspe.getLineNumber() + " col: " + csspe.getColumnNumber() + " of file " + csspe.getURI());
            }

            @Override
            public void fatalError(CSSParseException csspe) throws CSSException {
                System.out.println("CSS Fatal Error: " + csspe.getLocalizedMessage() + " on line " + csspe.getLineNumber() + " col: " + csspe.getColumnNumber() + " of file " + csspe.getURI());
            }
        });
        // parser.setLocale(Locale.getDefault());
        parser.setDocumentHandler(new DocumentHandler() {

            Map<String, LexicalUnit> variables = new LinkedHashMap<>();

            SelectorList currSelectors;

            FontFace currFontFace;

            SACMediaList currMediaList;

            // double currentTargetDpi = 320;
            // double currentMinDpi = 120;
            // double currentMaxDpi = 640;
            // int currentScreenWidth = 1280;
            // int currentScreenHeight = 1920;
            @Override
            public void startDocument(InputSource is) throws CSSException {
            // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void endDocument(InputSource is) throws CSSException {
            // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void comment(String string) throws CSSException {
            }

            @Override
            public void ignorableAtRule(String string) throws CSSException {
            // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void namespaceDeclaration(String string, String string1) throws CSSException {
            // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void importStyle(String string, SACMediaList sacml, String string1) throws CSSException {
            // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void startMedia(SACMediaList sacml) throws CSSException {
                currMediaList = sacml;
            }

            @Override
            public void endMedia(SACMediaList sacml) throws CSSException {
                currMediaList = null;
            }

            @Override
            public void startPage(String string, String string1) throws CSSException {
            // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void endPage(String string, String string1) throws CSSException {
            // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void startFontFace() throws CSSException {
                currFontFace = theme.createFontFace();
            }

            @Override
            public void endFontFace() throws CSSException {
                currFontFace = null;
            }

            @Override
            public void startSelector(SelectorList sl) throws CSSException {
                // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                currSelectors = sl;
            }

            @Override
            public void endSelector(SelectorList sl) throws CSSException {
                currSelectors = null;
            }

            @Override
            public void property(String string, LexicalUnit lu, boolean bln) throws CSSException {
                try {
                    property_(string, lu, bln);
                } catch (Throwable t) {
                    if (t instanceof CSSException) {
                        throw (CSSException) t;
                    } else {
                        System.out.println("Exception occurred while parsing property " + string + " " + lu);
                        t.printStackTrace();
                        throw new ParseException(t.getMessage());
                    }
                }
            }

            private ScaledUnit last(LexicalUnit lu) {
                while (lu.getNextLexicalUnit() != null) {
                    lu = lu.getNextLexicalUnit();
                }
                return (lu instanceof ScaledUnit) ? (ScaledUnit) lu : new ScaledUnit(lu, theme.currentDpi, theme.getPreviewScreenWidth(), theme.getPreviewScreenHeight());
            }

            /**
             * Evaluates a LexicalUnit in the current parser position.  This will expand any variables.  It will
             * continue to evaluate the next lexical unit, until it reaches the end of the current lexical unit chain.
             * @param lu The lexical unit to evaluate.
             * @return
             * @throws CSSException
             */
            private ScaledUnit evaluate(LexicalUnit lu) throws CSSException {
                if (lu.getLexicalUnitType() == LexicalUnit.SAC_FUNCTION && "var".equals(lu.getFunctionName())) {
                    LexicalUnit parameters = lu.getParameters();
                    String varname = parameters.getStringValue();
                    LexicalUnit varVal = variables.get(varname);
                    ScaledUnit su;
                    if (varVal == null && parameters.getNextLexicalUnit() != null) {
                        varVal = parameters.getNextLexicalUnit();
                        su = evaluate(new ScaledUnit(varVal, theme.currentDpi, theme.getPreviewScreenWidth(), theme.getPreviewScreenHeight()));
                    } else if (varVal == null) {
                        su = new ScaledUnit(lu, theme.currentDpi, theme.getPreviewScreenWidth(), theme.getPreviewScreenHeight());
                    } else {
                        su = evaluate(new ScaledUnit(varVal, theme.currentDpi, theme.getPreviewScreenWidth(), theme.getPreviewScreenHeight()));
                    }
                    // Evaluate the variable value in case it also includes other variables that need to be evaluated.
                    // ScaledUnit su = evaluate(new ScaledUnit(varVal, theme.currentDpi, theme.getPreviewScreenWidth(), theme.getPreviewScreenHeight()));
                    LexicalUnit toAppend = lu.getNextLexicalUnit();
                    ScaledUnit last = last(su);
                    if (toAppend != null) {
                        toAppend = evaluate(toAppend);
                        last.setNextLexicalUnit(toAppend);
                        ((ScaledUnit) toAppend).setPrevLexicalUnit(last);
                    } else {
                        last.setNextLexicalUnit(null);
                    }
                    return su;
                } else {
                    ScaledUnit su = new ScaledUnit(lu, theme.currentDpi, theme.getPreviewScreenWidth(), theme.getPreviewScreenHeight());
                    LexicalUnit nex = su.getNextLexicalUnit();
                    if (su.getParameters() != null) {
                        su.setParameters(evaluate(su.getParameters()));
                    }
                    if (nex != null) {
                        ScaledUnit snex = evaluate(nex);
                        su.setNextLexicalUnit(snex);
                        snex.setPrevLexicalUnit(su);
                    }
                    return su;
                }
            }

            private void property_(String string, LexicalUnit _lu, boolean bln) throws CSSException {
                if (string.startsWith("cn1--")) {
                    variables.put(string, _lu);
                    return;
                }
                ScaledUnit su = evaluate(_lu);
                if (currFontFace != null) {
                    switch(string) {
                        case "font-family":
                            currFontFace.fontFamily = su;
                            break;
                        case "font-style":
                            currFontFace.fontStyle = su;
                            break;
                        case "font-stretch":
                            currFontFace.fontStretch = su;
                            break;
                        case "src":
                            currFontFace.src = su;
                            break;
                        case "font-weight":
                            currFontFace.fontWeight = su;
                            break;
                    }
                } else {
                    int len = currSelectors.getLength();
                    for (int i = 0; i < len; i++) {
                        Selector sel = currSelectors.item(i);
                        if (currMediaList != null) {
                            for (String mediaPrefix : getMediaPrefixes(currMediaList)) {
                                theme.apply(mediaPrefix, sel, string, su);
                            }
                        } else {
                            theme.apply(null, sel, string, su);
                        }
                    }
                }
            }
        });
        parser.parseStyleSheet(source);
        stream.close();
        return theme;
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(CSSTheme.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(CSSTheme.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        Logger.getLogger(CSSTheme.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NullPointerException ex) {
        if (ex.getMessage().contains("encoding properties")) {
        // This error always happens and there doesn't seem to be a way to fix it... so let's just hide
        // it .  Doesn't seem to hurt anything.
        } else {
        // Logger.getLogger(CSSTheme.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (ClassCastException ex) {
        Logger.getLogger(CSSTheme.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}
Also used : InputSource(org.w3c.css.sac.InputSource) SACMediaList(org.w3c.css.sac.SACMediaList) ParserFactory(org.w3c.css.sac.helpers.ParserFactory) LinkedHashMap(java.util.LinkedHashMap) DocumentHandler(org.w3c.css.sac.DocumentHandler) CSSException(org.w3c.css.sac.CSSException) LexicalUnit(org.w3c.css.sac.LexicalUnit) ConditionalSelector(org.w3c.css.sac.ConditionalSelector) ElementSelector(org.w3c.css.sac.ElementSelector) Selector(org.w3c.css.sac.Selector) SimpleSelector(org.w3c.css.sac.SimpleSelector) ErrorHandler(org.w3c.css.sac.ErrorHandler) ObjectInputStream(java.io.ObjectInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ImageInputStream(javax.imageio.stream.ImageInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Parser(org.w3c.css.sac.Parser) JSONParser(com.codename1.io.JSONParser) CharArrayReader(java.io.CharArrayReader) CSSParseException(org.w3c.css.sac.CSSParseException) SelectorList(org.w3c.css.sac.SelectorList) CSSParseException(org.w3c.css.sac.CSSParseException) ParseException(org.w3c.flute.parser.ParseException)

Example 22 with Property

use of com.codename1.rad.models.Property in project CodenameOne by codenameone.

the class LazyValueC method postCreateComponents.

/**
 * Invoked after the components were created to allow properties that require the entire
 * tree to exist to update the component. This is useful for properties that point
 * at other components.
 */
private void postCreateComponents(DataInputStream in, Container parent, Resources res) throws Exception {
    // finds the component whose properties need to update
    String name = in.readUTF();
    Component lastComponent = null;
    while (name.length() > 0) {
        if (lastComponent == null || !lastComponent.getName().equals(name)) {
            lastComponent = findByName(name, parent);
        }
        Component c = lastComponent;
        int property = in.readInt();
        modifyingProperty(c, property);
        switch(property) {
            case PROPERTY_COMMAND_LEGACY:
                {
                    readCommand(in, c, parent, res, true);
                    break;
                }
            case PROPERTY_COMMAND:
                {
                    readCommand(in, c, parent, res, false);
                    break;
                }
            case PROPERTY_LABEL_FOR:
                c.setLabelForComponent((Label) findByName(in.readUTF(), parent));
                break;
            case PROPERTY_LEAD_COMPONENT:
                ((Container) c).setLeadComponent(findByName(in.readUTF(), parent));
                break;
            case PROPERTY_NEXT_FOCUS_UP:
                c.setNextFocusUp(findByName(in.readUTF(), parent));
                break;
            case PROPERTY_NEXT_FOCUS_DOWN:
                c.setNextFocusDown(findByName(in.readUTF(), parent));
                break;
            case PROPERTY_NEXT_FOCUS_LEFT:
                c.setNextFocusLeft(findByName(in.readUTF(), parent));
                break;
            case PROPERTY_NEXT_FOCUS_RIGHT:
                c.setNextFocusRight(findByName(in.readUTF(), parent));
                break;
        }
        name = in.readUTF();
    }
}
Also used : Container(com.codename1.ui.Container) Component(com.codename1.ui.Component)

Example 23 with Property

use of com.codename1.rad.models.Property in project CodenameOne by codenameone.

the class ConnectionRequest method initConnection.

/**
 * Invoked to initialize HTTP headers, cookies etc.
 *
 * @param connection the connection object
 */
protected void initConnection(Object connection) {
    timeSinceLastUpdate = System.currentTimeMillis();
    CodenameOneImplementation impl = Util.getImplementation();
    impl.setPostRequest(connection, isPost());
    if (readTimeout > 0) {
        impl.setReadTimeout(connection, readTimeout);
    }
    if (insecure) {
        impl.setInsecure(connection, insecure);
    }
    impl.setConnectionId(connection, id);
    if (getUserAgent() != null) {
        impl.setHeader(connection, "User-Agent", getUserAgent());
    }
    if (getContentType() != null) {
        // UWP will automatically filter out the Content-Type header from GET requests
        // Historically, CN1 has always included this header even though it has no meaning
        // for GET requests.  it would be be better if CN1 did not include this header
        // with GET requests, but for backward compatibility, I'll leave it on as
        // the default, and add a property to turn it off.
        // -- SJH Sept. 15, 2016
        boolean shouldAddContentType = contentTypeSetExplicitly || Display.getInstance().getProperty("ConnectionRequest.excludeContentTypeFromGetRequests", "true").equals("false");
        if (isPost() || (getHttpMethod() != null && !"get".equals(getHttpMethod().toLowerCase()))) {
            shouldAddContentType = true;
        }
        if (shouldAddContentType) {
            impl.setHeader(connection, "Content-Type", getContentType());
        }
    }
    if (chunkedStreamingLen > -1) {
        impl.setChunkedStreamingMode(connection, chunkedStreamingLen);
    }
    if (!post && (cacheMode == CachingMode.MANUAL || cacheMode == CachingMode.SMART || cacheMode == CachingMode.OFFLINE_FIRST)) {
        String msince = Preferences.get("cn1MSince" + createRequestURL(), null);
        if (msince != null) {
            impl.setHeader(connection, "If-Modified-Since", msince);
        } else {
            String etag = Preferences.get("cn1Etag" + createRequestURL(), null);
            if (etag != null) {
                impl.setHeader(connection, "If-None-Match", etag);
            }
        }
    }
    if (userHeaders != null) {
        Enumeration e = userHeaders.keys();
        while (e.hasMoreElements()) {
            String k = (String) e.nextElement();
            String value = (String) userHeaders.get(k);
            impl.setHeader(connection, k, value);
        }
    }
}
Also used : Enumeration(java.util.Enumeration) CodenameOneImplementation(com.codename1.impl.CodenameOneImplementation)

Example 24 with Property

use of com.codename1.rad.models.Property in project CodenameOne by codenameone.

the class SEBrowserComponent method init.

private static void init(SEBrowserComponent self, BrowserComponent p) {
    final WeakReference<SEBrowserComponent> weakSelf = new WeakReference<SEBrowserComponent>(self);
    final WeakReference<BrowserComponent> weakP = new WeakReference<BrowserComponent>(p);
    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            SEBrowserComponent self = weakSelf.get();
            if (self == null) {
                return;
            }
            self.cnt = new InternalJPanel(self.instance, self);
            // <--- Important if container is opaque it will cause
            self.cnt.setOpaque(false);
            // all kinds of flicker due to painting conflicts with CN1 pipeline.
            self.cnt.setLayout(new BorderLayout());
            self.cnt.add(BorderLayout.CENTER, self.panel);
        // cnt.setVisible(false);
        }
    });
    self.web.getEngine().getLoadWorker().messageProperty().addListener(new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> ov, String t, String t1) {
            SEBrowserComponent self = weakSelf.get();
            BrowserComponent p = weakP.get();
            if (self == null || p == null) {
                return;
            }
            if (t1.startsWith("Loading http:") || t1.startsWith("Loading file:") || t1.startsWith("Loading https:")) {
                String url = t1.substring("Loading ".length());
                if (!url.equals(self.currentURL)) {
                    p.fireWebEvent("onStart", new ActionEvent(url));
                }
                self.currentURL = url;
            } else if ("Loading complete".equals(t1)) {
            }
        }
    });
    self.web.getEngine().setOnAlert(new EventHandler<WebEvent<String>>() {

        @Override
        public void handle(WebEvent<String> t) {
            BrowserComponent p = weakP.get();
            if (p == null) {
                return;
            }
            String msg = t.getData();
            if (msg.startsWith("!cn1_message:")) {
                System.out.println("Receiving message " + msg);
                p.fireWebEvent("onMessage", new ActionEvent(msg.substring("!cn1_message:".length())));
            }
        }
    });
    self.web.getEngine().getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {

        @Override
        public void changed(ObservableValue<? extends Throwable> ov, Throwable t, Throwable t1) {
            System.out.println("Received exception: " + t1.getMessage());
            if (ov.getValue() != null) {
                ov.getValue().printStackTrace();
            }
            if (t != ov.getValue() && t != null) {
                t.printStackTrace();
            }
            if (t1 != ov.getValue() && t1 != t && t1 != null) {
                t.printStackTrace();
            }
        }
    });
    self.web.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {

        @Override
        public void changed(ObservableValue ov, State oldState, State newState) {
            SEBrowserComponent self = weakSelf.get();
            BrowserComponent p = weakP.get();
            try {
                netscape.javascript.JSObject w = (netscape.javascript.JSObject) self.web.getEngine().executeScript("window");
                if (w == null) {
                    System.err.println("Could not get window");
                } else {
                    Bridge b = new Bridge(p);
                    self.putClientProperty("SEBrowserComponent.Bridge.jconsole", b);
                    w.setMember("jconsole", b);
                }
            } catch (Throwable t) {
                Log.e(t);
            }
            if (self == null || p == null) {
                return;
            }
            /*
                // DISABLING TRANSPARENCY BECAUSE IT CAUSES A MESS WHEN SCROLLING
                // ORIGINALLY TRIED TO ADD THIS FOR CSS GENERATION, BUT LATER OPTED
                // TO ONLY USE CEF FOR THAT ANYWAYS
                // SINCE THIS FX COMPONENT IS DEPRECATED, WE'LL JUST LET IT DIE
                self.transparent = p.getStyle().getBgTransparency() == 0;
                if (self.transparent) {
                    try {
                        Class WebPage = Class.forName("com.sun.webkit.WebPage", true, SEBrowserComponent.class.getClassLoader());
                        Class Accessor = Class.forName("com.sun.javafx.webkit.Accessor", true, SEBrowserComponent.class.getClassLoader());
                        Method getPageFor = Accessor.getMethod("getPageFor", new Class[]{WebEngine.class});
                        Object webPage = getPageFor.invoke(null, self.web.getEngine());
                        Method setBackgroundColor = WebPage.getMethod("setBackgroundColor", new Class[]{int.class});
                        setBackgroundColor.invoke(webPage, 0);
                    } catch (Exception ex){}
                }
                */
            String url = self.web.getEngine().getLocation();
            if (newState == State.SCHEDULED) {
                p.fireWebEvent("onStart", new ActionEvent(url));
            } else if (newState == State.RUNNING) {
                p.fireWebEvent("onLoadResource", new ActionEvent(url));
            } else if (newState == State.SUCCEEDED) {
                if (!p.isNativeScrollingEnabled()) {
                    self.web.getEngine().executeScript("document.body.style.overflow='hidden'");
                }
                // let's just add a client property to the BrowserComponent to enable firebug
                if (Boolean.TRUE.equals(p.getClientProperty("BrowserComponent.firebug"))) {
                    self.web.getEngine().executeScript("if (!document.getElementById('FirebugLite')){E = document['createElement' + 'NS'] && document.documentElement.namespaceURI;E = E ? document['createElement' + 'NS'](E, 'script') : document['createElement']('script');E['setAttribute']('id', 'FirebugLite');E['setAttribute']('src', 'https://getfirebug.com/' + 'firebug-lite.js' + '#startOpened');E['setAttribute']('FirebugLite', '4');(document['getElementsByTagName']('head')[0] || document['getElementsByTagName']('body')[0]).appendChild(E);E = new Image;E['setAttribute']('src', 'https://getfirebug.com/' + '#startOpened');}");
                }
                netscape.javascript.JSObject window = (netscape.javascript.JSObject) self.web.getEngine().executeScript("window");
                Bridge b = new Bridge(p);
                self.putClientProperty("SEBrowserComponent.Bridge.cn1application", b);
                window.setMember("cn1application", b);
                self.web.getEngine().executeScript("while (window._cn1ready && window._cn1ready.length > 0) {var f = window._cn1ready.shift(); f();}");
                // System.out.println("cn1application is "+self.web.getEngine().executeScript("window.cn1application && window.cn1application.shouldNavigate"));
                self.web.getEngine().executeScript("window.addEventListener('unload', function(e){console.log('unloading...');return 'foobar';});");
                p.fireWebEvent("onLoad", new ActionEvent(url));
            }
            self.currentURL = url;
            self.repaint();
        }
    });
    self.web.getEngine().getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {

        @Override
        public void changed(ObservableValue<? extends Throwable> ov, Throwable t, Throwable t1) {
            BrowserComponent p = weakP.get();
            if (p == null) {
                return;
            }
            t1.printStackTrace();
            if (t1 == null) {
                if (t == null) {
                    p.fireWebEvent("onError", new ActionEvent("Unknown error", -1));
                } else {
                    p.fireWebEvent("onError", new ActionEvent(t.getMessage(), -1));
                }
            } else {
                p.fireWebEvent("onError", new ActionEvent(t1.getMessage(), -1));
            }
        }
    });
    // Monitor the location property so that we can send the shouldLoadURL event.
    // This allows us to cancel the loading of a URL if we want to handle it ourself.
    self.web.getEngine().locationProperty().addListener(new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> prop, String before, String after) {
            SEBrowserComponent self = weakSelf.get();
            BrowserComponent p = weakP.get();
            if (self == null || p == null) {
                return;
            }
            if (!p.fireBrowserNavigationCallbacks(self.web.getEngine().getLocation())) {
                self.web.getEngine().getLoadWorker().cancel();
            }
        }
    });
    self.adjustmentListener = new AdjustmentListener() {

        @Override
        public void adjustmentValueChanged(AdjustmentEvent e) {
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    SEBrowserComponent self = weakSelf.get();
                    if (self == null) {
                        return;
                    }
                    self.onPositionSizeChange();
                }
            });
        }
    };
}
Also used : ActionEvent(com.codename1.ui.events.ActionEvent) ObservableValue(javafx.beans.value.ObservableValue) BorderLayout(java.awt.BorderLayout) WeakReference(java.lang.ref.WeakReference) WebEvent(javafx.scene.web.WebEvent) AdjustmentEvent(java.awt.event.AdjustmentEvent) IBrowserComponent(com.codename1.impl.javase.IBrowserComponent) State(javafx.concurrent.Worker.State) AdjustmentListener(java.awt.event.AdjustmentListener)

Example 25 with Property

use of com.codename1.rad.models.Property in project CodenameOne by codenameone.

the class SQLMap method createTable.

/**
 * Creates a table matching the given property component if one doesn't exist yet
 * @param cmp the business object
 * @return true if the table was created false if it already existed
 */
public boolean createTable(PropertyBusinessObject cmp) throws IOException {
    String tableName = getTableName(cmp);
    Cursor cr = null;
    boolean has = false;
    try {
        cr = executeQuery("SELECT * FROM sqlite_master WHERE type='table' AND name='" + tableName + "'");
        has = cr.next();
    } finally {
        if (cr != null) {
            cr.close();
        }
    }
    if (has) {
        return false;
    }
    StringBuilder createStatement = new StringBuilder("CREATE TABLE ");
    createStatement.append(tableName);
    createStatement.append(" (");
    String pkName = (String) cmp.getPropertyIndex().getMetaDataOfClass("cn1$pk");
    boolean autoIncrement = cmp.getPropertyIndex().getMetaDataOfClass("cn1$autoinc") != null;
    boolean first = true;
    for (PropertyBase p : cmp.getPropertyIndex()) {
        SqlType tp = getSqlType(p);
        if (tp == SqlType.SQL_EXCLUDE) {
            continue;
        }
        if (!first) {
            createStatement.append(",");
        }
        first = false;
        String columnName = getColumnName(p);
        createStatement.append(columnName);
        createStatement.append(" ");
        createStatement.append(tp.dbType);
        if (columnName.equalsIgnoreCase(pkName)) {
            createStatement.append(" PRIMARY KEY");
            if (autoIncrement) {
                createStatement.append(" AUTOINCREMENT");
            }
        }
    }
    createStatement.append(")");
    execute(createStatement.toString());
    return true;
}
Also used : Cursor(com.codename1.db.Cursor)

Aggregations

Entity (com.codename1.rad.models.Entity)22 Property (com.codename1.rad.models.Property)16 IOException (java.io.IOException)11 ResultParser (com.codename1.rad.io.ResultParser)10 ArrayList (java.util.ArrayList)10 SimpleDateFormat (com.codename1.l10n.SimpleDateFormat)9 Component (com.codename1.ui.Component)9 Element (com.codename1.xml.Element)8 ParseException (com.codename1.l10n.ParseException)7 Container (com.codename1.ui.Container)7 Label (com.codename1.ui.Label)7 SortedProperties (com.codename1.ant.SortedProperties)6 Log (com.codename1.io.Log)6 Form (com.codename1.ui.Form)6 AnimationObject (com.codename1.ui.animations.AnimationObject)6 Map (java.util.Map)6 Thing (com.codename1.rad.schemas.Thing)5 XMLParser (com.codename1.xml.XMLParser)5 StringReader (java.io.StringReader)5 List (java.util.List)5