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:com.ocp.picasa.PicasaApi.java

public int getAlbumPhotos(AccountManager accountManager, SyncResult syncResult, AlbumEntry album,
        GDataParser.EntryHandler handler) {
    // Construct the query URL for user albums.
    StringBuilder builder = new StringBuilder(BASE_URL);
    builder.append("user/");
    builder.append(Uri.encode(mAuth.user));
    builder.append("/albumid/");
    builder.append(album.id);//from w  w  w.  jav a2 s . c om
    builder.append(BASE_QUERY_STRING);
    builder.append("&kind=photo");
    try {
        // Send the request.
        synchronized (mOperation) {
            GDataClient.Operation operation = mOperation;
            operation.inOutEtag = album.photosEtag;
            boolean retry = false;
            int numRetries = 1;
            do {
                retry = false;
                synchronized (mClient) {
                    mClient.get(builder.toString(), operation);
                }
                switch (operation.outStatus) {
                case HttpStatus.SC_OK:
                    break;
                case HttpStatus.SC_NOT_MODIFIED:
                    return RESULT_NOT_MODIFIED;
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_UNAUTHORIZED:
                    // We need to reset the authtoken and retry only once.
                    if (!retry) {
                        retry = true;
                        accountManager.invalidateAuthToken(PicasaService.SERVICE_NAME, mAuth.authToken);
                    }
                    if (numRetries == 0) {
                        ++syncResult.stats.numAuthExceptions;
                    }
                    break;
                default:
                    Log.e(Gallery.TAG, TAG + ": " + "getAlbumPhotos: " + builder.toString()
                            + ", unexpected status code " + operation.outStatus);
                    ++syncResult.stats.numIoExceptions;
                    return RESULT_ERROR;
                }
                --numRetries;
            } while (retry && numRetries >= 0);

            // Store the new ETag for the album/photos feed.
            album.photosEtag = operation.inOutEtag;

            // Parse the response.
            synchronized (mParser) {
                GDataParser parser = mParser;
                parser.setEntry(mPhotoInstance);
                parser.setHandler(handler);
                try {
                    Xml.parse(operation.outBody, Xml.Encoding.UTF_8, parser);
                } catch (SocketException e) {
                    Log.e(Gallery.TAG, TAG + ": " + "getAlbumPhotos: " + e);
                    ++syncResult.stats.numIoExceptions;
                    e.printStackTrace();
                    return RESULT_ERROR;
                }
            }
        }
        return RESULT_OK;
    } catch (IOException e) {
        Log.e(Gallery.TAG, TAG + ": " + "getAlbumPhotos: " + e);
        ++syncResult.stats.numIoExceptions;
        e.printStackTrace();
    } catch (SAXException e) {
        Log.e(Gallery.TAG, TAG + ": " + "getAlbumPhotos: " + e);
        ++syncResult.stats.numParseExceptions;
        e.printStackTrace();
    }
    return RESULT_ERROR;
}

From source file:net.fenyo.mail4hotspot.dns.DnsListener.java

public void run() {
    final ExecutorService pool = Executors.newCachedThreadPool();

    try {//from  w w  w  .  j  a v a  2 s . c  om
        socket = new DatagramSocket(DNSPORT);
    } catch (final SocketException ex) {
        ex.printStackTrace();
        log.error("can not start DNS service");
        return;
    }

    do {
        final DatagramPacket query = new DatagramPacket(new byte[DATAGRAMMAXSIZE], DATAGRAMMAXSIZE);
        try {
            socket.receive(query);
            pool.execute(new Handler(query));
        } catch (IOException ex) {
            log.error(ex);
        }
    } while (thread.isInterrupted() == false);

    try {
        log.info("waiting for executor tasks to terminate");
        pool.awaitTermination(120, TimeUnit.SECONDS);
    } catch (InterruptedException ex) {
        log.error(ex);
    }
}

From source file:com.kyne.webby.rtk.web.Connection.java

