End-to-End J2ME Application Development by Example - Introducing Smart Ticket

《光学》全套PPT课件(安徽大学) 立即下载

Overview

The first Java technology blueprint, Java Pet Store, was released in 2001 as a showcase for Sun's J2EE technologies. The blueprint not only provides sample code for a multilayered, database-driven e-commerce application, it also furnishes design guidelines and demonstrates commonly used patterns. Since that first release, the Java blueprints have become one of the most important resources for developers wanting to learn the latest J2EE technologies and best practices.

The Smart Ticket blueprint adds a new dimension: mobility. It demonstrates how to build a complete end-to-end mobile commerce system for ordering movie tickets, using J2ME MIDP for a wireless front end and a J2EE application server and a relational database at the back end. Studying how this application is designed and built will greatly enhance your understanding of the problems of mobile enterprise applications – and their solutions.

This article covers version 2.0 Early Access of the Smart Ticket code, released in April 2003. The screen shots and code samples in the early-access version may change slightly in the final release, but the lessons you learn from the design should still hold. Smart Ticket 1.2 is still available. It has the same model and back-end implementation as the version discussed here, so many of the details are applicable to both past and future releases. Unless otherwise noted, all source code in this article is copyrighted by Sun Microsystems.

Download and Installation

The Smart Ticket application is available from Sun's Blueprints web site. The .zip archive contains source code, Ant build scripts, and pre-built, deployable applications.

Smart Ticket contains a J2ME component and a J2EE component. Running it requires a J2EE application server (such as the Sun J2EE reference implementation, version 1.3 or higher), and either a MIDP 2.0-compatible device with Internet connectivity or a suitable emulator, such as the one in Sun's J2ME Wireless Toolkit 2.0. The Smart Ticket distribution contains specific instructions for building and deploying the application. To get started:

  1. Make sure you have these resources installed:

    • JDK v1.4.1 or higher
    • J2EE v1.3.1 or higher
    • J2ME Wireless Toolkit 2.0 or higher

  2. Set the following environment variables:

    • JAVA_HOME: JDK installation directory
    • J2EE_HOME: J2EE RI installation directory
    • J2MEWTK_HOME: J2ME Wireless Toolkit installation directory

  3. Start the J2EE server:

    J2EE_HOME/bin/cloudscape -start
    J2EE_HOME/bin/j2ee -verbose
    

  4. Deploy the J2EE application. Use the setup script as follows to invoke the deploy Ant task in setup.xml:

    setup deploy
    

  5. Point your browser to http://localhost:8000/smartticket and click on the Populate Database link to import mock theater and movie data into the database. This is a very slow process on older computers, so be patient! The mock data includes theaters in two Zip codes: 95054 and 95130.

  6. Start J2ME Wireless Toolkit 2.0 and run the MIDlet described in smart_ticket-client.jad.

Smart Ticket in Action

When you have the MIDlet running, take a brief tour to get the user's perspective. You'll find you can perform four kinds of tasks.

  • Manage user preferences: When you start the MIDP client for the first time, you'll be asked to create a profile with a username, password, preferred Zip codes for theater search, preferred day of the week and, optionally, credit-card numbers. Smart Ticket uses the account credentials to create a user account on the server side, and caches the preference data on the device. You could also configure the MIDP client to cache the credentials so that you don't need to sign in manually every time you want to purchase tickets or submit movie ratings. You can modify user preferences at any time.

    (Click image to enlarge.)
  • Search for films and purchase tickets: Once you've logged in, you can search among theaters, movies, and show times that reflect your preference data. Once you select a show, the MIDlet presents a seating map that shows available seats. This process involves a series of real-time queries to the J2EE server. Taking advantage of MIDP's rich UI, you can select a seat and make a reservation. The reservation is written to the server database and will be reflected on the seating map in the next search.

    (Click image to enlarge.)
  • Rate movies: You can assign ratings to movies you've seen. These aren't immediately submitted to the server. They are cached on device and can be synchronized to the server whenever you like, so you can rate movies even when your phone is out of network range (for example, in a shielded cinema building!) The synchronization agent is smart enough to stop you from "stuffing the ballot box": If you rate the same movie more than once, it keeps only the most recent rating in the database.

    (Click image to enlarge.)
  • Cache theater schedules: You can download a theater's schedule to the client application and browse it offline, to avoid lengthy round trips. You can delete or re-download the schedule as needed.

    (Click image to enlarge.)
Smart Ticket Benefits

Older mobile-commerce platforms such as the WAP/WML-based micro-browsers put all the intelligence on the server side. A key benefit of J2ME is that it supports smart clients that run on devices. Smart Ticket capitalizes fully on the advantages of the smart-client application paradigm:

  • Rich UI: Taking advantage of the LCDUI enhancements in MIDP 2.0, the Smart Ticket client offers an excellent user interface. For example, it allows the user to select seats on an interactive seating map, and when you browse a schedule and choose a date, the MIDlet dynamically adds the showtime to the current screen.
  • Cached preferences: User preferences are fully cached to support extreme personalization -- a core value of mobile commerce. For example, you don't need to enter Zip code, credit-card number, or even personal login information every time you use Smart Ticket, which greatly reduces the amount of keypad labor.
  • Offline capability: Limited and unreliable mobile network coverage has hindered the adoption of "always connected" applications based on micro-browsers. J2ME smart clients follow the "occasionally connected" paradigm, using data stored on the device and synchronized with server-resident data as desired - exemplified by Smart Ticket's support for browsing downloaded schedules and rating movies offline.
  • High-performance cache: The downloaded schedule can also serve as a performance cache, even when the device is connected. It reduces the need for multiple round trips, which could be very slow.
  • Smart synchronization: The application caches used by smart clients need to be updated periodically from the back end. Movie schedules can be downloaded directly by the user, and ratings are synchronized through smart agents residing on both client and server.

