Package javax.microedition.io

Examples of javax.microedition.io.StreamConnection


      int cut = url.indexOf('#');

//      System.out.println("");
//      System.out.println("Requesting: " + url);
     
      StreamConnection con = (StreamConnection) Connector.open(
          cut == -1 ? url : url.substring(0, cut),
              post ? Connector.READ_WRITE : Connector.READ);

      screen.setStatus(type == SystemRequestHandler.TYPE_IMAGE ? "Loading Image" :
          "Requesting");

      int contentLength = -1;

      if (con instanceof HttpConnection) {
        HttpConnection httpCon = (HttpConnection) con;
        if (post) {
          httpCon.setRequestMethod("POST");
          httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        }
        httpCon.setRequestProperty("User-Agent", browser.userAgent);
        httpCon.setRequestProperty("X-Screen-Width", ""+screen.getWidth());
        httpCon.setRequestProperty("Connection", "Keep-Alive");
        httpCon.setRequestProperty("Accept-Charset", "utf-8");

        String cookie = browser.getCookies(url);
        if (cookie != null) {
//          System.out.println("Setting Cookie: " + cookie);
          httpCon.setRequestProperty("Cookie", cookie);
        }

        if (post && requestData != null) {
          OutputStream os = httpCon.openOutputStream();
          os.write(requestData);
          os.close();
//          System.out.println("Postdata\n" + new String(requestData));
        }

//        System.out.println("receiving:");
        contentLength = (int) httpCon.getLength();
        int headerIndex = 0;
        while (true){
          String name = httpCon.getHeaderFieldKey(headerIndex);
          if (name == null) {
            break;
          }
          name = name.toLowerCase();
//          System.out.println(name + ": " + httpCon.getHeaderField(headerIndex));
         
          if ("content-type".equals(name)) {
            String value = httpCon.getHeaderField(headerIndex);
            if (value.indexOf("vnd.sun.j2me.app-descriptor") != -1) {
              browser.platformRequest(url);
              return;
            }
            int eq = value.indexOf ("harset=");
            if (eq != -1) {
              encoding = value.substring(eq + 7).trim();
            }
          } else if ("set-cookie".equals(name)) {
            String cName = "";
            String cValue = "";
            String cHost = httpCon.getHost();
            String cPath = "";
            String cExpires = null;
            String cSecure = null;
            String[] parts = Util.split(
                httpCon.getHeaderField(headerIndex), ';');
            for (int i = 0; i < parts.length; i++){
              String part = parts[i];
              cut = part.indexOf('=');
              if (cut == -1) {
                continue;
              }
              String key = part.substring(0, cut).trim();
              String value = part.substring(cut + 1).trim();
              if (i == 0) {
                cName = key;
                cValue = value;
              } else {
                key = key.toLowerCase();
                if ("host".equals(key)) {
                  cHost = value;
                } else if ("path".equals(key)) {
                  cPath = value;
                } else if ("expires".equals(key)) {
                  cExpires = value;
                } else if ("secure".equals(key)) {
                  cSecure = value;
                }
              }          
            }
            browser.setCookie(cHost, cPath, cName, cValue, cExpires, cSecure);
          }
          headerIndex++;
        }

        int responseCode = httpCon.getResponseCode();
//        System.out.println("Response Code: " + httpCon.getResponseCode());
        if (responseCode >= 300 && responseCode <= 310) {
          String location = httpCon.getHeaderField("Location");
          if (location != null) {
//            System.out.println("Redirecting to: " + location);
          screen.htmlWidget.setUrl(location);
            browser.requestResource(screen.htmlWidget, method, location,
                type, requestData);
            return;
          }
        }

        if (responseCode != 200 && !page) {
          throw new IOException("HTTP Error " + responseCode);
        }
      }

      byte [] responseData;

      InputStream is = con.openInputStream();
      if (is == null) {
        responseData = new byte[0];
      } else {
        if (contentLength == -1) {
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          byte [] buf = new byte [2048];

          while (true) {
            screen.setStatus(total / 1000 + "k");
            int len = is.read(buf, 0, 2048);
            if (len <= 0) {
              break;
            }
            total += len;
            baos.write(buf, 0, len);
          }
          responseData = baos.toByteArray();
        } else {
          responseData = new byte[contentLength];
          int pos = 0;
          while (pos < contentLength) {
            screen.setStatus(total / 1000 + "k");
            int len = is.read(responseData, pos,
                Math.min(contentLength - pos, 4096));
            if (len <= 0) {
              break;
            }
            pos += len;
            total += len;
          }
        }
      }
      con.close();

      switch (type) {
        case SystemRequestHandler.TYPE_DOCUMENT:

          String tmp = new String(responseData, 0, Math.min(responseData.length,
View Full Code Here


    /**
     * Implementation of Thread.
     */
    public void run() {
        StreamConnection connection = null;

        try {
            _screen.updateDisplay("Opening Connection...");
            final String url =
                    "socket://" + _screen.getHostFieldText() + ":44444"
                            + (_screen.isDirectTCP() ? ";deviceside=true" : "");
            connection = (StreamConnection) Connector.open(url);
            _screen.updateDisplay("Connection open");

            _in = connection.openInputStream();

            _out = new OutputStreamWriter(connection.openOutputStream());

            // Send the HELLO string.
            exchange("Hello");

            // Execute further data exchange here...

            // Send the GOODBYE string.
            exchange("Goodbye and farewell");

            _screen.updateDisplay("Done!");
        } catch (final IOException e) {
            System.err.println(e.toString());
        } finally {
            _screen.setThreadRunning(false);

            try {
                _in.close();
            } catch (final IOException ioe) {
            }
            try {
                _out.close();
            } catch (final IOException ioe) {
            }
            try {
                connection.close();
            } catch (final IOException ioe) {
            }
        }
    }
View Full Code Here

        /**
         * @see java.lang.Runnable#run()
         */
        public void run() {
            try {
                StreamConnection connection = null;
                DataOutputStream os = null;
                DataInputStream is = null;
                try {
                    final UUID uuid = new UUID(_uuid);
                    final LocalDevice local = LocalDevice.getLocalDevice();
                    updateStatus("[SERVER] Device Address: "
                            + local.getBluetoothAddress());
                    updateStatus("[SERVER] Device Name: "
                            + local.getFriendlyName());
                    updateStatus("[SERVER] Listening for Client...");

                    // Open a connection and wait for client requests
                    final StreamConnectionNotifier service =
                            (StreamConnectionNotifier) Connector
                                    .open("btspp://localhost:" + uuid
                                            + ";name=" + SERVICE_NAME_SPP);
                    connection = service.acceptAndOpen();
                    updateStatus("[SERVER] SPP session created");

                    // Read a message
                    is = connection.openDataInputStream();
                    final byte[] buffer = new byte[1024];
                    final int readBytes = is.read(buffer);
                    final String receivedMessage =
                            new String(buffer, 0, readBytes);
                    updateStatus("[SERVER] Message received: "
                            + receivedMessage);

                    // Send a message
                    final String message = "\nJSR-82 SERVER says hello!";
                    updateStatus("[SERVER] Sending message....");
                    os = connection.openDataOutputStream();
                    os.write(message.getBytes());
                    os.flush();
                } finally {
                    os.close();
                    is.close();
View Full Code Here

        /**
         * @see java.lang.Runnable#run()
         */
        public void run() {
            try {
                StreamConnection connection = null;
                DataOutputStream os = null;
                DataInputStream is = null;
                try {
                    // Send the server a request to open a connection
                    connection = (StreamConnection) Connector.open(_url);
                    updateStatus("[CLIENT] SPP session created");

                    // Send a message to the server
                    final String message = "\nJSR-82 CLIENT says hello!";
                    updateStatus("[CLIENT] Sending message....");
                    os = connection.openDataOutputStream();
                    os.write(message.getBytes());
                    os.flush();

                    // Read a message
                    is = connection.openDataInputStream();
                    final byte[] buffer = new byte[1024];
                    final int readBytes = is.read(buffer);
                    final String receivedMessage =
                            new String(buffer, 0, readBytes);
                    updateStatus("[CLIENT] Message received: "
                            + receivedMessage);
                } finally {
                    os.close();
                    is.close();
                    connection.close();
                    updateStatus("[CLIENT] SPP session closed");
                }
            } catch (final IOException ioe) {
                BluetoothJSR82Demo.errorDialog(ioe.toString());
            }
View Full Code Here

            // Wait for the app's event thread to start
            while (!HTTPPushDemo.this.hasEventThread()) {
                Thread.yield();
            }

            StreamConnection stream = null;
            InputStream input = null;
            MDSPushInputStream pushInputStream = null;

            try {
                _notify =
                        (StreamConnectionNotifier) Connector.open(URL
                                + ";deviceside=false");

                while (!_stop) {
                    // NOTE: the following will block until data is received
                    stream = _notify.acceptAndOpen();

                    try {
                        input = stream.openInputStream();
                        pushInputStream =
                                new MDSPushInputStream(
                                        (HttpServerConnection) stream, input);

                        // Extract the data from the input stream
                        final DataBuffer db = new DataBuffer();
                        byte[] data = new byte[CHUNK_SIZE];
                        int chunk = 0;

                        while (-1 != (chunk = input.read(data))) {
                            db.write(data, 0, chunk);
                        }

                        updateMessage(data);

                        // If the push server has application level reliabilty
                        // enabled, this method call will acknowledge receipt
                        // of the push.
                        pushInputStream.accept();

                        data = db.getArray();
                    } catch (final IOException ioe) {
                        // A problem occurred with the input stream , however,
                        // the original
                        // StreamConnectionNotifier is still valid.
                        errorDialog(ioe.toString());
                    } finally {
                        if (input != null) {
                            try {
                                input.close();
                            } catch (final IOException ioe) {
                            }
                        }

                        if (stream != null) {
                            try {
                                stream.close();
                            } catch (final IOException ioe) {
                            }
                        }
                    }
                }
View Full Code Here

        try {
         
            /** Open the server and block on connection */
          conNotifier = (StreamConnectionNotifier) Connector.open(url, Connector.READ, true);
          constants.info( "Blocking, waiting... ");
          final StreamConnection connection = (StreamConnection) conNotifier.acceptAndOpen();
            constants.info( "Incomming connection...");
           
            doConnReply( connection );
            conNotifier.close();
           
View Full Code Here

        try {
         
            /** Open the server and block on connection */
          conNotifier = (StreamConnectionNotifier) Connector.open(url, Connector.READ, true);
          constants.info( "Blocking, waiting... ");
          final StreamConnection connection = (StreamConnection) conNotifier.acceptAndOpen();
            constants.info( "Incomming connection...");
           
            doConnReply( connection );
            conNotifier.close();
           
View Full Code Here

TOP

Related Classes of javax.microedition.io.StreamConnection

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.