@SuppressWarnings("unchecked")
private void handleRequest(final String url, final String params, final Socket clientSocket)
        throws IOException, ClassNotFoundException {
    try {//from  www  .  j ava2s  .co  m
        LogHelper.debug("Processing new request : " + url + " with params : " + params + ". ClientSocket = "
                + clientSocket);
        // Clean too old authentications
        this.cleanOldAuthentications();
        // If still connected, update
        this.updateLastAction(clientSocket.getInetAddress());

        // Favicons
        if (url.startsWith("/favicon.ico")) {
            return; // Ignore
        }
        // JS, CSS and images
        else if (url.startsWith("/js/")) {
            this.webServer.printStaticFile(this.htmlDir() + url, "text/javascript", clientSocket, null);
            return;
        } else if (url.startsWith("/css/")) {
            this.webServer.printStaticFile(this.htmlDir() + url, "text/css", clientSocket, null);
            return;
        } else if (url.startsWith("/images/")) {
            if (url.endsWith("png")) {
                this.webServer.printStaticFile(this.htmlDir() + url, "images/png", clientSocket, null);
            } else if (url.endsWith("gif")) {
                this.webServer.printStaticFile(this.htmlDir() + url, "images/gif", clientSocket, null);
            }
            return;
        }
        // Unrestricted HTML Pages
        if ("/login".equals(url)) { // Login form
            final String login = this.getParam("login", params);
            final String pass = this.getParam("password", params);
            if (login == null && pass == null) { // Show form
                this.webServer.printStaticFile(this.htmlDir() + "login.html", "text/html", clientSocket,
                        this.asMap("errorMsg:none"));
                return;
            } else {
                // Try to authenticate...
                if (this.checkAuthentication(login, pass)) {
                    this.logUser(clientSocket.getInetAddress());
                    final Map<InetAddress, String> lastUrlByIp = this.webServer.getLastUrlByIp();
                    final String redirectUrl = lastUrlByIp.get(clientSocket.getInetAddress());
                    this.webServer.clearLastUrlFor(clientSocket.getInetAddress());
                    final String finalUrl = redirectUrl == null ? "/index" : redirectUrl;
                    LogHelper.info("Login successful. Redirect to " + finalUrl);
                    this.handleRequest(finalUrl, params, clientSocket);
                    return;
                } else {
                    LogHelper.info("Wrong login / password");
                    this.webServer.printStaticFile(this.htmlDir() + "login.html", "text/html", clientSocket,
                            this.asMap("errorMsg:Wrong Login/Password"));
                    return;
                }
            }
        } else if ("/logout".equals(url)) {
            this.logOut(clientSocket.getInetAddress().getHostAddress());
            this.webServer.printStaticFile(this.htmlDir() + "login.html", "text/html", clientSocket, null);
            return;
        } else if ("/404".equals(url)) {
            this.webServer.printStaticFile(this.htmlDir() + "404.html", "text/html", clientSocket, null);
            return;
        }
        //'Contextual calls'
        else if (isContextualCallUrl(url)) {
            LogHelper.info("Contextual call detected : " + url);
            final String login = getParam("login", params);
            final String password = getParam("password", params);
            boolean authenticated = this.checkAuthentication(login, password);
            if (!authenticated) {
                LogHelper.info("Wrong login / password");
                this.webServer.printStaticFile(this.htmlDir() + "login.html", "text/html", clientSocket,
                        this.asMap("errorMsg:Wrong Login/Password"));
                return;
            } else {
                // Handle the contextual call
                if (url.equals("/backupRemote")) {
                    this.rtkModule.backupServer(false, webServer.getDefaultWorldName());
                    this.webServer.printJSONObject(new JSONObject(), clientSocket);
                    return;
                }
            }
        }
        // Restricted HTML Pages
        else if (this.isRestrictedUrl(url)) {
            if (this.isUserLoggedIn(clientSocket.getInetAddress())) {
                // User may access any pages
                if ("/".equals(url) || "/index".equals(url)) { // Index
                    this.webServer.printStaticFile(this.htmlDir() + "index.html", "text/html", clientSocket,
                            this.asMap("errorMsg:none;infoMsg:none;warningMsg:none"));
                    return;
                } else if ("/indexJSON".equals(url)) {
                    this.webServer.handleIndexJSON(clientSocket);
                    return;
                } else if ("/execCommand".equals(url)) {
                    final String command = this.getParam("command", params);
                    this.rtkModule.handleCommand(command);
                    this.webServer.printJSONObject(new JSONObject(), clientSocket);
                    return;
                } else if ("/execBukkitCommand".equals(url)) {
                    final String command = this.getParam("command", params);
                    this.rtkModule.handleBukkitCommand(command);
                    this.webServer.printJSONObject(new JSONObject(), clientSocket);
                    return;
                } else if ("/backupServer".equals(url)) {
                    this.rtkModule.backupServer(false, webServer.getDefaultWorldName());
                    this.webServer.printJSONObject(new JSONObject(), clientSocket);
                    return;
                } else if ("/backups".equals(url)) {
                    this.webServer.printStaticFile(this.htmlDir() + "backups.html", "text/html", clientSocket,
                            null);
                    return;
                } else if ("/backupsJSON".equals(url)) {
                    final JSONObject backupJSON = this.webServer.getBackupJSON();
                    this.webServer.printJSONObject(backupJSON, clientSocket);
                    return;
                } else if ("/deleteBackup".equals(url)) {
                    final String fileName = this.getParam("fileName", params);
                    final boolean success = this.webServer.deleteBackup(fileName);
                    final JSONObject response = new JSONObject();
                    response.put("success", success);
                    this.webServer.printJSONObject(response, clientSocket);
                    return;
                } else if ("/restoreBackup".equals(url)) {
                    // First, backup the server
                    this.rtkModule.backupServer(true, webServer.getDefaultWorldName());

                    // Then, shutdown the server
                    this.rtkModule.handleCommand(ToolkitAction.HOLD.name());
                    this.checkForShutdown();

                    // Restore backup
                    final String fileName = this.getParam("fileName", params);
                    boolean success = this.rtkModule.restoreBackup(fileName);
                    JSONObject response = new JSONObject();
                    response.put("success", success);

                    //Restart
                    this.rtkModule.handleCommand(ToolkitAction.UNHOLD.name());
                    this.webServer.printJSONObject(response, clientSocket);
                    return;
                } else if ("/about".equals(url)) {
                    this.webServer.printStaticFile(this.htmlDir() + "about.html", "text/html", clientSocket,
                            this.asMap("version:" + WebbyKeys.VERSION));
                    return;
                } else if ("/license".equals(url)) {
                    final String license = this.webServer.getLicenseTxt();
                    this.webServer.printPlainText(license, clientSocket);
                    return;
                } else if ("/bukkitconf".equals(url)) {
                    this.webServer.printStaticFile(this.htmlDir() + "bukkitconf.html", "text/html",
                            clientSocket, null);
                    return;
                } else if ("/saveConf".equals(url)) {
                    this.webServer.saveBukkitConf(getParam("dataConf", params));
                    this.webServer.printJSON(new JSONObject(), clientSocket);
                    return;
                } else if ("/bukkitconfJSON".equals(url)) {
                    final Map<String, Object> conJSON = this.webServer.getConfJSON();
                    this.webServer.printJSON(conJSON, clientSocket);
                    return;
                }
            } else {
                this.webServer.saveLastUrlFor(clientSocket.getInetAddress(), url);
                this.handleRequest("/login", params, clientSocket); // Redirect to login
                return;
            }
        }
        // Not found -> wrong url
        LogHelper.warn("Unknow/Unsupported URL requested : " + url + ". Params = " + params);
        this.handleRequest("/404", params, clientSocket); //Forward to 404
    } catch (final SocketException e) {
        /* Go to hell */ } catch (final Exception e) {
        LogHelper.error("An error occured while processing a new HTTP request", e);
        e.printStackTrace();
    }
}

