Example usage for java.net SocketException printStackTrace

List of usage examples for java.net SocketException printStackTrace

Introduction

In this page you can find the example usage for java.net SocketException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.rifidi.emulator.reader.alien.heartbeat.HeartbeatController.java

/**
 * Send out a heartbeat//w w  w  . jav  a  2s. c om
 */
private void broadcast() {
    String retString = "<Alien-RFID-Reader-Heartbeat>\n" + "  <ReaderName>Alien RFID Reader</ReaderName>\n"
            + "  <ReaderType>Alien RFID Tag Reader, Model: ALR-9800(Four Antenna / Multi-Protocol / 915 Mhz)"
            + "</ReaderType>\n" + "  <IPAddress>" + asr.getCommandIP() + "</IPAddress>\n" + "  <CommandPort>"
            + asr.getCommandPort() + "</CommandPort>\n" + "  <HeartbeatTime>" + this.timeInMs / 1000
            + "</HeartbeatTime>\n" + "  <MACAddress>00:00:00:00:00:00</MACAddress>\n"
            + "</Alien-RFID-Reader-Heartbeat>\n";

    try {
        logger.debug("Attempting to send heartbeat...");
        DatagramSocket sock = new DatagramSocket(bindingPort);
        InetAddress ia = InetAddress.getByName(broadcastAddr);
        sock.setBroadcast(true);
        DatagramPacket p = new DatagramPacket(retString.getBytes(), retString.getBytes().length, ia,
                broadcastPort);
        sock.send(p);
        sock.disconnect();
        sock.close();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:se.kth.android.FrameWork.SynchronizedTime.java

void Sync() {
    try {// w  w  w  .  j a  va2s  .  c o  m
        InetAddress hostAddr = InetAddress.getByName(ntpServer);

        try {
            client.open();
        } catch (SocketException e1) {
            e1.printStackTrace();
        }

        info = client.getTime(hostAddr);
        info.computeDetails();

        String s = "S;" + info.getMessage().getOriginateTimeStamp().ntpValue() + ";"
                + info.getMessage().getReceiveTimeStamp().ntpValue() + ";"
                + info.getMessage().getTransmitTimeStamp().ntpValue() + ";" + info.getReturnTime() + "\n";
        logFile.write(s.getBytes());

        // Values in nanoseconds
        if (returnTime == 0) {
            offsetValue = info.getOffset();
        }
        //
        //offsetValue =info.getOffset();
        delayValue = info.getDelay();//TimeStamp.fromNtpToNanos(info.getDelay());
        returnTime = info.getReturnTime();//TimeStamp.fromNtpToNanos(info.getReturnTime())-startNanoTimeLocal;

        if (offsetValue == 0)
            return;

        if (delayValue < shortestDelay * 3) {
            //offsetValue = (offsetValue*9 + info.getOffset())/10;//TimeStamp.fromNtpToNanos(info.getOffset());
            offsetValue = info.getOffset();//(offsetValue*9 + info.getOffset())/10;//TimeStamp.fromNtpToNanos(info.getOffset());
            for (int i = 1; i < NONTPO; i++) {
                ntpoffsets[i - 1] = ntpoffsets[i];
            }
            ntpoffsets[NONTPO - 1] = new NTPOffsets(delayValue, offsetValue, returnTime);
        }

        p = new Parameters();

        //fit(ntpoffsets,p);

    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:com.cheesmo.nzb.client.NNTPConnection.java

public boolean downloadSegment(String group, String string, String downloadName) {
    try {//from   w  w  w.j av  a2  s  . c o  m
        tryConnect();
        client.selectNewsgroup(group);
        Reader reader = client.retrieveArticleBody(string);

        if (reader != null) {
            FileOutputStream fos = new FileOutputStream(
                    config.getCacheDir() + java.io.File.separator + downloadName);
            char[] buffer = new char[512];
            int charsRead = reader.read(buffer);
            while (charsRead > -1 && client.isConnected()) {
                fos.write(Charset.forName("ISO-8859-1").encode(CharBuffer.wrap(buffer, 0, charsRead)).array());
                charsRead = reader.read(buffer);
            }

            if (!client.isConnected()) {
                System.out.println("Client disconnected.");
            }
            reader.close();
            fos.flush();
            fos.close();
            return true;
        } else {
            //System.out.println("Problem retrieving " + string);
        }

    } catch (SocketException e) {
        System.out.println("Client disconnected.");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

From source file:nacho.tfg.blepresencetracker.MyFirebaseInstanceIDService.java

/**
 * Persist token to third-party servers.
 *
 * Modify this method to associate the user's FCM InstanceID token with any server-side account
 * maintained by your application.//  w w w. ja  va  2s  .c o  m
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(String token) {
    // Add custom implementation, as needed.
    Intent intent = new Intent(ACTION_SHOW_TOKEN);
    intent.putExtra("token", token);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

    AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Boolean doInBackground(String... params) {
            String data = params[0];
            String ip = "192.168.4.1";
            int port = 7777;
            try {
                Socket socket = new Socket(ip, port);
                while (!socket.isConnected()) {

                }

                OutputStream out = socket.getOutputStream();
                PrintWriter output = new PrintWriter(out);

                output.println(data);
                output.flush();
                out.close();
                output.close();

                socket.close();
            } catch (SocketException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (result) {
                SharedPreferences settings = PreferenceManager
                        .getDefaultSharedPreferences(MyFirebaseInstanceIDService.this);
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean(getString(R.string.registration_id_sent), true);
                editor.commit();
            } else {
                SharedPreferences settings = PreferenceManager
                        .getDefaultSharedPreferences(MyFirebaseInstanceIDService.this);
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean(getString(R.string.registration_id_sent), false);
                editor.commit();
            }
        }
    };

    // Change wifi network to "NodeMCU WiFi"

    String ssid = "";
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if (WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState()) == NetworkInfo.DetailedState.CONNECTED) {
        ssid = wifiInfo.getSSID();
    }

    if (!ssid.equals("NodeMCU WiFi")) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), getString(R.string.toast_connect_NodeMCU),
                        Toast.LENGTH_LONG).show();

            }
        });

    }
}

From source file:org.cloudata.core.common.metrics.GangliaContext.java

/** Creates a new instance of GangliaContext */
public synchronized void startMonitoring() {
    CloudataMetricsFactory factory = CloudataMetricsFactory.getFactory();
    String periodStr = factory.getAttribute(contextName + "." + PERIOD_PROPERTY);
    if (periodStr != null) {
        int period = 0;
        try {//from w w w.  j  av  a2 s . c o  m
            period = Integer.parseInt(periodStr);
        } catch (NumberFormatException nfe) {
        }
        if (period <= 0) {
            throw new MetricsException("Invalid period: " + periodStr);
        }
        setPeriod(period);
    }

    metricsServers = parse(factory.getAttribute(contextName + "." + SERVERS_PROPERTY), DEFAULT_PORT);

    unitsTable = getAttributeTable(factory, UNITS_PROPERTY);
    slopeTable = getAttributeTable(factory, SLOPE_PROPERTY);
    tmaxTable = getAttributeTable(factory, TMAX_PROPERTY);
    dmaxTable = getAttributeTable(factory, DMAX_PROPERTY);

    try {
        datagramSocket = new DatagramSocket();
    } catch (SocketException se) {
        se.printStackTrace();
    }

    super.startMonitoring();
}

From source file:com.xperia64.cosi.CosiActivity.java

public String getLocalIpAddress() {
    try {//from  www.  j av a2 s.c  o m
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:org.peercast.core.PeerCastServiceController.java

private String getIpAddress() {
    Enumeration<NetworkInterface> netIFs;
    try {/* w w  w  .j a v  a2s  .  c  o m*/
        netIFs = NetworkInterface.getNetworkInterfaces();
        while (netIFs.hasMoreElements()) {
            NetworkInterface netIF = netIFs.nextElement();
            Enumeration<InetAddress> ipAddrs = netIF.getInetAddresses();
            while (ipAddrs.hasMoreElements()) {
                InetAddress ip = ipAddrs.nextElement();
                if (!ip.isLoopbackAddress() && !ip.isLinkLocalAddress() && ip.isSiteLocalAddress()) {
                    String ipStr = ip.getHostAddress().toString();
                    Log.d(TAG, "IP: " + ipStr);
                    return ipStr;
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.catrobat.catroid.web.ConnectionWrapper.java

public String doFtpPostFileUpload(String urlString, HashMap<String, String> postValues, String fileTag,
        String filePath, ResultReceiver receiver, String httpPostUrl, Integer notificationId)
        throws IOException, WebconnectionException {
    String answer = "";
    try {/*from w  ww  . j a  va  2  s.c  om*/
        // important to call this before connect
        ftpClient.setControlEncoding("UTF-8");

        ftpClient.connect(urlString, ServerCalls.FTP_PORT);
        ftpClient.login(FTP_USERNAME, FTP_PASSWORD);

        int replyCode = ftpClient.getReplyCode();

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            ftpClient.disconnect();
            Log.e(TAG, "FTP server refused to connect");
            throw new WebconnectionException(replyCode);
        }

        ftpClient.setFileType(FILE_TYPE);
        BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
        ftpClient.enterLocalPassiveMode();

        String fileName = "";
        if (filePath != null) {
            fileName = postValues.get("projectTitle");
            String extension = filePath.substring(filePath.lastIndexOf(".") + 1).toLowerCase(Locale.ENGLISH);
            FtpProgressInputStream ftpProgressStream = new FtpProgressInputStream(inputStream, receiver,
                    notificationId, fileName);
            boolean result = ftpClient.storeFile(fileName + "." + extension, ftpProgressStream);

            if (!result) {
                throw new IOException();
            }
        }

        inputStream.close();
        ftpClient.logout();
        ftpClient.disconnect();

        answer = sendUploadPost(httpPostUrl, postValues, fileTag, filePath);

    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return answer;
}

From source file:com.bluetooth.activities.WiFiControl.java

/**
 * This method gets an IPv4 address for the user to enter in the browser.
 * /*from  ww w  .  jav  a 2 s.c om*/
 * @return The IP
 */
private String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.blueshift.mvpremote.MVPremoteActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);//ww w .j  a  va 2 s  .  c  o  m

    MyPagerAdapter adapter = new MyPagerAdapter();
    ViewPager myPager = (ViewPager) findViewById(R.id.mypanelpager);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(0);

    mPrefs = getPreferences(MODE_PRIVATE);

    hostname = mPrefs.getString("hostname", "192.168.1.255");

    try {
        s = new DatagramSocket();
        addr = InetAddress.getByName(hostname);
    } catch (SocketException e) {
        // TODO Auto-generated catch blck
        e.printStackTrace();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}