Search in sources :

Example 11 with Description

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

the class RSSService method readResponse.

/**
 * {@inheritDoc}
 */
protected void readResponse(InputStream input) throws IOException {
    results = new Vector();
    class FinishParsing extends RuntimeException {
    }
    XMLParser p = new XMLParser() {

        private String lastTag;

        private Hashtable current;

        private String url;

        protected boolean startTag(String tag) {
            if ("item".equalsIgnoreCase(tag) || "entry".equalsIgnoreCase(tag)) {
                if (startOffset > 0) {
                    return true;
                }
                current = new Hashtable();
                if (iconPlaceholder != null) {
                    current.put("icon", iconPlaceholder);
                }
            }
            lastTag = tag;
            return true;
        }

        protected void attribute(String tag, String attributeName, String value) {
            if (current != null) {
                if ("media:thumbnail".equalsIgnoreCase(tag) && "url".equalsIgnoreCase(attributeName)) {
                    current.put("thumb", value);
                } else {
                    if ("media:player".equalsIgnoreCase(tag) && "url".equalsIgnoreCase(attributeName)) {
                        current.put("player", value);
                    }
                }
            }
        }

        protected void textElement(String text) {
            if (lastTag != null && current != null) {
                // make "ATOM" seem like RSS
                if ("summary".equals(lastTag)) {
                    current.put("details", text);
                } else {
                    if ("content".equals(lastTag)) {
                        current.put("description", text);
                    } else {
                        current.put(lastTag, text);
                    }
                }
            }
        }

        protected void endTag(String tag) {
            if ("item".equalsIgnoreCase(tag) || "entry".equalsIgnoreCase(tag)) {
                if (startOffset > 0) {
                    startOffset--;
                    return;
                }
                results.addElement(current);
                current = null;
                if (limit > -1 && results.size() >= limit) {
                    throw new FinishParsing();
                }
            }
            if (tag.equals(lastTag)) {
                lastTag = null;
            }
        }
    };
    p.setParserCallback(this);
    input.mark(10);
    // Skip the bom marking UTF-8 in some streams
    while (input.read() != '<') {
    // input.mark(4);
    }
    int question = input.read();
    String cType = "UTF-8";
    if (question == '?') {
        // we are in an XML header, check if the encoding section exists
        StringBuilder cs = new StringBuilder();
        question = input.read();
        while (question != '>') {
            cs.append((char) question);
            question = input.read();
        }
        String str = cs.toString();
        int index = str.indexOf("encoding=\"") + 10;
        if (index > -1) {
            cType = str.substring(index, Math.max(str.indexOf("\"", index), str.indexOf("'", index)));
        }
    } else {
        // oops, continue as usual
        input.reset();
    }
    String resultType = getResponseContentType();
    if (resultType != null && resultType.indexOf("charset=") > -1) {
        cType = resultType.substring(resultType.indexOf("charset=") + 8);
    }
    try {
        int pos2 = cType.indexOf(';');
        if (pos2 > 0) {
            cType = cType.substring(0, pos2);
        }
        p.eventParser(new InputStreamReader(input, cType));
    } catch (FinishParsing ignor) {
        hasMore = true;
    }
    if (isCreatePlainTextDetails()) {
        int elementCount = results.size();
        for (int iter = 0; iter < elementCount; iter++) {
            Hashtable h = (Hashtable) results.elementAt(iter);
            String s = (String) h.get("description");
            if (s != null && !h.containsKey("details")) {
                XMLParser x = new XMLParser();
                Element e = x.parse(new CharArrayReader(("<xml>" + s + "</xml>").toCharArray()));
                Vector results = e.getTextDescendants(null, false);
                StringBuilder endResult = new StringBuilder();
                for (int i = 0; i < results.size(); i++) {
                    endResult.append(((Element) results.elementAt(i)).getText());
                }
                h.put("details", endResult.toString());
            }
        }
    }
    fireResponseListener(new NetworkEvent(this, results));
}
Also used : CharArrayReader(com.codename1.io.CharArrayReader) InputStreamReader(java.io.InputStreamReader) Hashtable(java.util.Hashtable) Element(com.codename1.xml.Element) NetworkEvent(com.codename1.io.NetworkEvent) XMLParser(com.codename1.xml.XMLParser) Vector(java.util.Vector)

Example 12 with Description

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

the class AndroidImplementation method setNotificationChannel.