From source file:de.jeanpierrehotz.messagingapptest.MainActivity.java

/**
 * Diese Methode baut eine Verbindung zum Server auf, von dem wir die Nachrichten bekommen
 *///from  w  w  w  .  j  a v  a2s  .  com
private void connectToServer() {
    if (!tryingToConnect && !serverReached && online) {
        tryingToConnect = true;

        //          Initialisierung der Serververbindung auf einem eigenen Thread, da Android
        //          keine Netzwerkkommunikation auf dem MainThread erlaubt
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    server = new Socket(getString(R.string.serverinfo_url),
                            getResources().getInteger(R.integer.serverinfo_port));

                    serverMessageSender = new MessageSender(new DataOutputStream(server.getOutputStream()));
                    serverMessageSender.setPingListener(pingListener);

                    serverMessageListener = new MessageListener(new DataInputStream(server.getInputStream()));
                    serverMessageListener.setClosingDetector(closingDetector);
                    serverMessageListener.setOnMessageReceivedListener(receivedListener);
                    serverMessageListener.bindMessageSender(serverMessageSender);
                    serverMessageListener.start();

                    serverMessageSender.changeName(currentName);

                    serverReached = true;
                } catch (SocketException e) {
                    e.printStackTrace();
                    serverReached = false;
                    showDisconnectedErrorMessage();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                tryingToConnect = false;
            }
        }).start();
    }
}

From source file:com.monkey.entonado.MainActivity.java

/**
 * Recibe la informacion del servidor con las canciones
 * o cualcquier informacion   `/*from w  w w  .  j a va  2  s. c  o  m*/
 * @return Mensaje
 */
