Package javax.microedition.io

Examples of javax.microedition.io.Connection


     *
     * @return true if the URL points to a MIDlet suite
     */

    private boolean isMidletSuiteUrl(String url) {
        Connection conn = null;
        HttpConnection httpConnection = null;
        String profile;
        int space;
        String configuration;
        String locale;
        int responseCode;
        String mediaType;

        try {
            conn = Connector.open(url, Connector.READ);
        } catch (IllegalArgumentException e) {
            return false;
        } catch (IOException e) {
            return false;
        }

        try {
            if (!(conn instanceof HttpConnection)) {
                // only HTTP or HTTPS are supported
                return false;
            }

            httpConnection = (HttpConnection)conn;

            httpConnection.setRequestMethod(HttpConnection.HEAD);

            httpConnection.setRequestProperty("Accept", "*/*");

            profile = System.getProperty("microedition.profiles");
            space = profile.indexOf(' ');
            if (space != -1) {
                profile = profile.substring(0, space);
            }

            configuration = System.getProperty("microedition.configuration");
            httpConnection.setRequestProperty("User-Agent",
                "Profile/" + profile + " Configuration/" + configuration);

            httpConnection.setRequestProperty("Accept-Charset",
                                              "UTF-8, ISO-8859-1");

            /* locale can be null */
            locale = System.getProperty("microedition.locale");
            if (locale != null) {
                httpConnection.setRequestProperty("Accept-Language", locale);
            }

            responseCode = httpConnection.getResponseCode();

            if (responseCode != HttpConnection.HTTP_OK) {
                return false;
            }

            mediaType = Util.getHttpMediaType(httpConnection.getType());
            if (mediaType == null) {
                return false;
            }

            if (mediaType.equals(JAD_MT) || mediaType.equals(JAR_MT_1) ||
                    mediaType.equals(JAR_MT_2)) {
                return true;
            }

            return false;
        } catch (IOException ioe) {
            return false;
        } finally {
            try {
                conn.close();
            } catch (Exception e) {
                if (Logging.REPORT_LEVEL <= Logging.WARNING) {
                    Logging.report(Logging.WARNING, LogChannels.LC_AMS,
                                  "Exception while closing  connection");
                }
View Full Code Here


    public Connection open(boolean timeouts)
        throws IOException, SecurityException
    {
  String url = getURL();
  url.length();    // Throw NPE if null
        Connection conn = Connector.open(url, Connector.READ, timeouts);
        return conn;
    }   
View Full Code Here

            String[] extraFieldValues, String[] acceptableTypes,
            boolean sendAcceptableTypes, boolean allowNoMediaType,
            OutputStream output, String[] encoding, int invalidURLCode,
            int serverNotFoundCode, int resourceNotFoundCode,
            int invalidMediaTypeCode) throws IOException {
        Connection conn = null;
        StringBuffer acceptField;
        int responseCode;
        String retryAfterField;
        int retryInterval;
        String mediaType;

        try {
            for (; ; ) {
                try {
                    conn = Connector.open(url, Connector.READ);
                } catch (IllegalArgumentException e) {
                    throw new InvalidJadException(invalidURLCode, url);
                } catch (ConnectionNotFoundException e) {
                    // protocol not found
                    throw new InvalidJadException(invalidURLCode, url);
                }

                if (!(conn instanceof HttpConnection)) {
                    // only HTTP or HTTPS are supported
                    throw new InvalidJadException(invalidURLCode, url);
                }

                httpConnection = (HttpConnection)conn;

                if (extraFieldKeys != null) {
                    for (int i = 0; i < extraFieldKeys.length &&
                                    extraFieldKeys[i] != null; i++) {
                        httpConnection.setRequestProperty(extraFieldKeys[i],
                                                          extraFieldValues[i]);
                    }
                }

                // 256 is given to avoid resizing without adding lengths
                acceptField = new StringBuffer(256);

                if (sendAcceptableTypes) {
                    // there must be one or more acceptable media types
                    acceptField.append(acceptableTypes[0]);
                    for (int i = 1; i < acceptableTypes.length; i++) {
                        acceptField.append(", ");
                        acceptField.append(acceptableTypes[i]);
                    }
                } else {
                    /* Send at least a wildcard to satisfy WAP gateways. */
                    acceptField.append("*/*");
                }

                httpConnection.setRequestProperty("Accept",
                                                  acceptField.toString());
                httpConnection.setRequestMethod(HttpConnection.GET);

                if (state.username != null &&
                    state.password != null) {
                    httpConnection.setRequestProperty("Authorization",
                        formatAuthCredentials(state.username,
                                              state.password));
                }

                if (state.proxyUsername != null &&
                    state.proxyPassword != null) {
                    httpConnection.setRequestProperty("Proxy-Authorization",
                        formatAuthCredentials(state.proxyUsername,
                                              state.proxyPassword));
                }

                try {
                    responseCode = httpConnection.getResponseCode();
                } catch (IOException ioe) {
                    if (httpConnection.getHost() == null) {
                        throw new InvalidJadException(invalidURLCode, url);
                    }

                    throw new InvalidJadException(serverNotFoundCode, url);
                }

                if (responseCode != HttpConnection.HTTP_UNAVAILABLE) {
                    break;
                }

                retryAfterField = httpConnection.getHeaderField("Retry-After");
                if (retryAfterField == null) {
                    break;
                }

                try {
                    /*
                     * see if the retry interval is in seconds, and
                     * not an absolute date
                     */
                    retryInterval = Integer.parseInt(retryAfterField);
                    if (retryInterval > 0) {
                        if (retryInterval > 60) {
                            // only wait 1 min
                            retryInterval = 60;
                        }

                        Thread.sleep(retryInterval * 1000);
                    }
                } catch (InterruptedException ie) {
                    // ignore thread interrupt
                    break;
                } catch (NumberFormatException ne) {
                    // ignore bad format
                    break;
                }

                httpConnection.close();

                if (state.stopInstallation) {
                    postInstallMsgBackToProvider(
                        OtaNotifier.USER_CANCELLED_MSG);
                    throw new IOException("stopped");
                }
            } // end for

            if (responseCode == HttpConnection.HTTP_NOT_FOUND) {
                throw new InvalidJadException(resourceNotFoundCode);
            }

            if (responseCode == HttpConnection.HTTP_NOT_ACCEPTABLE) {
                throw new InvalidJadException(invalidMediaTypeCode, "");
            }

            if (responseCode == HttpConnection.HTTP_UNAUTHORIZED) {
                // automatically throws the correct exception
                checkIfBasicAuthSupported(
                     httpConnection.getHeaderField("WWW-Authenticate"));

                state.exception =
                    new InvalidJadException(InvalidJadException.UNAUTHORIZED);
                return 0;
            }

            if (responseCode == HttpConnection.HTTP_PROXY_AUTH) {
                // automatically throws the correct exception
                checkIfBasicAuthSupported(
                     httpConnection.getHeaderField("WWW-Authenticate"));

                state.exception =
                    new InvalidJadException(InvalidJadException.PROXY_AUTH);
                return 0;
            }

            if (responseCode != HttpConnection.HTTP_OK) {
                throw new IOException("Failed to download " + url +
                                      " HTTP response code: " + responseCode);
            }

            mediaType = Util.getHttpMediaType(httpConnection.getType());

            if (mediaType != null) {
                boolean goodType = false;

                for (int i = 0; i < acceptableTypes.length; i++) {
                    if (mediaType.equals(acceptableTypes[i])) {
                        goodType = true;
                        break;
                    }
                }

                if (!goodType) {
                    throw new InvalidJadException(invalidMediaTypeCode,
                                                  mediaType);
                }
            } else if (!allowNoMediaType) {
                throw new InvalidJadException(invalidMediaTypeCode, "");
            }

            if (encoding != null) {
                encoding[0] = getCharset(httpConnection.getType());
            }

            httpInputStream = httpConnection.openInputStream();
            return transferData(httpInputStream, output, MAX_DL_SIZE);
        } finally {
            // Close the streams or connections this method opened.
            try {
                httpInputStream.close();
            } catch (Exception e) {
                if (Logging.REPORT_LEVEL <= Logging.WARNING) {
                    Logging.report(Logging.WARNING, LogChannels.LC_AMS,
                    "stream close  threw an Exception");
                }
            }

            try {
                conn.close();
            } catch (Exception e) {
                if (Logging.REPORT_LEVEL <= Logging.WARNING) {
                    Logging.report(Logging.WARNING, LogChannels.LC_AMS,
                    "connection close  threw an Exception");
                }
View Full Code Here

    if (colon < 1) {
      throw new IllegalArgumentException("no : in URL");
    }
    String scheme = uri.substring(0, colon);
    ConnectionFactory prov = getConnectionFactory(scheme);
    Connection ret = null;
    if (prov != null) {
      ret = prov.createConnection(uri, mode, timeouts);
    }
    if (ret == null) {
      try {
View Full Code Here

   *         found.
   * @throws IllegalArgumentException if the given uri is invalid
   * @return A <tt>DataInputStream</tt> to the given URI
   */
  public DataInputStream openDataInputStream(String name) throws IOException {
    Connection conn = open(name, READ);
    if (!(conn instanceof InputConnection)) {
      try {
        conn.close();
      }
      catch (IOException e) {
      }
      throw new IOException(
          "Connection does not implement InputConnection:"
              + conn.getClass());
    }
    return ((InputConnection) conn).openDataInputStream();
  }
View Full Code Here

   * @throws IllegalArgumentException if the given uri is invalid
   * @return A <tt>DataOutputStream</tt> to the given URI
   */
  public DataOutputStream openDataOutputStream(String name)
      throws IOException {
    Connection conn = open(name, WRITE);
    if (!(conn instanceof OutputConnection)) {
      try {
        conn.close();
      }
      catch (IOException e) {
      }
      throw new IOException(
          "Connection does not implement OutputConnection:"
              + conn.getClass());
    }
    return ((OutputConnection) conn).openDataOutputStream();
  }
View Full Code Here

   *         found.
   * @throws IllegalArgumentException if the given uri is invalid
   * @return A <tt>OutputStream</tt> to the given URI
   */
  public OutputStream openOutputStream(String name) throws IOException {
    Connection conn = open(name, WRITE);
    if (!(conn instanceof OutputConnection)) {
      try {
        conn.close();
      }
      catch (IOException e) {
      }
      throw new IOException(
          "Connection does not implement OutputConnection:"
              + conn.getClass());
    }
    return ((OutputConnection) conn).openOutputStream();
  }
View Full Code Here

        /**
         * @see java.lang.Runnable#run()
         */
        public void run() {
            try {
                Connection connection = null;
                OutputStream outputStream = null;
                Operation putOperation = null;
                ClientSession cs = null;
                try {
                    // Send a request to the server to open a connection
                    connection = Connector.open(_url);
                    cs = (ClientSession) connection;
                    cs.connect(null);
                    updateStatus("[CLIENT] OPP session created");

                    // Send a file with meta data to the server
                    final byte filebytes[] = "[CLIENT] Hello..".getBytes();
                    final HeaderSet hs = cs.createHeaderSet();
                    hs.setHeader(HeaderSet.NAME, "test.txt");
                    hs.setHeader(HeaderSet.TYPE, "text/plain");
                    hs.setHeader(HeaderSet.LENGTH, new Long(filebytes.length));

                    putOperation = cs.put(hs);
                    updateStatus("[CLIENT] Pushing file: " + "test.txt");
                    updateStatus("[CLIENT] Total file size: "
                            + filebytes.length + " bytes");

                    outputStream = putOperation.openOutputStream();
                    outputStream.write(filebytes);
                    updateStatus("[CLIENT] File push complete");
                } finally {
                    outputStream.close();
                    putOperation.close();
                    cs.disconnect(null);
                    connection.close();
                    updateStatus("[CLIENT] Connection Closed");
                }
            } catch (final Exception e) {
                BluetoothJSR82Demo.errorDialog(e.toString());
            }
View Full Code Here

            final String dirURL = dirURLs[dirURLIndex];
            if (dirURL == null) {
                continue;
            }

            Connection con;
            try {
                con = Connector.open(dirURL);
            } catch (final Exception e) {
                exceptions[dirURLIndex] = e;
                continue;
            }

            try {
                final FileConnection fcon = (FileConnection) con;
                if (!fcon.exists()) {
                    throw new IOException("directory does not exist");
                } else if (!fcon.isDirectory()) {
                    throw new IOException("not a directory");
                }

                for (int i = 0; i < SONG_FILENAMES.length; i++) {
                    final String filename = SONG_FILENAMES[i];
                    final String fileURL = fcon.getURL() + filename;

                    Connection con2;
                    try {
                        con2 = Connector.open(fileURL);
                    } catch (final Exception e) {
                        throw new IOException("unable to open connection to "
                                + fileURL + ": " + e);
                    }

                    try {
                        final FileConnection fcon2 = (FileConnection) con2;
                        if (fcon2.exists()) {
                            continue;
                        }

                        try {
                            fcon2.create();
                        } catch (final Exception e) {
                            throw new IOException("unable to create " + fileURL
                                    + ": " + e);
                        }

                        final String resourcePath = "/sounds/" + filename;
                        copyCODResourceToFileConnection(resourcePath, fcon2);
                    } finally {
                        try {
                            con2.close();
                        } catch (final Exception e) {
                        }
                    }
                }
View Full Code Here

            if (dirURL == null) {
                continue;
            }

            // Open a connection to the folder so that we can list its files
            Connection con;
            try {
                con = Connector.open(dirURL);
            } catch (final Exception e) {
                System.err.println("WARNING: unable to open connection to "
                        + dirURL + ": " + e);
                continue; // Skip this directory
            }

            try {
                final FileConnection fcon = (FileConnection) con;
                if (!fcon.isDirectory()) {
                    continue; // Not a directory, so skip it
                }

                // Search for files whose names end with ".mp3" and add them to
                // the playlist
                Enumeration enumeration;
                try {
                    enumeration = fcon.list();
                } catch (final Exception e) {
                    System.err.println("WARNING: unable to list files in "
                            + dirURL + ": " + e);
                    continue; // Skip this directory
                }

                while (enumeration.hasMoreElements()) {
                    final String filename = (String) enumeration.nextElement();
                    if (filename != null
                            && filename.toLowerCase().endsWith(".mp3")) {
                        final String fileURL = fcon.getURL() + filename;
                        final String name =
                                filename.substring(0, filename.length() - 4);
                        final PlaylistEntry playlistEntry =
                                new PlaylistEntry(fileURL, name);
                        vector.addElement(playlistEntry);
                    }
                }
            } finally {
                try {
                    con.close();
                } catch (final Exception e) {
                }
            }
        }
View Full Code Here

TOP

Related Classes of javax.microedition.io.Connection

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.