/**
 * Sets the notification channel on a notification builder.  Uses service properties to
 * set properties of channel.
 * @param nm The notification manager.
 * @param mNotifyBuilder The notify builder
 * @param context The context
 * @param soundName The name of the sound to use for notifications on this channel.  E.g. mysound.mp3.  This feature is not yet implemented, but
 *  parameter is added now to scaffold compatibility with build daemon until implementation is complete.
 * @since 8.0
 */
public static void setNotificationChannel(NotificationManager nm, NotificationCompat.Builder mNotifyBuilder, Context context, String soundName) {
    if (android.os.Build.VERSION.SDK_INT >= 26) {
        try {
            NotificationManager mNotificationManager = nm;
            String id = getServiceProperty("android.NotificationChannel.id", "cn1-channel", context);
            CharSequence name = getServiceProperty("android.NotificationChannel.name", "Notifications", context);
            String description = getServiceProperty("android.NotificationChannel.description", "Remote notifications", context);
            // NotificationManager.IMPORTANCE_LOW = 2
            // NotificationManager.IMPORTANCE_HIGH = 4  // <-- Minimum level to produce sound.
            int importance = Integer.parseInt(getServiceProperty("android.NotificationChannel.importance", "4", context));
            // Note: Currently we use a single notification channel for the app, but if the app uses different kinds of
            // push notifications, then this may not be sufficient.   E.g. The app may send both silent push notifications
            // and regular notifications - but their settings (e.g. sound) are all managed through one channel with
            // same settings.
            // TODO Add support for multiple channels.
            // See https://github.com/codenameone/CodenameOne/issues/2583
            Class clsNotificationChannel = Class.forName("android.app.NotificationChannel");
            // android.app.NotificationChannel mChannel = new android.app.NotificationChannel(id, name, importance);
            Constructor constructor = clsNotificationChannel.getConstructor(java.lang.String.class, java.lang.CharSequence.class, int.class);
            Object mChannel = constructor.newInstance(new Object[] { id, name, importance });
            Method method = clsNotificationChannel.getMethod("setDescription", java.lang.String.class);
            method.invoke(mChannel, new Object[] { description });
            // mChannel.setDescription(description);
            method = clsNotificationChannel.getMethod("enableLights", boolean.class);
            method.invoke(mChannel, new Object[] { Boolean.parseBoolean(getServiceProperty("android.NotificationChannel.enableLights", "true", context)) });
            // mChannel.enableLights(Boolean.parseBoolean(getServiceProperty("android.NotificationChannel.enableLights", "true", context)));
            method = clsNotificationChannel.getMethod("setLightColor", int.class);
            method.invoke(mChannel, new Object[] { Integer.parseInt(getServiceProperty("android.NotificationChannel.lightColor", "" + android.graphics.Color.RED, context)) });
            // mChannel.setLightColor(Integer.parseInt(getServiceProperty("android.NotificationChannel.lightColor", "" + android.graphics.Color.RED, context)));
            method = clsNotificationChannel.getMethod("enableVibration", boolean.class);
            method.invoke(mChannel, new Object[] { Boolean.parseBoolean(getServiceProperty("android.NotificationChannel.enableVibration", "false", context)) });
            // mChannel.enableVibration(Boolean.parseBoolean(getServiceProperty("android.NotificationChannel.enableVibration", "false", context)));
            String vibrationPatternStr = getServiceProperty("android.NotificationChannel.vibrationPattern", null, context);
            if (vibrationPatternStr != null) {
                String[] parts = vibrationPatternStr.split(",");
                int len = parts.length;
                long[] pattern = new long[len];
                for (int i = 0; i < len; i++) {
                    pattern[i] = Long.parseLong(parts[i].trim());
                }
                method = clsNotificationChannel.getMethod("setVibrationPattern", long[].class);
                method.invoke(mChannel, new Object[] { pattern });
            // mChannel.setVibrationPattern(pattern);
            }
            String soundUri = getServiceProperty("android.NotificationChannel.soundUri", null, context);
            if (soundUri != null) {
                Uri uri = android.net.Uri.parse(soundUri);
                android.media.AudioAttributes audioAttributes = new android.media.AudioAttributes.Builder().setContentType(android.media.AudioAttributes.CONTENT_TYPE_SONIFICATION).setUsage(android.media.AudioAttributes.USAGE_NOTIFICATION).build();
                method = clsNotificationChannel.getMethod("setSound", android.net.Uri.class, android.media.AudioAttributes.class);
                method.invoke(mChannel, new Object[] { uri, audioAttributes });
            }
            method = NotificationManager.class.getMethod("createNotificationChannel", clsNotificationChannel);
            method.invoke(mNotificationManager, new Object[] { mChannel });
            // mNotificationManager.createNotificationChannel(mChannel);
            try {
                // For some reason I can't find the app-support-v4.jar for
                // API 26 that includes this method so that I can compile in netbeans.
                // So we use reflection...  If someone coming after can find a newer version
                // that has setChannelId(), please rip out this ugly reflection hack and
                // replace it with a proper call to mNotifyBuilder.setChannelId(id)
                mNotifyBuilder.getClass().getMethod("setChannelId", new Class[] { String.class }).invoke(mNotifyBuilder, new Object[] { id });
            } catch (Exception ex) {
                Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
            }
        // mNotifyBuilder.setChannelId(id);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchMethodException ex) {
            Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalArgumentException ex) {
            Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvocationTargetException ex) {
            Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
        }
    // mNotifyBuilder.setChannelId(id);
    }
}
Also used : Uri(android.net.Uri) Constructor(java.lang.reflect.Constructor) Method(java.lang.reflect.Method) Paint(android.graphics.Paint) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) MediaException(com.codename1.media.AsyncMedia.MediaException) ParseException(java.text.ParseException) SAXException(org.xml.sax.SAXException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) InvocationTargetException(java.lang.reflect.InvocationTargetException) JSONObject(org.json.JSONObject)