public String recibir() {
    String mensajeRecibir = "";
    try {
        System.out.println("recibiendo canciones metodo recibir");
        String linea = in.readLine();
        if (linea == null) {
            mensajeConexion = "desconectado";
            mensajeRecibir = mensajeConexion;
        }
        System.out.println("-----" + linea + "-----");

        int i = 0;
        while (linea != null && !linea.equals("TERMINO")) {
            i++;
            System.out.println(linea);

            if (linea.split(";").length > 1) {
                String[] lineaSp = linea.split(";");

                if (lineaSp[0].equals(AGREGAR_CANCION)) {
                    String[] infoCancion = lineaSp[1].split(" : ");
                    Cancion cancion = new Cancion(infoCancion[0], infoCancion[1], infoCancion[2]);
                    System.out.println("agrega cancion : " + cancion);
                    canciones.add(cancion);
                } else {
                    mensajeRecibir = lineaSp[1];
                    System.out.println("mensaje no == AGREGAR_CANCION");
                }
            }

            System.out.println("No entro AGREGAR");
            linea = in.readLine();
        }
        System.out.println("linae al final es: " + linea);

        Intent intent = new Intent(this, Resultados.class);
        intent.putParcelableArrayListExtra(EXTRA_CANCIONES, canciones);
        intent.putParcelableArrayListExtra(EXTRA_LISTA, milista);
        startActivityForResult(intent, 999);
    } catch (SocketException e) {
        mensajeRecibir = e.getMessage();
        e.printStackTrace();
    } catch (IOException e) {
        mensajeRecibir = e.getMessage();
        e.printStackTrace();
    } catch (Exception e) {
        mensajeRecibir = e.getMessage();
        e.printStackTrace();
    }
    return mensajeRecibir;
}

From source file:org.squidy.nodes.iPhone.java

/**
 * @param image/*from  w w w  .  ja va 2s.c  o m*/
 */
public void showButton(int x, int y, int actionType, BufferedImage image) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);

        byte[] bytes = baos.toByteArray();

        System.out.println("BYTES TO READ: " + bytes.length);

        for (Socket client : outputStreams.keySet()) {

            try {
                DataOutputStream outputStream = outputStreams.get(client);
                outputStream.writeInt(x);
                outputStream.writeInt(y);
                outputStream.writeInt(actionType);
                outputStream.writeInt(bytes.length);
                outputStream.write(bytes);
                outputStream.flush();
            } catch (SocketException e) {
                outputStreams.remove(client);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        publishFailure(e);
    }
}

From source file:com.google.appinventor.components.runtime.BlockyTalky.java

/**
 * Creates a new BlockyTalky component.//w w w.ja  va  2 s . c  om
 */
public BlockyTalky(ComponentContainer container) {
    super(container.$form());
    androidUIHandler = new Handler();

    localBTs = new ConcurrentHashMap<String, LocalBTData>();
    headers = new HashMap<String, String>() {
        {
            put("Sec-WebSocket-Protocol", "echo-protocol");
        }
    };
    handler = new Handler();
    announcerHandler = new Handler();
    Log.d(LOG_TAG, "Done with BlockyTalky constructor.");
    String addr = getIPAddress(true);
    if (addr.equals("")) {
        addr = getIPAddress(false);
    }

    try {
        mContext = container.$context();
        InetAddress ip = InetAddress.getByName(addr); //Android ip
        InetAddress bip = InetAddress.getByName(MULTICAST_ADDRESS);
        ds = new DatagramSocket(UNICAST_PORT);
        //ds.setReuseAddress(true);
        broadcastSocket = new MulticastSocket(MULTICAST_PORT);
        broadcastSocket.joinGroup(bip);
        broadcastSocket.setBroadcast(true);
        MessageListener listener = new MessageListener();
        Thread listenerThread = new Thread(listener);
        listenerThread.start();
        BroadcastListener broadcastListener = new BroadcastListener();
        Thread broadcastThread = new Thread(broadcastListener);
        broadcastThread.start();
        aquireMulticastLock();
        BroadcastAnnouncer announcer = new BroadcastAnnouncer();
        Thread announcerThread = new Thread(announcer);
        announcerThread.start();
    } catch (SocketException e) {
        Log.d(LOG_TAG,
                "Caught SocketException while trying to initialize BlockyTalky messaging: " + e.getMessage());
        e.printStackTrace();
    } catch (UnknownHostException e) {
        Log.d(LOG_TAG, "Caught UnknownHostException while trying to reach Blockytalky messaging router: "
                + e.getMessage());
    } catch (Exception e) {
        Log.d(LOG_TAG, "Exception while initializing BlockyTalky messaging: " + e);
        e.printStackTrace();
    }
    connectToMessagingRouter();

}