How are those features implemented?

Important Architectural Patterns

The Overall MVC Pattern

The overall architecture of the Smart Ticket application follows the Model-View-Controller pattern. The application is separated into several logical layers, so developers can change one part without affecting others. Smart Ticket adopts the MVC model as follows:

  • View: Each view class displays an interactive UI screen and waits for user input. When the user generates a UI event by pressing a button, or selecting an item from a list, the view class's event handler captures the event and passes control to the controller class. Most classes in the com.sun.j2me.blueprints.smartticket.client.midp.ui package are view classes.

    public class ChooseMovieUI extends Form implements 
        CommandListener, ItemStateListener, 
            ItemCommandListener {
    
      private UIController uiController;
      
      // ...
      
      public void commandAction(Command command, Displayable 
          displayable) { uiController.commandAction(command, 
              displayable);
      } 
    
      public void commandAction(Command command, Item item) {
        if (command == selectSeatsCommand) {
          if (numOfTickets.getString().length() == 0 
              || Integer.parseInt(numOfTickets.getString()) 
                  < 1) {
            uiController.showErrorAlert(
              uiController.getString(
                UIConstants.NUM_OF_TICKET_ERR));
          } else {
            uiController.selectSeatsSelected(
              movieSchedules[movieList.getSelectedIndex()],
                                             getShowTimes());
          }
        } 
      } 
    }
    

  • Controller: The controller class knows all the possible interactions between the user and the program. In Smart Ticket, the UIController class has one method for each possible action; for example, purchaseRequested(). The action method often starts two new threads, one to perform the action in the background and the other to display a progress bar for the user. The action thread is represented by the EventDispatcher class, whose run() method contains a long switch statement that performs the action requested by invoking appropriate methods in the model layer. When the last-called of these methods returns, the controller initiates and displays the next UI screen.

    package com.sun.j2me.blueprints.smartticket.client.midp.ui;
    
    public class UIController {
    
      // references to all UI classes
      // ...
      
      public UIController(MIDlet midlet, ModelFacade model) {
        this.display = Display.getDisplay(midlet);
        this.model = model;
      }
      
      // ...
      
      public void selectSeatsSelected(TheaterSchedule.MovieSchedule
                                movieSchedule, int[] showTime) {
        selectedShowTime = showTime;
        selectedMovie = movieSchedule.getMovie();
        selectedMovieSchedule = movieSchedule;
    
        runWithProgress(
          new EventDispatcher(EventIds.EVENT_ID_SELECTSEATSSELECTED,
                              mainMenuUI),
          getString(UIConstants.PROCESSING), false);
      }
      
      class EventDispatcher extends Thread {
        private int taskId;
        private Displayable fallbackUI;
    
        EventDispatcher(int taskId, Displayable fallbackUI) {
          this.taskId = taskId;
          this.fallbackUI = fallbackUI;
          return;
        }
    
        public void run() {
          try {
            switch (taskId) {
            
            // cases ...
            
            case EventIds.EVENT_ID_SELECTSEATSSELECTED: {
              SeatingPlan seatingPlan = 
                selectedMovieSchedule.getSeatingPlan(selectedShowTime);
              String movieName = selectedMovie.getTitle();
    
              seatingPlanUI.init(selectedTheater.getName(), movieName,
                                 seatingPlan, selectedShowTime);
              display.setCurrent(seatingPlanUI);
    
              break;
            } 
    
            case EventIds.EVENT_ID_SEATSSELECTED: {
              reservation = 
                model.reserveSeats(selectedTheater.getPrimaryKey(), 
                                   selectedMovie.getPrimaryKey(), 
                                   selectedShowTime, selectedSeats);
    
              purchaseTicketsUI.init(model.getAccountInfo());
              display.setCurrent(purchaseTicketsUI);
    
              break;
            } 
    
            case EventIds.EVENT_ID_PURCHASEREQUESTED: {
              model.purchaseTickets(reservation);
              purchaseCompleteUI.init(reservation.getId(), 
                                      selectedTheater.getName(), 
                                      selectedMovie.getTitle(), 
                                      selectedShowTime);
              display.setCurrent(purchaseCompleteUI);
    
              break;
            }
            
            // Other cases ...
            
            }
          } catch (Exception exception) {
            // handle exceptions
          }
        } // end of run() method
      } // end of EventDispatcher class
    }
    

  • Model: Classes in the model layer contain all the application logic. In fact, the entire J2EE server component, the on-device caches, and the communication classes all belong to the model layer. The model layer features sophisticated façade patterns on both the client side and the server side.

      Let's look at the details of the model layer.

    The Client-Side Facade

    For most application actions, the controller's entry point into the model layer is the ModelFacade class. In keeping with the MVC pattern, ModelFacade contains one method for each action in the model layer. Depending on the nature of the action, the façade delegates it to one or more of the following model classes:

    • The LocalModel class handles actions that need access to data stored locally, on the device. For example, if an action entails reading or writing preference data, ModelFacade calls the appropriate action method in LocalModel.
    • The RemoteModelProxy class, which implements the RemoteModel interface, handles actions that require access to the J2EE server, such as ticket purchases. Action methods in RemoteModelProxy make remote procedure calls (RPCs) to the façade on the server side, in a format we'll disuss when we look at the back end.
    • The SynchronizationAgent class synchronizes data stored on the remote server with local data. In Smart Ticket, only movie ratings are synchronized. This agent has two action methods: synchronizeMovieRatings() synchronizes the ratings; commitMovieRatings() commits the resolved synchronization requests to the back end and updates the content of the local store.
    package com.sun.j2me.blueprints.smartticket.client.midp.model;
    
    public class ModelFacade {
    
      private SynchronizationAgent syncAgent;
      private RemoteModelProxy remoteModel;
      private LocalModel localModel;
    
      // Action methods ...
      
      public Reservation reserveSeats(String theaterKey,
                             String movieKey,
                             int[] showTime, Seat[] seats)
                             throws ApplicationException {
        try {
          return remoteModel.reserveSeats(theaterKey, 
              movieKey, showTime, seats);
        } catch (ModelException me) {
          // ...
        } 
      } 
    
      public void purchaseTickets(Reservation reservation) 
                              throws ApplicationException {
        try {
          remoteModel.purchaseTickets(reservation.getId());
          localModel.addMovieRating(
            new MovieRating(remoteModel.getMovie(reservation.getMovieId()), 
                            reservation.getShowTime()));
        } catch (ModelException me) {
          // ...
        }
        return;
      }
      
      public void synchronizeMovieRatings(int 
         conflictResolutionStrategyId) 
             throws ApplicationException {
        try {
          syncAgent.synchronizeMovieRatings(conflictResolutionStrategyId);
          return;
        } catch (ModelException me) {
          // ...
        }
      }
      // ...
    }
    

    The Server-Side Facade

    The server side of the application uses a number of Enterprise JavaBeans components (EJBs) to encapsulate the business logic and manage interaction with a relational database. When the RemoteModelProxy on the client side makes an RPC call to the server side, the HTTP servlet SmartTicketServlet invokes the appropriate action method in a session EJB, SmartTicketFacadeBean, through a business delegate object SmartTicketBD. Depending on the nature of the request, it will be further delegated to one of two other session beans, TicketingBean or SynchronizingBean. An array of entity beans uses EJB 2.0 container-managed persistence to update the database as needed.

    package com.sun.j2me.blueprints.smartticket.server.web.midp;
    
    public class SmartTicketServlet extends HttpServlet {
    
      public static final String SESSION_ATTRIBUTE_SMART_TICKET_BD =
        "com.sun.j2me.blueprints.smartticket.server.web.midp.SmartTicketBD";
      
      protected void doPost(HttpServletRequest request,
                            HttpServletResponse response)
                            throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        SmartTicketBD smartTicketBD = (SmartTicketBD)
          session.getAttribute(SESSION_ATTRIBUTE_SMART_TICKET_BD);
    
        // Calls handleCall() method and encodes the URL for
        // session tracking
      }
      
      public int handleCall(SmartTicketBD smartTicketBD, 
         InputStream in, OutputStream out)
             throws IOException, ApplicationException {
        // Identifies the requested action method
        
        // Executes the method, as selected in a switch statement
        switch (method) {
        
        // cases ...
        
        case MessageConstants.OPERATION_GET_MOVIE: {
          getMovie(smartTicketBD, call, successfulResult);
          break;
        }
    
        // more cases ...
        
        }
      }
    }
    
    package com.sun.j2me.blueprints.smartticket.server.web.midp;
    
    public class SmartTicketBD implements RemoteModel {
    
      public static final String EJB_REF_FACADE = 
          "ejb/SmartTicketFacade";
      private SmartTicketFacadeLocal facade;
      private ServletContext servletContext = null;
    
      public SmartTicketBD(ServletContext servletContext) 
                           throws ApplicationException {
        this.servletContext = servletContext;
    
        try {
          Context context = (Context)
            new InitialContext().lookup("java:comp/env");
          facade = ((SmartTicketFacadeLocalHome)
            context.lookup(EJB_REF_FACADE)).create();
          return;
        } catch (Exception e) {
          throw new ApplicationException(e);
        } 
      }
      
      public Movie getMovie(String movieKey) 
          throws ModelException, ApplicationException {
        try {
          MovieLocal movieLocal = facade.getMovie(movieKey);
          Movie movie = new Movie(movieLocal.getId(), 
                                  movieLocal.getTitle(), 
                                  movieLocal.getSummary(), 
                                  movieLocal.getRating());
    
          return movie;
        } catch (SmartTicketFacadeException stfe) {
          throw new 
              ModelException(ModelException.CAUSE_MOVIE_NOT_FOUND);
        } catch (Exception e) {
          throw new ApplicationException(e);
        } 
      }
      
      // Other action methods in RemoteModel interface ...
      
    }
    
    package com.sun.j2me.blueprints.smartticket.server.ejb;
    
    public class SmartTicketFacadeBean implements SessionBean {
    
      // ...
      
      public MovieLocal getMovie(String movieId) 
                        throws SmartTicketFacadeException {
        try {
          return movieHome.findByPrimaryKey(movieId);
        } catch (FinderException fe) {
          throw new 
              SmartTicketFacadeException("No matching movie.");
        } 
      }
      
      // ...
      
    }
    

    This diagram illustrates the overall MVC-plus-façade architecture:

    Implementation Patterns

    The MVC and façade patterns define the overall architecture of the application. In addition, Smart Ticket also showcases some important behavior patterns that could help developers improve productivity.

    Chain of Handlers

    The RemoteModelProxy class delegates each requested action to a chain of handler classes that transparently work out the dirty plumbing of the RMS serialization and HTTP connection. The chained-handler architecture is based on the RequestHandler interface and on the RemoteModelRequestHandler abstract class that implements it:

    public interface RequestHandler {
    
        RequestHandler getNextHandler();
        void init() throws ApplicationException;
        void destroy() throws ApplicationException;
    }
    
    abstract public class RemoteModelRequestHandler 
      implements RequestHandler, RemoteModel {
    
      private RemoteModelRequestHandler nextHandler;
      private Preferences preferences;
      protected static ProgressObserver progressObserver;
    
      public RemoteModelRequestHandler(
          RemoteModelRequestHandler nextHandler) {
        this.nextHandler = nextHandler;
      }
    
      public RequestHandler getNextHandler() {
        return nextHandler;
      }
    
      public void init() throws ApplicationException {
        if (nextHandler != null) {
          nextHandler.init();
        }
        return;
      }
    
      public void destroy() throws ApplicationException {
        if (nextHandler != null) {
          nextHandler.destroy();
        }
        return;
      }
      
      public void login(String userName, String password) 
          throws ModelException, ApplicationException {
        getRemoteModelRequestHandler().login(userName, password);
        return;
      } 
    
      public void createAccount(AccountInfo accountInfo) 
                                throws ModelException, 
                                ApplicationException {
        getRemoteModelRequestHandler().createAccount(accountInfo);
        return;
      }
      
      // Other action methods declared in RemoteModel
      // ...
    }
    

    Concrete handler classes extend the RemoteModelRequestHandler class. Nested constructors establish a chain of handlers. Smart Ticket makes two handler classes available: RMSCacheHandler and HTTPCommunicationHandler. The chain is assembled thus:

    public class RemoteModelProxy extends ModelObjectLoader 
                                  implements RemoteModel {
    
      private RemoteModelRequestHandler requestHandlerChain;
      private Preferences preferences = null;
      private Hashtable movies = new Hashtable();
    
      public RemoteModelProxy(String serviceURL) 
                              throws ApplicationException {
        requestHandlerChain =
          new RMSCacheHandler(
            new HTTPCommunicationHandler(null, serviceURL));
        return;
      }
      
      // ...
      
      public Movie getMovie(String movieKey) 
                            throws ModelException, 
                            ApplicationException {
        Movie movie = (Movie) movies.get(movieKey);
    
        if (movie == null) {
          movie = requestHandlerChain.getMovie(movieKey);
          movies.put(movieKey, movie);
        } 
        return movie;
      } 
      
      // Other methods ...
      
    }
    

    A handler can implement any action methods in the RemoteModel interface selectively, in either of two ways:

    • If a RemoteModelProxy class calls an action method not implemented by the first handler class, the base RemoteModelRequestHandler class ensures that the call is passed to the next handler in the chain.
    • If a handler in a chain decides it has finished processing an action, it returns directly. Otherwise, it invokes the same action method in the superclass, to pass it to the next handler in the chain
    public class RMSCacheHandler extends RemoteModelRequestHandler {
    
      // ...
    
      public Movie getMovie(String movieKey) 
                            throws ModelException, 
                            ApplicationException {
        IndexEntry indexEntry = 
            rmsAdapter.getIndexEntry(movieKey, 
                IndexEntry.TYPE_MOVIE, IndexEntry.MODE_ANY);
    
        if (indexEntry != null) {
          return rmsAdapter.loadMovie(indexEntry.getRecordId());
        }
        return super.getMovie(movieKey);
      }
      
      // ...
      
    }
    

    Binary Remote Procedure Call over HTTP

    In the model layer, the HTTPCommunicationHandler class in the RemoteModelProxy class invokes remote procedures on the server side through a binary RPC protocol over an HTTP connection. The protocol is defined as follows:

    All RPC requests from the client to the server follow the same basic pattern. The first byte in the stream specifies the action method that the façade session bean on the server side must execute, and the remaining bytes encode a sequence of UTF strings that represent the parameters to be passed to the remote method. The response HTTP stream contains the RPC return value. The formats of the requests and responses are unique to each method, and you have to look at the source code for each to figure out the exact format.

    The RPC codes that go into the first byte of the request stream are defined in the MessageConstants class:

    package com.sun.j2me.blueprints.smartticket.shared.midp;
    
    public final class MessageConstants {
    
      public static final byte OPERATION_LOGIN_USER = 0;
      public static final byte OPERATION_CREATE_ACCOUNT = 1;
      public static final byte OPERATION_UPDATE_ACCOUNT = 2;
      public static final byte OPERATION_GET_THEATERS = 3;
      public static final byte OPERATION_GET_THEATER_SCHEDULE = 4;
      public static final byte OPERATION_GET_MOVIE = 5;
      public static final byte OPERATION_GET_MOVIE_POSTER = 6;
      public static final byte OPERATION_GET_MOVIE_SHOWTIMES = 7;
      public static final byte OPERATION_GET_SEATING_PLAN = 8;
      public static final byte OPERATION_RESERVE_SEATS = 9;
      public static final byte OPERATION_PURCHASE_TICKETS = 10;
      public static final byte OPERATION_CANCEL_SEAT_RESERVATION = 11;
      public static final byte OPERATION_GET_LOCALES = 12;
      public static final byte OPERATION_GET_RESOURCE_BUNDLE = 13;
      public static final byte OPERATION_INITIATE_SYNCHRONIZATION = 14;
      public static final byte OPERATION_SYNCHRONIZE_MOVIE_RATINGS = 15;
      public static final byte OPERATION_COMMIT_MOVIE_RATINGS = 16;
      public static final byte ERROR_NONE = 0;
      public static final byte ERROR_UNKNOWN_OPERATION = 1;
      public static final byte ERROR_SERVER_ERROR = 2;
      public static final byte ERROR_MODEL_EXCEPTION = 3;
      public static final byte ERROR_REQUEST_FORMAT = 4;
      
      private MessageConstants() {}
    }
    

    The two classes that follow illustrate an RPC round trip; an action method of the HTTPCommunicationHandler requests information about a specified movie, and invokes a method of the Movie class to extract the return values from the response stream.

    package com.sun.j2me.blueprints.smartticket.client.midp.model;
    
    public class HTTPCommunicationHandler
      extends RemoteModelRequestHandler {
    
      // ...
      
      public Movie getMovie(String movieKey) 
                            throws ModelException, 
                            ApplicationException {
        HttpConnection connection = null;
        DataOutputStream outputStream = null;
        DataInputStream inputStream = null;
    
        try {
          connection = openConnection();
          updateProgress();
          outputStream = openConnectionOutputStream(connection);
    
          // The RPC request
          outputStream.writeByte(MessageConstants.OPERATION_GET_MOVIE);
          outputStream.writeUTF(movieKey);
          outputStream.close();
          updateProgress();
    
          // unmarshal the return values
          inputStream = openConnectionInputStream(connection);
          Movie movie = Movie.deserialize(inputStream);
          updateProgress();
    
          return movie;
        } catch (IOException ioe) {
          throw new
            ApplicationException(ErrorMessageCodes.ERROR_CANNOT_CONNECT);
        } finally {
          closeConnection(connection, outputStream, inputStream);
        } 
      }
      
      // Other action methods ...
      
    }
    
    package com.sun.j2me.blueprints.smartticket.shared.midp.model;
    
    public class Movie {
      private String primaryKey;
      private String title;
      private String summary;
      private String rating;
      private boolean alreadySeen = false;
      transient private byte[] poster = null;
        
      public static Movie deserialize(DataInputStream 
          dataStream) throws ApplicationException {
        try {
          Movie movie = new Movie();
    
          // Read the RPC response stream
          movie.primaryKey = dataStream.readUTF();
          movie.title = dataStream.readUTF();
          movie.summary = dataStream.readUTF();
          movie.rating = dataStream.readUTF();
          try {
            movie.alreadySeen = dataStream.readBoolean();
          } catch (IOException ioe) {
            movie.alreadySeen = false;
          } 
    
          try {
            return 
                ModelObjectLoader.getInstance().getMovie(movie);
          } catch (ModelException me) {
            throw new ApplicationException();
          } 
        } catch (IOException ioe) {
          throw new ApplicationException(ioe);
        } 
      }
      
      // Other methods ...
      
    }
    

    On the server side, the SmartTicketServlet first determines the action desired from the code in the first byte in the request stream. It then dispatches the request to the appropriate action method through the façade, passing all the RPC parameters remaining in the stream.

    In Smart Ticket, the client and server are tightly coupled. This approach can improve network efficiency because each RPC exchange can be specially designed and optimized. The trade-off, however, is development speed and robustness. Even small changes to the server are likely to force changes in the protocol and the parsing code on the client side too, and potentially in multiple places. Developers need to keep track of all code that might be affected, and update it when necessary. They also need to recompile and redistribute clients oftener than they'd like, which could also lead to errors.

    The Client-Side Thread Model

    The Smart Ticket application uses a sophisticated threading model on the client side, with two important aspects:

    • The MIDP specification requires the CommandListener.commandAction() method to "return immediately" to avoid blocking the UI, so any lengthy operation must be put into another thread.
    • One of the running threads can display a moving gauge indicating the progress of a long action, particularly any that involves remote network operations. The gauge screen can provide impatient users with a button to cancel actions that take too long.

      (Click image to enlarge.)

    You probably noticed earlier that action methods in the UIController class are simply wrappers of the runWithProgress() method, which sets the display to ProgressObserverUI and starts the EventDispatcher thread. The ProgressObserverUI screen displays a gauge and a Stop button which is monitored by the main MIDlet system UI thread. As we described, the EventDispatcher thread eventually delegates the requested action to methods in the model layer. Each of these methods calls the ProgressObserverUI.updateProgress() at certain stages in its execution to tell the user it's making progress.

    public class UIController {
      
      // Action methods ...
      
      public void chooseMovieRequested() {
        runWithProgress(
          new EventDispatcher(
            EventIds.EVENT_ID_CHOOSEMOVIEREQUESTED, 
                mainMenuUI), 
                    getString(UIConstants.PROCESSING), false);
      }
      
      // Action methods ...
      
      public void runWithProgress(Thread thread, String title, 
                                  boolean stoppable) {
        progressObserverUI.init(title, stoppable);
        getDisplay().setCurrent(progressObserverUI);
        thread.start();
      }
      
      class EventDispatcher extends Thread {
    
        // ...
    
        public void run() {
          // Switch -- case statements to delegate
          // actions to the model layer
        }
      }
    }
    
    public class ProgressObserverUI extends Form 
                implements ProgressObserver,
                CommandListener {
    
      private UIController uiController;
      private static final int GAUGE_MAX = 8;
      private static final int GAUGE_LEVELS = 4;
      int current = 0;
      Gauge gauge;
      Command stopCommand;
      boolean stoppable;
      boolean stopped;
    
      public ProgressObserverUI(UIController uiController) {
    
        super("");
    
        gauge = new Gauge("", false, GAUGE_MAX, 0);
        stopCommand = new 
            Command(uiController.getString(UIConstants.STOP), 
                Command.STOP, 10);
    
        append(gauge);
        setCommandListener(this);
      }
    
      public void init(String note, boolean stoppable) {
        gauge.setValue(0);
        setNote(note);
        setStoppable(stoppable);
        stopped = false;
      }
    
      public void setNote(String note) {
        setTitle(note);
      }
    
      public boolean isStoppable() {
        return stoppable;
      }
    
      public void setStoppable(boolean stoppable) {
        this.stoppable = stoppable;
        if (stoppable) {
          addCommand(stopCommand);
        } else {
          removeCommand(stopCommand);
        }
      }
    
      /**
       * Indicates whether the user has stopped the progress.
       * This message should be called before calling update.
       */
      public boolean isStopped() {
        return stopped;
      }
    
      public void updateProgress() {
        current = (current + 1) % GAUGE_LEVELS;
        gauge.setValue(current * GAUGE_MAX / GAUGE_LEVELS);
      }
    
      public void commandAction(Command c, Displayable d) {
        if (c == stopCommand) {
          stopped = true;
        }
      }
    }
    

    Conclusion

    This article introduced the all-new Smart Ticket blueprint v2.0. Several key improvements over the previous versions take advantage of the rich capability of smart clients. Smart Ticket shows you how to implement advanced features using several important design patterns, which we explored briefly. We hope our presentation will get you off to a fast start in the world of end-to-end design patterns!

    Resources





    http://developers.sun.com/techtopics/mobility/midp/articles/smartticket1_2/index.html
    YOLO26算法婴幼儿面部情绪识别目标检测+训练好的模型+2681张数据集+pyqt可视化界面.zip 附训练好的 YOLO 权重与 PyQt 可视化检测界面,页面底部含可视化效果预览,毕设/课设开箱即用。 【数据集概况】 · 检测类别(中文):[哭泣(crying), 开心(happy)] · 总计:2681 张 · 测试集:186 张 · 验证集:0 张 · 训练集:2495 张 【训练曲线与评估图】 【模型训练配置】 参数 | 值 模型 | yolo26n 训练轮数 | 100 epochs 输入尺寸 | 640x640 批次大小 | 24 优化器 | auto 初始学习率 | 0.01 训练设备 【关键指标汇总】 训练了 100 个 epoch,最终轮指标: 指标 | 数值 mAP50 | **0.8069** mAP50-95 | 0.5664 Precision | 0.8700 Recall | 0.7726 train/box_loss | 0.7524 train/cls_loss | 0.4490 val/box_loss | 1.1351 val/cls_loss | 0.7588 【训练过程分析】 训练伊始,模型对 box_loss 和 cls_loss 的下降表现出惊人的效率,前 20 轮迅速将训练损失降至低位,显示了训练集的强大适应性。然而,在第 20 轮之后,loss 下降速度明显放缓,整体趋于平稳。到了 60 轮左右,box_loss 值逐渐接近 0.75,而 cls_loss 则稳定在 0.44 左右。从训练集的 box_loss 从 0.7524 降至 0.7325,能看出来 model 正在逐步优化每个实例的边界框准确性,这一过程在前 40 轮尤为显著。相比之下,cls_loss 从 0.4490 降至 0.4389,尽管变化不大,但整体上表现出了模型对类别的清晰度提升... 使用场景:毕业设计、课程设计、深度学习入门、工业场景落地验证。 立即下载

    相关推荐

    chrome-headless-shell-mac-x64-160.0.8180.0(Canary).zip

    Chrome for Testing 官方测试构建包,内含 Chrome 浏览器、ChromeDriver 与 Chrome Headless Shell,适用于对应平台的自动化测试、Selenium/Playwright 驱动与 CI 环境搭建。解压即用,请按文件名中的平台选择对应版本。

    konica C368(柯尼卡美能达bizhub C368系列打印机驱动)

    1、查看本机 IP,确保电脑和复印机在同一个局域网。 2、安装时 右键以管理员运行 ,旧驱动先卸载干净避免冲突。 3、端口默认:9100(RAW),也可用 LPR。 安装方法: 1. 解压后进入文件夹,64 位运行 `Setup64.exe`,32 位运行 `Setup.exe`。 2. 同意协议 → 选择【安装(网络搜索)】,程序自动扫描局域网内 C368P。 3. 在列表选中对应 IP 的机器,下一步;如果扫不到,切换到【手动设置】,填入复印机 IP。 4. 勾选驱动类型(PCL6),点击安装,等待完成。 5. 安装结束,打印测试页验证。

    烟雾报警器光电散射 Python 源码

    光电式烟雾报警器散射信号与阈值触发模拟源码,含火灾起烟与做饭蒸汽两组序列、六档阈值扫描(报警时刻与误报次数)和权衡图,装好 numpy、matplotlib 直接运行复现。

    EI复现梯级水光互补系统最大化可消纳电量期望短期优化调度模型(Python代码实现)

    内容概要:本文提出了一种针对梯级水光互补系统的短期优化调度模型,旨在最大化可消纳电量期望,通过构建精确的数学优化模型并结合Python编程实现,对水电与光伏发电出力进行协同调度,提升新能源的利用效率与系统运行的稳定性;研究中引入Copula理论对光伏出力的不确定性与风光之间的时空相关性进行建模,提高了功率预测的概率精度与场景生成的科学性,从而增强调度方案在实际复杂环境下的鲁棒性与实用性。; 适合人群:具备电力系统运行与优化基础、掌握Python编程技能,从事新能源调度、多能互补系统建模、可再生能源集成研究的科研人员、工程技术人员及研究生。; 使用场景及目标:①应用于梯级水电站与大型光伏电站的联合运行调度分析;②支撑高比例可再生能源接入背景下的电力系统短期优化决策;③为考虑风光出力不确定性与相关性的多能源互补系统提供从概率预测到优化调度的完整技术路径与代码实现参考。; 阅读建议:建议读者结合文中Copula光伏预测模块与优化调度框架,使用实际气象与运行数据进行代码复现与参数调优,深入理解不确定性建模与优化求解的耦合机制,并可进一步拓展至含储能、负荷响应等多元灵活性资源的综合调度场景研究。

    依赖专家资源的传统机构与依赖数据算法的现代平台,在转化效率上谁更胜一筹?.docx

    依赖专家资源的传统机构与依赖数据算法的现代平台,在转化效率上谁更胜一筹?

    当前全国范围内备案登记的技术转移机构总数大概有多少?.docx

    科易网基于行业知识库+行业大数据+科技资源要素+AI模型,以AI,赋能技术转移、成果转化、技术经理人培训、知识产权管理、区域产业分析与布局、地方科技招商、创新创业大赛等场景,推出科技创新领域的AI工具、场景化服务和数智化解决方案,推动科技创新与产业创新智能化发展。

    电气数据大规模复杂配电网故障溯源数据集

    【电气数据】大规模复杂配电网故障溯源数据集内容概要:本文介绍了名为“大规模复杂配电网故障溯源数据集”的电气数据资源,旨在为电力系统领域的科研人员提供用于故障诊断、状态估计和配电网优化研究的数据支持。该数据集及相关资源涵盖了配电网故障溯源、电力变压器诊断、新能源并网、储能优化调度等多个关键技术方向,并提供了大量基于Matlab/Simulink的仿真代码与模型,如序贯蒙特卡洛模拟法可靠性评估、含分布式电源的配电网重构、最优潮流计算等,具有较强的工程应用价值。资源还配套详细文档、参考文献及运行结果,便于使用者快速理解和复现。; 适合人群:具备电力系统、电气工程或自动化等相关专业背景,从事科研或工程仿真的研究生、高校教师及研发人员。; 使用场景及目标:①开展配电网故障定位、溯源与恢复策略研究;②进行电力系统可靠性评估、优化调度与状态估计算法开发;③复现高水平期刊论文中的仿真案例,支撑科研项目与论文撰写。; 阅读建议:建议读者结合提供的完整资源目录和网盘链接,系统性地查阅相关代码与文献,优先选择与自身研究方向契合的内容进行实践,并通过公众号“荔枝科研社”获取最新资料和技术支持。

    福建省技术转移机构在应对市场竞争时有哪些差异化服务策略?.docx

    福建省技术转移机构在应对市场竞争时有哪些差异化服务策略?

    【SCI一区复现】基于配电网韧性提升的应急移动电源预配置和动态调度(上)-MPS预配置(Matlab代码实现)

    内容概要:本文围绕提升配电网在极端灾害下的韧性,重点研究应急移动电源(MPS)的预配置问题,属于SCI一区级别科研成果的高质量复现。通过构建考虑负荷恢复优先级、网络拓扑连通性、MPS容量与位置约束的混合整数线性规划(MILP)模型,采用Matlab结合优化求解器进行仿真求解,系统实现了灾后配电网关键负荷的快速供电恢复策略设计。文中详尽阐述了建模思路、变量定义、目标函数构成(如最小化未恢复负荷量)及各类物理约束的数学表达,并提供了完整的代码实现流程,具有很强的科研指导性和工程应用参考价值。; 适合人群:电力系统及其自动化、电气工程等相关专业的硕士、博士研究生及科研人员,以及从事电网规划、应急管理、灾害响应等领域的技术人员;具备一定的优化理论基础、电力系统分析知识和Matlab/YALMIP建模能力者更佳。; 使用场景及目标:①用于高水平学术论文(如SCI一区)中关于配电网韧性提升方法的复现、验证与对比分析;②支撑电力部门在灾害预防阶段制定MPS的最优部署方案,提升应急响应能力;③作为“配电网韧性”、“应急电源调度”、“两阶段鲁棒优化”等方向的教学案例或科研项目开发的基础模块。; 阅读建议:建议结合配套Matlab代码逐行解读,重点关注模型中对网络连通性、孤岛运行能力及MPS部署逻辑的数学刻画,熟练掌握YALMIP工具箱的建模技巧与求解器调用方式,并可进一步衔接下半部分的动态调度内容,构建完整的应急电源全时段优化调度体系。

    福建省制造业龙头企业在寻找海外技术时,哪些本地机构能提供支持?.docx

    福建省制造业龙头企业在寻找海外技术时,哪些本地机构能提供支持?

    PostgreSQL 数据库辅助类(要求 Npgsql 7.0 及以上) .NET Framework 4.7.2+ 或 .NET 6+;C# 7.3+

    类别 :方法 数据源: Initialize、Close、DataSource、ConfigureBuilder、CommandTimeout、OnSqlExecuted 参数: CreateParameter(含类型版)、CreateJsonbParameter、CreateArrayParameter、ParamsFrom 执行: ExecuteNonQuery、ExecuteScalar<T>、ExecuteDataTable、ExecuteDataSet、ExecuteList<T>、ExecuteModel<T>、ExecuteDictionaryList、ExecuteColumn<T>、ExecuteReader(均有异步版) 封装: Exists、Count、ExecutePagedDataTable/List、Insert、Update、Delete、Upsert、TableExists、ColumnExists、GetTableNames、GetServerVersion、TestConnection 数据库对象: ExecuteFunctionTable/Scalar、CallProcedure 批量: ExecuteBatch(NpgsqlBatch)、BulkInsert(二进制 COPY)、CopyOut、ToDataTable 事务: ExecuteInTransaction(Async)、OpenTransaction(Async) 其他: Notify、ListenAsync、PgRetry(只读、显式调用)

    考虑分布式电源运行特性的有源配电网智能软开关SOP规划方法【IEEE33节点】(Matlab代码实现)

    内容概要:本文提出了一种考虑分布式电源(DG)运行特性的有源配电网智能软开关(SOP)规划方法,并基于IEEE33节点系统进行了Matlab仿真验证。该方法通过引入SOP替代传统联络开关,实现配电网中功率的灵活调控,提升系统对分布式电源的接纳能力与运行经济性。研究综合考虑了分布式电源的出力波动性与负荷时序特性,构建了以网损最小、电压偏差最小和设备投资运行成本最低为目标的多目标优化模型,并采用智能优化算法进行求解,最终在IEEE33节点标准算例上验证了所提方法在改善配电网电压质量、降低网络损耗和提高新能源消纳水平方面的有效性。; 适合人群:电力系统及其自动化、电气工程等相关专业的研究生、科研人员及从事配电网规划与运行的工程技术人员。; 使用场景及目标:①应用于高比例分布式电源接入背景下的配电网规划与重构;②为智能软开关(SOP)的选址与定容提供科学决策依据;③提升配电网的灵活性、经济性和电能质量,促进新型电力系统建设。; 阅读建议:读者应具备一定的电力系统分析基础和Matlab编程能力,建议结合文中提供的算例数据与代码,复现仿真结果,深入理解SOP的调控机理与优化模型的构建方法。同时可进一步探索不同优化算法、多场景概率分析或与其他主动管理措施(如储能、需求响应)的协调优化策略。

    知识管理四款团队知识库选型对比:Confluence、OmniBox、语雀、Sward适用场景与部署方案分析

    内容概要:本文对2026年主流的四款团队知识库工具Confluence、小黑OmniBox、语雀和Sward进行了横向评测,指出这四款产品并非直接竞争关系,而是分别对应不同组织状态下的解决方案。评测围绕部署方式、权限协作、检索与AI能力三大核心维度展开,强调选型不应仅看功能列表,而应关注资料来源、使用场景与团队特征。Confluence适合已有Atlassian体系的中大型企业,强在权限控制与流程治理;小黑OmniBox聚焦多源资料整合与AI问答,适用于资料分散的团队;语雀以“书本式”结构降低中文团队使用门槛;Sward则主打开源私有化部署,满足内网合规需求。文章最后提供四类典型团队的选型路径,并澄清了“AI万能”“私有化即安全”等常见误区。; 适合人群:企业IT负责人、技术管理者、知识管理相关从业者,尤其是面临知识库选型决策的团队领导者。; 使用场景及目标:①帮助团队根据自身规模、技术栈、数据主权要求和协作习惯选择合适知识库工具;②厘清AI与知识库的关系,避免选型误区;③指导已有系统如何与新工具(如OmniBox)叠加使用,提升知识利用率。; 阅读建议:此评测基于公开资料与产品文档,未进行压力测试或大规模实测,建议结合实际业务场景试用验证,并优先考虑现有系统兼容性与迁移成本。

    高校想通过第三方机构进行成果转化,近年来高校成果转化服务市场的规模有多大?.docx

    科易网基于行业知识库+行业大数据+科技资源要素+AI模型,以AI,赋能技术转移、成果转化、技术经理人培训、知识产权管理、区域产业分析与布局、地方科技招商、创新创业大赛等场景,推出科技创新领域的AI工具、场景化服务和数智化解决方案,推动科技创新与产业创新智能化发展。

    基于深度学习分类的时相关MIMO信道的递归CSI量化(Matlab代码实现)

    内容概要:本文系统阐述了基于深度学习分类的时相关MIMO信道递归CSI量化方法,并提供了完整的Matlab代码实现。该方法针对大规模MIMO系统中因信道状态信息(CSI)反馈开销过大而导致的系统效率下降问题,提出一种结合深度学习与递归结构的量化方案,利用分类网络对时域相关的CSI进行高效压缩,通过递归机制捕捉信道动态的时间连续性特征,显著提升了量化精度与频谱利用率。文中详细介绍了算法设计原理、神经网络架构选型、训练策略设计、损失函数构建及仿真验证流程,展示了在不同信道模型与时变条件下相较于传统量化方法的性能优势。; 适合人群:具备通信工程、信号处理或无线通信领域基础知识,熟悉MIMO系统原理与深度学习基本模型(如RNN、CNN)的研究生、科研人员及工程师,尤其适合从事智能通信、信道建模、CSI反馈优化等相关方向的研究者。; 使用场景及目标:①应用于大规模MIMO和5G/6G系统中的CSI反馈压缩与传输优化;②为时变无线信道环境下的高效信道量化提供基于深度学习的智能化解决方案;③支持科研复现实验,促进先进信号处理技术在通信系统中的融合与创新; 阅读建议:建议读者结合提供的Matlab代码逐模块调试运行,深入理解深度学习模型在信道量化任务中的输入输出设计、网络训练流程与性能评估方式,可尝试在不同信道参数(如多普勒频移、SNR)下进行仿真实验以验证算法鲁棒性与泛化能力。

    RouterOS网桥VLAN实战:从零构建安全隔离的二层虚拟网络

    本文详细讲解了如何在RouterOS上利用网桥和VLAN功能,从零开始构建安全隔离的二层虚拟网络。通过分步实战演示,涵盖核心概念、网桥创建、PVID设置、VLAN规则配置及安全过滤,帮助网络管理员实现办公、访客与服务器网络的逻辑隔离与灵活管理,提升网络安全性。

    u9v0w的博客 509
    上一篇: 端到端J2ME应用开发实例——介绍Smart Ticket
    下一篇: J2ME Web 服务入门
    mobilechannel
    博客等级 码龄22年 36粉丝 431原创
    评论
    成就一亿技术人!
    拼手气红包6.0元
    还能输入1000个字符
     
     条评论被折叠 查看
    添加红包

    请填写红包祝福语或标题

    个

    红包个数最小为10个

    元

    红包金额最低5元

    当前余额3.43元 前往充值 >
    需支付:10.00元
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付元
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值