Example 13 with Description

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

the class PushNotificationService method push.

@Override
public void push(final String value) {
    final PushCallback callback = getPushCallbackInstance();
    if (callback != null) {
        Display.getInstance().callSerially(new Runnable() {

            public void run() {
                callback.push(value);
            }
        });
    } else {
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Intent newIntent = new Intent(this, getStubClass());
        PendingIntent contentIntent = AndroidImplementation.createPendingIntent(this, 0, newIntent);
        Notification.Builder builder = new Notification.Builder(this).setContentIntent(contentIntent).setSmallIcon(android.R.drawable.stat_notify_sync).setTicker(value).setAutoCancel(true).setWhen(System.currentTimeMillis()).setContentTitle(value).setDefaults(Notification.DEFAULT_ALL);
        // The following section is commented out so that builds against SDKs below 26
        // won't fail.
        /*<SDK26>
            if(android.os.Build.VERSION.SDK_INT >= 21){
                builder.setCategory("Notification");
            }
            if (android.os.Build.VERSION.SDK_INT >= 26) {
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

                String id = getProperty("android.NotificationChannel.id", "cn1-channel");

                CharSequence name = getProperty("android.NotificationChannel.name", "Notifications");

                String description = getProperty("android.NotificationChannel.description", "Remote notifications");

                int importance = Integer.parseInt(getProperty("android.NotificationChannel.importance", ""+NotificationManager.IMPORTANCE_HIGH));

                android.app.NotificationChannel mChannel = new android.app.NotificationChannel(id, name,importance);

                mChannel.setDescription(description);

                mChannel.enableLights(Boolean.parseBoolean(getProperty("android.NotificationChannel.enableLights", "true")));

                mChannel.setLightColor(Integer.parseInt(getProperty("android.NotificationChannel.lightColor", ""+android.graphics.Color.RED)));

                mChannel.enableVibration(Boolean.parseBoolean(getProperty("android.NotificationChannel.enableVibration", "false")));
                String vibrationPatternStr = getProperty("android.NotificationChannel.vibrationPattern", null);
                if (vibrationPatternStr != null) {
                    String[] parts = vibrationPatternStr.split(",");
                    int len = parts.length;
                    long[] pattern = new long[len];
                    for (int i=0; i<len; i++) {
                        pattern[i] = Long.parseLong(parts[i].trim());
                    }
                    mChannel.setVibrationPattern(pattern);
                }



                mNotificationManager.createNotificationChannel(mChannel);
                System.out.println("Setting push channel to "+id);
                builder.setChannelId(id);
            }
            </SDK26>*/
        Notification notif = builder.build();
        // (int)System.currentTimeMillis();
        int notifId = getNotifyId();
        // notif.extras.putInt("notificationId", notifId);
        nm.notify(notifId, notif);
    }
}
Also used : NotificationManager(android.app.NotificationManager) PushCallback(com.codename1.push.PushCallback) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) PendingIntent(android.app.PendingIntent) Notification(android.app.Notification)