From source file:hellomindwavepro.ThinkGearSocket.java

@Override
public void run() {
    if (running && neuroSocket.isConnected()) {
        String userInput;//from w  w  w  .  j a v  a 2 s. com

        try {
            while ((userInput = stdIn.readLine()) != null) {

                String[] packets = userInput.split("/\r/");
                for (int s = 0; s < packets.length; s++) {
                    if (((String) packets[s]).indexOf("{") > -1) {
                        JSONObject obj = new JSONObject((String) packets[s]);
                        parsePacket(obj);
                    }

                    //String name = obj.get("name").toString();
                }

            }
        } catch (SocketException e) {
            //System.out.println("For some reason stdIn throws error even if closed");
            //maybe it takes a cycle to close properly?
            //e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
        parent.delay(50);
    } else {
        running = false;
    }
}

From source file:node.Mailbox.java

/**
 * main loop/*from w  ww .j  a  v a 2s . com*/
 */
@Override
public void run() {
    Socket socket = null;
    // set up server socket
    try {
        if (backlog == 0) {
            serverSocket = new ServerSocket(port);
        } else {
            serverSocket = new ServerSocket(port, backlog);
        }
        serverSocket.setSoTimeout(100);
        println("Opened up server socket on port " + port);
    } catch (SocketException e) {
        Control.logOneTime(e.getLocalizedMessage(), Level.SEVERE);
        println(e.getLocalizedMessage());
        System.exit(-1);
    } catch (IOException e) {
        Control.logOneTime(
                "Mailbox error: could not listen on port " + port + ". stacktrace: " + e.getLocalizedMessage(),
                Level.SEVERE);
        e.printStackTrace();
        log.severe(ExceptionUtils.getStackTrace(e));
        System.exit(-1);
    }
    // enter main loop
    while (!shutdown) {
        if (REPORT)
            reportSend.add(report());
        println(report().toJSONString());

        // block until a connection is accepted
        println("Waiting for a connection");
        try {
            socket = serverSocket.accept();
            InetAddress inetaddr = socket.getInetAddress();

            println("Received connection from " + inetaddr);
            // get the message id, then call the appropriate message handler
            acceptMessage(socket);
            // close the socket
            socket.close();
        } catch (SocketTimeoutException e) {
            println("No connection: socket timed out", true);
        } catch (ConnectException e) {
            println("Caught ConnectException", true);
        } catch (SocketException e) {
            println("Caught SocketException", true);
        } catch (IOException e) {
            e.printStackTrace();
            log.severe(ExceptionUtils.getStackTrace(e));
        }

        // See if we have any messages to send
        if (msgsSend.size() > 0)
            println("Have " + msgsSend.size() + " messages to send");
        while (msgsSend.size() > 0) {
            MessageWrapper<AbstractMessage> currentMsg = msgsSend.remove();
            println("Current message: " + currentMsg.toString());
            NodeListEntry nle_dest = currentMsg.nle;
            String destID = currentMsg.destID;
            printMessageSize(currentMsg);
            currentMsg.msg.scheduleSend(nodeList, destID, nle_dest);
            println("Mailbox: Message of type " + currentMsg.msg.msgType + " with id# " + currentMsg.msg.msgID
                    + " scheduled for sending to " + nle_dest.toString());
        }
        // check if it's time to shut down (signaled from Control)
        if (shutdown) {
            // write a log message, then exit
            // serverSocket.close()
            println("Mailbox exited");
            return;
        }
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.severe(ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:bpv.neurosky.connector.ThinkGearSocket.java

@Override
public void run() {
    if (running && neuroSocket.isConnected()) {
        String userInput;/* w ww .j  a v a2  s  .  c o  m*/

        try {
            while ((userInput = stdIn.readLine()) != null) {

                String[] packets = userInput.split("/\r/");
                for (int s = 0; s < packets.length; s++) {
                    if (((String) packets[s]).indexOf("{") > -1) {
                        JSONObject obj = new JSONObject((String) packets[s]);
                        parsePacket(obj);
                    }

                    //String name = obj.get("name").toString();
                }

            }
        } catch (SocketException e) {
            //System.out.println("For some reason stdIn throws error even if closed");
            //maybe it takes a cycle to close properly?
            //e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
        //TODO: Ajusta para funcionar na implementao atual
        //parent.delay(50);
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {

        }
    } else {
        running = false;
    }
}