// start server public void startServer() throws IOException { // Create a UUID for SPP UUID uuid = new UUID(Config.uuid, true); System.out.println(uuid.toString()); // Create the servicve url String connectionString = "btspp://localhost:" + uuid + ";name=Bluetooth SPP Server"; // open server url StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier) Connector.open(connectionString); // Wait for client connection System.out.println("\nServer Started. Waiting for clients to connect..."); while (isRunning) { connection = streamConnNotifier.acceptAndOpen(); System.out.println("Connection opened"); RemoteDevice dev = RemoteDevice.getRemoteDevice(connection); System.out.println("Remote device address: " + dev.getBluetoothAddress()); System.out.println("Remote device name: " + dev.getFriendlyName(true)); inStream = connection.openInputStream(); outStream = connection.openOutputStream(); if ((dev.getFriendlyName(true) == Config.pairedDevice) || true) { new Receiver().start(); new Sender().start(); } } streamConnNotifier.close(); }
private void getTrafficSpots() { controller.showProgressBar(); String uploadWebsite = "http://" + controller.selectedCity.URL + "/php/trafficstatus.cache?dummy=ert43"; String[] ArrayOfData = null; StreamConnection c = null; InputStream s = null; StringBuffer b = new StringBuffer(); String url = uploadWebsite; System.out.print(url); try { c = (StreamConnection) Connector.open(url); s = c.openDataInputStream(); int ch; int k = 0; while ((ch = s.read()) != -1) { System.out.print((char) ch); b.append((char) ch); } // System.out.println("b"+b); try { JSONObject ff1 = new JSONObject(b.toString()); String data1 = ff1.getString("locations"); JSONArray jsonArray1 = new JSONArray(data1); Vector TrafficStatus = new Vector(); for (int i = 0; i < jsonArray1.length(); i++) { System.out.println(jsonArray1.getJSONArray(i).getString(3)); double aDoubleLat = Double.parseDouble(jsonArray1.getJSONArray(i).getString(1)); double aDoubleLon = Double.parseDouble(jsonArray1.getJSONArray(i).getString(2)); System.out.println(aDoubleLat + " " + aDoubleLon); TrafficStatus.addElement( new LocationPointer( jsonArray1.getJSONArray(i).getString(3), (float) aDoubleLon, (float) aDoubleLat, 1, true)); } controller.setCurrentScreen(controller.TrafficSpots(TrafficStatus)); } catch (Exception E) { controller.setCurrentScreen(traf); new Thread() { public void run() { controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO); } }.start(); } } catch (Exception e) { controller.setCurrentScreen(traf); new Thread() { public void run() { controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO); } }.start(); } }
@Override public void dispose() { // temporary pause the console output, until a new console is available again outStreamConnection.getUiPipe().setTarget(new AlwaysPaused()); errStreamConnection.getUiPipe().setTarget(new AlwaysPaused()); stdOut.dispose(); stdErr.dispose(); totalWidget.dispose(); }
private String[] GetDataFromSite() { String uploadWebsite = "http://" + controller.selectedCity.URL + "/cameras/mobile_cam_list.php"; String[] ArrayOfData = null; StreamConnection c = null; InputStream s = null; StringBuffer b = new StringBuffer(); String url = uploadWebsite; System.out.print(url); try { c = (StreamConnection) Connector.open(url); s = c.openDataInputStream(); int ch; int k = 0; while ((ch = s.read()) != -1) { System.out.print((char) ch); b.append((char) ch); } String result = b.toString(); if (!result.equals("")) { ArrayOfData = StringUtil.split(result.toString().trim(), "~~"); if (ArrayOfData.length == 0) { controller.MainMenu(); new Thread() { public void run() { controller.showAlert("Network Error", 0, AlertType.ERROR); } }.start(); } } } catch (Exception e) { System.out.print(e); new Thread() { public void run() { controller.showProgressBar(); } }.start(); // controller.getDisp().setCurrent(this); } return ArrayOfData; }
protected BTGPSLocationProvider() throws LocationException { // TODO: Move this to searchConnect method? // TODO: The problem here is that it searches every time. Slow. Need to try Properties? // TODO: BIG ONE: Should only connect to GPS that isPaired() (from menu). Will // allow some degree of control over which GPS is connects to in classroom. try { da = LocalDevice.getLocalDevice().getDiscoveryAgent(); da.startInquiry(DiscoveryAgent.GIAC, this); } catch (BluetoothStateException e) { throw new LocationException(e.getMessage()); } while (!doneInq) { Thread.yield(); } if (btDevice == null) throw new LocationException("No device found"); String address = btDevice.getBluetoothAddress(); String btaddy = "btspp://" + address; try { StreamConnectionNotifier scn = (StreamConnectionNotifier) Connector.open(btaddy); if (scn == null) throw new LocationException("Bad BT address"); StreamConnection c = scn.acceptAndOpen(); /* This problem below occurred one time for my Holux GPS. The solution was to * remove the device from the Bluetooth menu, then find and pair again. */ if (c == null) throw new LocationException("Failed. Try pairing at menu again"); InputStream in = c.openInputStream(); if (in != null) { gps = new SimpleGPS(in); // c.close(); // TODO: Clean up when done. HOW TO HANDLE IN LOCATION? } } catch (IOException e) { throw new LocationException(e.getMessage()); } // Add itself to SimpleGPS as listener SimpleGPS.addListener(this); }
/** * disconnect the current connection. * * @param connection connection return from {@link #connect()} * @param inputStream input stream opened from <code>connection</code> * @param outputStream output stream opened from <code>connection</code> * @exception IOException if an I/O error occurs while the connection is terminated. */ protected void disconnect( StreamConnection connection, InputStream inputStream, OutputStream outputStream) throws IOException { try { try { inputStream.close(); } finally { try { outputStream.close(); } finally { connection.close(); } } } catch (IOException e) { } catch (NullPointerException e) { } }
/** method to disconnect from the server */ public void disconnect() throws IOException { // if stream connection is present then if (streamConnection != null) { // close all streams dataOutputStream.close(); dataInputStream.close(); streamConnection.close(); } // nullify all stream objects dataOutputStream = null; dataInputStream = null; streamConnection = null; // initiate garbage collector System.gc(); // set the connected flag to false indicating no connection connected = false; }
public void run() { StreamConnection stream = null; InputStream input = null; MDSPushInputStream pushInputStream = null; while (!_stop) { try { // Synchronize here so that we don't end up creating a connection that is never closed. synchronized (this) { // Open the connection once (or re-open after an IOException), so we don't end up // in a race condition, where a push is lost if it comes in before the connection // is open again. We open the url with a parameter that indicates that we should // always use MDS when attempting to connect. int port = RhoConf.getInstance().getInt("push_port"); if (port == 0) port = 100; _notify = (StreamConnectionNotifier) Connector.open(URL + port + ";deviceside=false"); } while (!_stop) { // NOTE: the following will block until data is received. LOG.TRACE("Block push thread until data is recieved"); stream = _notify.acceptAndOpen(); LOG.TRACE("Recieved push data"); try { input = stream.openInputStream(); pushInputStream = new MDSPushInputStream((HttpServerConnection) stream, input); // Extract the data from the input stream. DataBuffer db = new DataBuffer(); byte[] data = new byte[CHUNK_SIZE]; int chunk = 0; while (-1 != (chunk = input.read(data))) { db.write(data, 0, chunk); } processPushMessage(data); // This method is called to accept the push. pushInputStream.accept(); input.close(); stream.close(); data = db.getArray(); } catch (IOException e1) { // A problem occurred with the input stream , however, the original // StreamConnectionNotifier is still valid. System.err.println(e1.toString()); if (input != null) { try { input.close(); } catch (IOException e2) { } } if (stream != null) { try { stream.close(); } catch (IOException e2) { } } } } _notify.close(); _notify = null; } catch (IOException ioe) { LOG.TRACE("Exception thrown by _notify.acceptAndOpen() - exiting push thread"); // Likely the stream was closed. Catches the exception thrown by // _notify.acceptAndOpen() when this program exits. _stop = true; if (_notify != null) { try { _notify.close(); _notify = null; } catch (IOException e) { } } } } }
/** * Method to return the output stream of the connection * * @return OutputStream */ public OutputStream openOutputStream() throws IOException { return connection.openOutputStream(); }
public static OutputStream getStdErr() { return errStreamConnection.getStream(); }
public static OutputStream getStdOut() { return outStreamConnection.getStream(); }
private OutputWidget makeWidget( StreamConnection connection, Composite parent, Color c, int bufSize, boolean showAlways) { OutputWidget widget = new OutputWidget(parent, c, bufSize, showAlways, this); connection.getUiPipe().setTarget(widget); return widget; }
/** * Get the list of suites for the user to install. The suites that are listed are the links on a * web page that end with .jad. */ public void run() { StreamConnection conn = null; InputStreamReader in = null; String errorMessage; long startTime; startTime = System.currentTimeMillis(); try { parent.displayProgressForm( Resource.getString(ResourceConstants.AMS_DISC_APP_GET_INSTALL_LIST), "", url, 0, Resource.getString(ResourceConstants.AMS_GRA_INTLR_CONN_GAUGE_LABEL)); conn = (StreamConnection) Connector.open(url, Connector.READ); in = new InputStreamReader(conn.openInputStream()); try { parent.updateProgressForm( "", 0, Resource.getString(ResourceConstants.AMS_DISC_APP_GAUGE_LABEL_DOWNLOAD)); parent.installList = SuiteDownloadInfo.getDownloadInfoFromPage(in); if (parent.installList.size() > 0) { parent.installListBox = new List( Resource.getString(ResourceConstants.AMS_DISC_APP_SELECT_INSTALL), Choice.IMPLICIT); // Add each suite for (int i = 0; i < parent.installList.size(); i++) { SuiteDownloadInfo suite = (SuiteDownloadInfo) installList.elementAt(i); parent.installListBox.append(suite.label, (Image) null); } parent.installListBox.addCommand(parent.backCmd); parent.installListBox.addCommand(parent.installCmd); parent.installListBox.setCommandListener(parent); /* * We need to prevent "flashing" on fast development * platforms. */ while (System.currentTimeMillis() - parent.lastDisplayChange < GraphicalInstaller.ALERT_TIMEOUT) ; parent.display.setCurrent(parent.installListBox); return; } errorMessage = Resource.getString(ResourceConstants.AMS_DISC_APP_CHECK_URL_MSG); } catch (IllegalArgumentException ex) { errorMessage = Resource.getString(ResourceConstants.AMS_DISC_APP_URL_FORMAT_MSG); } catch (Exception ex) { errorMessage = ex.getMessage(); } } catch (Exception ex) { errorMessage = Resource.getString(ResourceConstants.AMS_DISC_APP_CONN_FAILED_MSG); } finally { if (parent.progressForm != null) { // end the background thread of progress gauge. Gauge progressGauge = (Gauge) parent.progressForm.get(parent.progressGaugeIndex); progressGauge.setValue(Gauge.CONTINUOUS_IDLE); } try { conn.close(); in.close(); } catch (Exception e) { if (Logging.REPORT_LEVEL <= Logging.WARNING) { Logging.report(Logging.WARNING, LogChannels.LC_AMS, "close threw an Exception"); } } } Alert a = new Alert( Resource.getString(ResourceConstants.ERROR), errorMessage, null, AlertType.ERROR); a.setTimeout(Alert.FOREVER); parent.display.setCurrent(a, parent.urlTextBox); }
/** Implementation of Thread. */ public void run() { StreamConnection connection = null; try { _screen.updateDisplay("Opening Connection..."); String url = "socket://" + _screen.getHostFieldText() + ":44444;interface=wifi" + (_screen.isDirectTCP() ? ";deviceside=true" : ""); connection = (StreamConnection) Connector.open(url); _screen.updateDisplay("Connection with " + _screen.getHostFieldText() + " established."); _in = connection.openInputStream(); _out = new OutputStreamWriter(connection.openOutputStream()); // Send the HELLO string. // send("Hello from BlackBerry 9860."); // send("Hello from BlackBerry 9860."); send(AzrRP_Screen.getMsg()); // Execute further data exchange here... // send("Bye"); _screen.updateDisplay("Done!"); } catch (IOException e) { System.err.println(e.toString()); } finally { _screen.setThreadRunning(false); try { _in.close(); } catch (IOException ioe) { } try { _out.close(); AzrRP_Screen.setMsg(null); } catch (IOException ioe) { } try { connection.close(); } catch (IOException ioe) { } } }