Example 14 with Description

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

the class AutocompleteOverrideFilterSample method searchLocations.

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;
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) JSONParser(com.codename1.io.JSONParser) IOException(java.io.IOException)

Example 15 with Description

use of com.codename1.rad.models.Property.Description in project CodeRAD by shannah.

the class ResultParserTest method manualExampleTest.

private void manualExampleTest() throws Exception {
    String xml = "<?xml version=\"1.0\"?>\n" + "<catalog>\n" + "   <book id=\"bk101\">\n" + "      <author>Gambardella, Matthew</author>\n" + "      <title>XML Developer's Guide</title>\n" + "      <genre>Computer</genre>\n" + "      <price>44.95</price>\n" + "      <publish_date>2000-10-01</publish_date>\n" + "      <description>An in-depth look at creating applications \n" + "      with XML.</description>\n" + "   </book>\n" + "   <book id=\"bk102\">\n" + "      <author>Ralls, Kim</author>\n" + "      <title>Midnight Rain</title>\n" + "      <genre>Fantasy</genre>\n" + "      <price>5.95</price>\n" + "      <publish_date>2000-12-16</publish_date>\n" + "      <description>A former architect battles corporate zombies, \n" + "      an evil sorceress, and her own childhood to become queen \n" + "      of the world.</description>\n" + "   </book>\n" + "   <book id=\"bk103\">\n" + "      <author>Corets, Eva</author>\n" + "      <title>Maeve Ascendant</title>\n" + "      <genre>Fantasy</genre>\n" + "      <price>5.95</price>\n" + "      <publish_date>2000-11-17</publish_date>\n" + "      <description>After the collapse of a nanotechnology \n" + "      society in England, the young survivors lay the \n" + "      foundation for a new society.</description>\n" + "   </book>\n" + "   <book id=\"bk104\">\n" + "      <author>Corets, Eva</author>\n" + "      <title>Oberon's Legacy</title>\n" + "      <genre>Fantasy</genre>\n" + "      <price>5.95</price>\n" + "      <publish_date>2001-03-10</publish_date>\n" + "      <description>In post-apocalypse England, the mysterious \n" + "      agent known only as Oberon helps to create a new life \n" + "      for the inhabitants of London. Sequel to Maeve \n" + "      Ascendant.</description>\n" + "   </book>\n" + "   <book id=\"bk105\">\n" + "      <author>Corets, Eva</author>\n" + "      <title>The Sundered Grail</title>\n" + "      <genre>Fantasy</genre>\n" + "      <price>5.95</price>\n" + "      <publish_date>2001-09-10</publish_date>\n" + "      <description>The two daughters of Maeve, half-sisters, \n" + "      battle one another for control of England. Sequel to \n" + "      Oberon's Legacy.</description>\n" + "   </book>\n" + "   <book id=\"bk106\">\n" + "      <author>Randall, Cynthia</author>\n" + "      <title>Lover Birds</title>\n" + "      <genre>Romance</genre>\n" + "      <price>4.95</price>\n" + "      <publish_date>2000-09-02</publish_date>\n" + "      <description>When Carla meets Paul at an ornithology \n" + "      conference, tempers fly as feathers get ruffled.</description>\n" + "   </book>\n" + "   <book id=\"bk107\">\n" + "      <author>Thurman, Paula</author>\n" + "      <title>Splish Splash</title>\n" + "      <genre>Romance</genre>\n" + "      <price>4.95</price>\n" + "      <publish_date>2000-11-02</publish_date>\n" + "      <description>A deep sea diver finds true love twenty \n" + "      thousand leagues beneath the sea.</description>\n" + "   </book>\n" + "   <book id=\"bk108\">\n" + "      <author>Knorr, Stefan</author>\n" + "      <title>Creepy Crawlies</title>\n" + "      <genre>Horror</genre>\n" + "      <price>4.95</price>\n" + "      <publish_date>2000-12-06</publish_date>\n" + "      <description>An anthology of horror stories about roaches,\n" + "      centipedes, scorpions  and other insects.</description>\n" + "   </book>\n" + "   <book id=\"bk109\">\n" + "      <author>Kress, Peter</author>\n" + "      <title>Paradox Lost</title>\n" + "      <genre>Science Fiction</genre>\n" + "      <price>6.95</price>\n" + "      <publish_date>2000-11-02</publish_date>\n" + "      <description>After an inadvertant trip through a Heisenberg\n" + "      Uncertainty Device, James Salway discovers the problems \n" + "      of being quantum.</description>\n" + "   </book>\n" + "   <book id=\"bk110\">\n" + "      <author>O'Brien, Tim</author>\n" + "      <title>Microsoft .NET: The Programming Bible</title>\n" + "      <genre>Computer</genre>\n" + "      <price>36.95</price>\n" + "      <publish_date>2000-12-09</publish_date>\n" + "      <description>Microsoft's .NET initiative is explored in \n" + "      detail in this deep programmer's reference.</description>\n" + "   </book>\n" + "   <book id=\"bk111\">\n" + "      <author>O'Brien, Tim</author>\n" + "      <title>MSXML3: A Comprehensive Guide</title>\n" + "      <genre>Computer</genre>\n" + "      <price>36.95</price>\n" + "      <publish_date>2000-12-01</publish_date>\n" + "      <description>The Microsoft MSXML3 parser is covered in \n" + "      detail, with attention to XML DOM interfaces, XSLT processing, \n" + "      SAX and more.</description>\n" + "   </book>\n" + "   <book id=\"bk112\">\n" + "      <author>Galos, Mike</author>\n" + "      <title>Visual Studio 7: A Comprehensive Guide</title>\n" + "      <genre>Computer</genre>\n" + "      <price>49.95</price>\n" + "      <publish_date>2001-04-16</publish_date>\n" + "      <description>Microsoft Visual Studio 7 is explored in depth,\n" + "      looking at how Visual Basic, Visual C++, C#, and ASP+ are \n" + "      integrated into a comprehensive development \n" + "      environment.</description>\n" + "   </book>\n" + "</catalog>";
    EntityType bookType = new EntityTypeBuilder().string(Thing.identifier).string(Thing.name).string(Thing.description).build();
    class Book extends BaseEntity {
    }
    EntityType.register(Book.class, bookType, cls -> {
        return new Book();
    });
    class Books extends EntityList<Book> {
    }
    EntityType.registerList(Books.class, Book.class, cls -> {
        return new Books();
    });
    Tag BOOKS = new Tag("Books");
    EntityType catalogType = new EntityTypeBuilder().list(Books.class, BOOKS).build();
    class Catalog extends BaseEntity {

        {
            setEntityType(catalogType);
        }
    }
    EntityType.register(Catalog.class, cls -> {
        return new Catalog();
    });
    ResultParser parser = new ResultParser(catalogType).property("./book", BOOKS).entityType(bookType).property("@id", Thing.identifier).property("title", Thing.name).property("description", Thing.description);
    Catalog catalog = (Catalog) parser.parseXML(xml, new Catalog());
    Books books = (Books) catalog.get(BOOKS);
    assertEqual("bk101", books.get(0).get(Thing.identifier));
    assertEqual("bk112", books.get(books.size() - 1).get(Thing.identifier));
    assertEqual("XML Developer's Guide", books.get(0).get(Thing.name));
}
Also used : ResultParser(com.codename1.rad.io.ResultParser)

Aggregations

IOException (java.io.IOException)6 BorderLayout (com.codename1.ui.layouts.BorderLayout)5 Container (com.codename1.ui.Container)4 Cursor (com.codename1.db.Cursor)3 Row (com.codename1.db.Row)3 ResultParser (com.codename1.rad.io.ResultParser)3 Form (com.codename1.ui.Form)3 ArrayList (java.util.ArrayList)3 SpanLabel (com.codename1.components.SpanLabel)2 Button (com.codename1.ui.Button)2 Element (com.codename1.xml.Element)2 XMLParser (com.codename1.xml.XMLParser)2 InputStreamReader (java.io.InputStreamReader)2 Notification (android.app.Notification)1 NotificationManager (android.app.NotificationManager)1 PendingIntent (android.app.PendingIntent)1 Intent (android.content.Intent)1 NameNotFoundException (android.content.pm.PackageManager.NameNotFoundException)1 Paint (android.graphics.Paint)1 Uri (android.net.Uri)1