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.openhab.binding.hexabus.internal.HexaBusBinding.java

public void activate() {
    logger.debug("activate() is called.");

    // checks if the jackdaw_sock isn't created yet
    if (jackdaw_sock == null) {
        try {/* w w  w  .j  av  a2s . co  m*/
            jackdaw_sock = new DatagramSocket(jackdaw_port, jackdaw_ip);
        } catch (SocketException e) {
            e.printStackTrace();
            logger.debug("Could not create Jackdaw Socket in activate()!");
        }
    }
}

From source file:com.sixt.service.framework.registry.consul.RegistrationManager.java

private void updateIpAddress() {
    try {//w  ww  .ja  v a  2s  .  c  o  m
        Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces();
        ipAddress = null;
        while (b.hasMoreElements()) {
            NetworkInterface iface = b.nextElement();
            if (iface.getName().startsWith("dock")) {
                continue;
            }
            for (InterfaceAddress f : iface.getInterfaceAddresses()) {
                if (f.getAddress().isSiteLocalAddress()) {
                    ipAddress = f.getAddress().getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
}

From source file:com.almarsoft.GroundhogReader.ComposeActivity.java

private void postMessage() {

    AsyncTask<Void, Void, Void> messagePosterTask = new AsyncTask<Void, Void, Void>() {

        String mPostingErrorMessage = null;

        @Override// w ww  .  jav  a2 s . c om
        protected Void doInBackground(Void... arg0) {
            MessagePosterLib poster = new MessagePosterLib(mCurrentGroup, mEdit_Groups.getText().toString(),
                    mEdit_Body.getText().toString(), mEdit_Subject.getText().toString(), mReferences,
                    mMessageID, ComposeActivity.this);

            try {
                poster.postMessage();
            }

            catch (SocketException e) {
                e.printStackTrace();
                mPostingErrorMessage = e.toString();
            }

            catch (EncoderException e) {
                e.printStackTrace();
                mPostingErrorMessage = e.toString();
            }

            catch (IOException e) {
                e.printStackTrace();
                mPostingErrorMessage = e.toString();
            }

            catch (ServerAuthException e) {
                e.printStackTrace();
                mPostingErrorMessage = e.toString();
            }

            catch (UsenetReaderException e) {
                e.printStackTrace();
                mPostingErrorMessage = e.toString();
            }

            return null;
        }

        protected void onPostExecute(Void arg0) {
            try {
                dismissDialog(ID_DIALOG_POSTING);
            } catch (IllegalArgumentException e) {
            }

            if (mPostingErrorMessage != null) {
                new AlertDialog.Builder(ComposeActivity.this).setTitle(getString(R.string.error_posting))
                        .setMessage(mPostingErrorMessage).setNeutralButton(getString(R.string.close), null)
                        .show();
                mPostingErrorMessage = null;
            } else {
                setResult(RESULT_OK);
                finish();
            }
        }

    }; // End messagePosterTask

    String groups = mEdit_Groups.getText().toString();

    if (groups == null || groups.trim().length() == 0) {
        new AlertDialog.Builder(ComposeActivity.this).setTitle(getString(R.string.empty_groups))
                .setMessage(getString(R.string.must_select_group)).setNeutralButton("Close", null).show();
    } else {
        showDialog(ID_DIALOG_POSTING);
        messagePosterTask.execute();
    }
}

From source file:com.iiitd.networking.UDPMessenger.java

/**
 * Sends a broadcast message (TAG EPOCH_TIME message). Opens a new socket in case it's closed.
 * @param message the message to send (multicast). It can't be null or 0-characters long.
 * @return/*  ww  w  .j a v a  2 s. c o  m*/
 * @throws IllegalArgumentException
 */
public boolean sendMessage(String message) throws IllegalArgumentException {
    if (message == null || message.length() == 0)
        throw new IllegalArgumentException();

    // Check for WiFi connectivity
    ConnectivityManager connManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (mWifi == null || !mWifi.isConnected()) {
        Log.d(DEBUG_TAG,
                "Sorry! You need to be in a WiFi network in order to send UDP multicast packets. Aborting.");
        return false;
    }

    // Check for IP address
    WifiManager wim = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int ip = wim.getConnectionInfo().getIpAddress();

    // Create the send socket
    if (socket == null) {
        try {
            socket = new DatagramSocket();
        } catch (SocketException e) {
            Log.d(DEBUG_TAG, "There was a problem creating the sending socket. Aborting.");
            e.printStackTrace();
            return false;
        }
    }

    // Build the packet
    DatagramPacket packet;
    Message msg = new Message(TAG, message);
    byte data[] = msg.toString().getBytes();

    WifiInfo wifiInfo = wim.getConnectionInfo();
    int ipa = wifiInfo.getIpAddress();
    String ipAddress = Formatter.formatIpAddress(ipa);

    try {
        //         packet = new DatagramPacket(data, data.length, InetAddress.getByName(ipToString(ip, true)), MULTICAST_PORT);
        packet = new DatagramPacket(data, data.length, InetAddress.getByName(ipAddress), MULTICAST_PORT);
    } catch (UnknownHostException e) {
        Log.d(DEBUG_TAG, "It seems that " + ipToString(ip, true) + " is not a valid ip! Aborting.");
        e.printStackTrace();
        return false;
    }

    try {
        socket.send(packet);
    } catch (IOException e) {
        Log.d(DEBUG_TAG, "There was an error sending the UDP packet. Aborted.");
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:org.openmeetings.test.calendar.TestSendIcalMessage.java

public void simpleInvitionIcalLink() {
    // Create a TimeZone
    TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
    TimeZone timezone = registry.getTimeZone("America/Mexico_City");
    VTimeZone tz = timezone.getVTimeZone();

    // Start Date is on: April 1, 2008, 9:00 am
    java.util.Calendar startDate = new GregorianCalendar();
    startDate.setTimeZone(timezone);/*from w w w. j a  v  a2  s .c  o  m*/
    startDate.set(java.util.Calendar.MONTH, java.util.Calendar.APRIL);
    startDate.set(java.util.Calendar.DAY_OF_MONTH, 1);
    startDate.set(java.util.Calendar.YEAR, 2008);
    startDate.set(java.util.Calendar.HOUR_OF_DAY, 9);
    startDate.set(java.util.Calendar.MINUTE, 0);
    startDate.set(java.util.Calendar.SECOND, 0);

    // End Date is on: April 1, 2008, 13:00
    java.util.Calendar endDate = new GregorianCalendar();
    endDate.setTimeZone(timezone);
    endDate.set(java.util.Calendar.MONTH, java.util.Calendar.APRIL);
    endDate.set(java.util.Calendar.DAY_OF_MONTH, 1);
    endDate.set(java.util.Calendar.YEAR, 2008);
    endDate.set(java.util.Calendar.HOUR_OF_DAY, 13);
    endDate.set(java.util.Calendar.MINUTE, 0);
    endDate.set(java.util.Calendar.SECOND, 0);

    // Create the event
    String eventName = "Progress Meeting";
    DateTime start = new DateTime(startDate.getTime());
    DateTime end = new DateTime(endDate.getTime());
    VEvent meeting = new VEvent(start, end, eventName);

    // add timezone info..
    meeting.getProperties().add(tz.getTimeZoneId());

    // generate unique identifier..
    UidGenerator ug;
    try {
        ug = new UidGenerator("uidGen");

        Uid uid = ug.generateUid();
        meeting.getProperties().add(uid);
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // add attendees..
    Attendee dev1 = new Attendee(URI.create("mailto:dev1@mycompany.com"));
    dev1.getParameters().add(Role.REQ_PARTICIPANT);
    dev1.getParameters().add(new Cn("Developer 1"));
    meeting.getProperties().add(dev1);

    Attendee dev2 = new Attendee(URI.create("mailto:dev2@mycompany.com"));
    dev2.getParameters().add(Role.OPT_PARTICIPANT);
    dev2.getParameters().add(new Cn("Developer 2"));
    meeting.getProperties().add(dev2);

    // Create a calendar
    net.fortuna.ical4j.model.Calendar icsCalendar = new net.fortuna.ical4j.model.Calendar();
    icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
    icsCalendar.getProperties().add(CalScale.GREGORIAN);
    icsCalendar.getProperties().add(Version.VERSION_2_0);

    // Add the event and print
    icsCalendar.getComponents().add(meeting);

    Organizer orger = new Organizer(URI.create("seba.wagner@gmail.com"));
    orger.getParameters().add(new Cn("Sebastian Wagner"));
    meeting.getProperties().add(orger);

    icsCalendar.getProperties().add(Method.REQUEST);

    System.out.println(icsCalendar);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    CalendarOutputter outputter = new CalendarOutputter();
    try {
        outputter.output(icsCalendar, bout);
        iCalMimeBody = bout.toByteArray();

        sendIcalMessage();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ValidationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:api.APICall.java

public String executePost(String targetURL, String urlParameters) {
    URL url;//from   ww w  .  jav a 2s .c o  m
    HttpURLConnection connection = null;
    try {
        // Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        // Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        // Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();

    } catch (SocketException se) {
        se.printStackTrace();
        System.out.println("Server is down.");
        return null;
    } catch (Exception e) {

        e.printStackTrace();
        return null;

    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.runmyprocess.sec.FTP.java

/**
 * receives the object with the path to look for the file and read the configuration file
 * @param jsonObject/*  www . ja va 2s. c  o  m*/
 * @param configPath
 */
@Override
public void accept(JSONObject jsonObject, String configPath) {
    try {
        LOG.log("NEW REQUEST", Level.INFO);
        Config config = new Config("configFiles" + File.separator + "FTP.config", true);//finds and reads the config file
        // get an ftpClient object
        if (client == null || jsonObject.containsKey("FTPType")) {
            if (jsonObject.getString("FTPType") == "FTP") {
                this.client = new FTPClient();
            } else if (jsonObject.getString("FTPType") == "FTPS") {
                this.client = new FTPSClient();
            }
        }
        LOG.log("NEW REQUEST CLIENT SET", Level.INFO);
        try {
            // pass directory path on server to connect
            if (!this.connect(config.getProperty("host"), jsonObject.getString("user"),
                    jsonObject.getString("password"), Integer.parseInt(config.getProperty("port")))) {
                throw new Exception("Unable to loggin to FTP");
            }
            LOG.log("Connection established...", Level.INFO);

            Task task = Task.DEFAULT;
            if (jsonObject.containsKey("task"))
                try {
                    task = Task.valueOf(jsonObject.getString("task"));
                } catch (Exception ex) {
                    //do NOTHING task not found
                }
            LOG.log(task.name(), Level.INFO);
            switch (task) {
            case PING:
                ping(jsonObject);
                break;
            case GET:
                fetchFile(jsonObject);
                break;
            case PUT:
                upload(jsonObject);
                break;
            case LIST:
                listFiles(jsonObject);
                break;
            case DELETE:
                remove(jsonObject);
                break;
            case RENAME:
                rename(jsonObject);
                break;
            case MKDIR:
                createDir(jsonObject);
                break;
            case RMDIR:
                removeDir(jsonObject);
                break;
            case DEFAULT:
                throw new Exception("Task not found");
            }

        } catch (SocketException e) {
            e.printStackTrace();
            throw new Exception(e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception(e);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e);
        } finally {
            try {
                if (this.logged)
                    this.client.logout();
                this.client.disconnect();
                LOG.log("Disconnected", Level.INFO);
            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception(e);
            }
        }

    } catch (Exception e) {
        response.setData(this.FTPError(e.toString()));
        SECErrorManager errorManager = new SECErrorManager();
        errorManager.logError(e.toString(), Level.SEVERE);
        e.printStackTrace();
    }
}

From source file:de.jaetzold.networking.SimpleServiceDiscovery.java

/**
 * Send a SSDP search message with the given search target (ST) and return a list of received responses.
 *///  ww w .  j  a va 2  s . c o  m
public Map<String, URL> discover(String searchTarget) {
    Log.d("HUE", "ServiceDiscovery.discover");
    final InetSocketAddress address;
    // standard multicast port for SSDP
    try {
        // multicast address with administrative scope
        address = new InetSocketAddress(InetAddress.getByName(MULTICAST_ADDRESS), MULTICAST_PORT);
        //address = InetAddress.getByName(MULTICAST_ADDRESS);

    } catch (UnknownHostException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not get multicast address", e);
    }

    final MulticastSocket socket;
    try {
        socket = new MulticastSocket(null);

        InetAddress localhost = getAndroidLocalIP();

        InetSocketAddress srcAddress = new InetSocketAddress(localhost, MULTICAST_PORT);
        Log.d("HUE", "" + srcAddress.getAddress());
        socket.bind(srcAddress);
        Log.d("HUE", "step 1");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not create multicast socket");
    }

    try {
        socket.setSoTimeout(socketTimeout);
        Log.d("HUE", "step 2");
    } catch (SocketException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not set socket timeout", e);
    }

    try {
        socket.joinGroup(InetAddress.getByName(MULTICAST_ADDRESS));
        Log.d("HUE", "step 3");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not make multicast socket joinGroup " + address, e);
    }
    try {
        socket.setTimeToLive(ttl);
        Log.d("HUE", "step 4");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not set TTL " + ttl, e);
    }
    final byte[] transmitBuffer;
    try {
        transmitBuffer = constructSearchMessage(searchTarget).getBytes(CHARSET_NAME);
        Log.d("HUE", "step 5");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new IllegalStateException("WTF? " + CHARSET_NAME + " is not supported?", e);
    }
    DatagramPacket packet = null;
    try {
        packet = new DatagramPacket(transmitBuffer, transmitBuffer.length, address);
        Log.d("HUE", "step 6");
    } catch (SocketException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        socket.send(packet);
        Log.d("HUE", "step 7");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not send search request", e);
    }
    Map<String, URL> result = new HashMap<String, URL>();
    byte[] receiveBuffer = new byte[1536];
    while (true) {
        try {
            Log.d("HUE", "sending packets");
            final DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length,
                    InetAddress.getByName(MULTICAST_ADDRESS), MULTICAST_PORT);
            socket.receive(receivePacket);
            //Log.d("HUE", new String(receivePacket.getData()));
            HueBridge response = parseResponsePacket(receivePacket);
            if (response != null) {
                Log.d("HUE", "resonse not null");
                ////System.out.println("resonse not null");
                result.put(response.getUDN(), response.getBaseUrl());
            } else {
                Log.d("HUE", "no bridge");
            }
        } catch (SocketTimeoutException e) {
            Log.e("HUE", "timeout exception");
            break;
        } catch (IOException e) {
            throw new IllegalStateException("Problem receiving search responses", e);
        }
    }
    return result;
}

From source file:com.mitre.holdshort.AlertLogger.java

public AlertLogger(String airport, Context ctx) {

    this.ctx = ctx;
    this.airport = airport;
    try {//from w  ww  .  j a  v  a 2  s .  c o m

        alertFTPClient = new FTPClient();
        alertFTPClient.connect(ftpHost, 21);
        alertFTPClient.login(ftpUser, ftpPassword);
        alertFTPClient.enterLocalPassiveMode();

    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnknownHostException e) {
        System.err.println("No Connection For FTP Client");
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Check for or create old alert file for when FTPClient cannot connect
    File oldAlerts = new File(ctx.getFilesDir() + "/oldAlerts.dat");
    if (!(oldAlerts.exists())) {
        try {
            oldAlerts.createNewFile();
        } catch (IOException e1) {

        }
    } else {
        //Old Alert file exists & push old alerts to the ftp server
        logOldAlerts();
    }

}

From source file:org.eclipse.om2m.comm.coap.CoapServer.java

@Override
public void deliverRequest(Exchange exchange) {

    req = exchange.getRequest();/*from   ww w .  j av a2 s  .c o  m*/

    try {
        resp = service(req);
        LOGGER.info("the response= " + resp);
        logservice.log(LogService.LOG_ERROR, "the response= " + resp);
    } catch (SocketException e) {
        LOGGER.info("the service failed! ");
        logservice.log(LogService.LOG_ERROR, "the service failed! ");
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    LOGGER.info("request = " + req);
    logservice.log(LogService.LOG_ERROR, "request = " + req);
    exchange.sendResponse(resp);

}