Example usage for java.net SocketException SocketException

List of usage examples for java.net SocketException SocketException

Introduction

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

Prototype

public SocketException(String msg) 

Source Link

Document

Constructs a new SocketException with the specified detail message.

Usage

From source file:net.yacy.http.ProxyHandler.java

@Override
public void handleRemote(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {

    sb.proxyLastAccess = System.currentTimeMillis();

    RequestHeader proxyHeaders = ProxyHandler.convertHeaderFromJetty(request);
    setProxyHeaderForClient(request, proxyHeaders);

    final HTTPClient client = new HTTPClient(ClientIdentification.yacyProxyAgent);
    client.setTimout(timeout);//from w  ww  . j a v  a 2 s . c om
    client.setHeader(proxyHeaders.entrySet());
    client.setRedirecting(false);
    // send request
    try {
        String queryString = request.getQueryString() != null ? "?" + request.getQueryString() : "";
        DigestURL digestURI = new DigestURL(request.getScheme(), request.getServerName(),
                request.getServerPort(), request.getRequestURI() + queryString);
        if (request.getMethod().equals(HeaderFramework.METHOD_GET)) {
            client.GET(digestURI, false);
        } else if (request.getMethod().equals(HeaderFramework.METHOD_POST)) {
            client.POST(digestURI, request.getInputStream(), request.getContentLength(), false);
        } else if (request.getMethod().equals(HeaderFramework.METHOD_HEAD)) {
            client.HEADResponse(digestURI, false);
        } else {
            throw new ServletException("Unsupported Request Method");
        }
        HttpResponse clientresponse = client.getHttpResponse();
        int statusCode = clientresponse.getStatusLine().getStatusCode();
        final ResponseHeader responseHeaderLegacy = new ResponseHeader(statusCode,
                clientresponse.getAllHeaders());

        if (responseHeaderLegacy.isEmpty()) {
            throw new SocketException(clientresponse.getStatusLine().toString());
        }
        cleanResponseHeader(clientresponse);

        // reserver cache entry
        final net.yacy.crawler.retrieval.Request yacyRequest = new net.yacy.crawler.retrieval.Request(null,
                digestURI, null, //requestHeader.referer() == null ? null : new DigestURI(requestHeader.referer()).hash(), 
                "", responseHeaderLegacy.lastModified(), sb.crawler.defaultProxyProfile.handle(), 0,
                sb.crawler.defaultProxyProfile.timezoneOffset()); //sizeBeforeDelete < 0 ? 0 : sizeBeforeDelete);
        final Response yacyResponse = new Response(yacyRequest, null, responseHeaderLegacy,
                sb.crawler.defaultProxyProfile, false, null);

        final String storeError = yacyResponse.shallStoreCacheForProxy();
        final boolean storeHTCache = yacyResponse.profile().storeHTCache();
        final String supportError = TextParser.supports(yacyResponse.url(), yacyResponse.getMimeType());

        if (
        /*
         * Now we store the response into the htcache directory if
         * a) the response is cacheable AND
         */
        (storeError == null) &&
        /*
         * b) the user has configured to use the htcache OR
         * c) the content should be indexed
         */
                ((storeHTCache) || (supportError != null))) {
            // we don't write actually into a file, only to RAM, and schedule writing the file.
            int l = responseHeaderLegacy.size();
            final ByteArrayOutputStream byteStream = new ByteArrayOutputStream((l < 32) ? 32 : l);
            final OutputStream toClientAndMemory = new MultiOutputStream(
                    new OutputStream[] { response.getOutputStream(), byteStream });
            convertHeaderToJetty(clientresponse, response);
            response.setStatus(statusCode);
            client.writeTo(toClientAndMemory);

            // cached bytes
            storeToCache(yacyResponse, byteStream.toByteArray());
        } else {
            // no caching
            /*if (log.isFine()) log.logFine(reqID +" "+ url.toString() + " not cached." +
             " StoreError=" + ((storeError==null)?"None":storeError) +
             " StoreHTCache=" + storeHTCache +
             " SupportError=" + supportError);*/
            convertHeaderToJetty(clientresponse, response);
            response.setStatus(statusCode);

            if (statusCode == HttpServletResponse.SC_OK) { // continue to serve header to client e.g. HttpStatus = 302 (while skiping content)
                client.writeTo(response.getOutputStream()); // may throw exception on httpStatus=302 while gzip encoded inputstream
            }

        }
    } catch (final SocketException se) {
        throw new ServletException("Socket Exception: " + se.getMessage());
    } finally {
        client.finish();
    }

    // we handled this request, break out of handler chain
    logProxyAccess(request);
    baseRequest.setHandled(true);
}

From source file:org.jnode.net.ipv4.tcp.TCPSocketImpl.java

/**
 * @see java.net.SocketOptions#getOption(int)
 *//*  w w w .ja va 2 s  .  c o  m*/
public Object getOption(int option_id) throws SocketException {
    switch (option_id) {
    case SocketOptions.SO_BINDADDR:
        return controlBlock.getLocalAddress().toInetAddress();
    case SocketOptions.SO_RCVBUF:
        return controlBlock.getReceiveBufferSize();
    case SocketOptions.SO_SNDBUF:
        return controlBlock.getSendBufferSize();
    case SocketOptions.SO_TIMEOUT:
        // todo implement it, 0 means disabled
        return 0;
    default:
        throw new SocketException("Option " + option_id + " is not recognised or not implemented");
    }
}

From source file:com.predic8.membrane.core.rules.SSLProxy.java

@Override
public SSLContext getSslInboundContext() {
    return new SSLContext(new SSLParser(), router.getResolverMap(), router.getBaseLocation()) {

        @Override/*from w ww  .j av a  2 s. co  m*/
        public Socket wrap(Socket socket, byte[] buffer, int position) throws IOException {
            int port = target.getPort();
            if (port == -1)
                port = getPort();

            StreamPump.StreamPumpStats streamPumpStats = router.getStatistics().getStreamPumpStats();
            String protocol = "SSL";

            Connection con = cm.getConnection(target.getHost(), port, connectionConfiguration.getLocalAddr(),
                    null, connectionConfiguration.getTimeout());

            con.out.write(buffer, 0, position);
            con.out.flush();

            String source = socket.getRemoteSocketAddress().toString();
            String dest = con.toString();
            final StreamPump a = new StreamPump(con.in, socket.getOutputStream(), streamPumpStats,
                    protocol + " " + source + " <- " + dest, SSLProxy.this);
            final StreamPump b = new StreamPump(socket.getInputStream(), con.out, streamPumpStats,
                    protocol + " " + source + " -> " + dest, SSLProxy.this);

            socket.setSoTimeout(0);

            String threadName = Thread.currentThread().getName();
            new Thread(a, threadName + " " + protocol + " Backward Thread").start();
            try {
                Thread.currentThread().setName(threadName + " " + protocol + " Onward Thread");
                b.run();
            } finally {
                try {
                    con.close();
                } catch (IOException e) {
                    log.debug("", e);
                }
            }
            throw new SocketException("SSL Forwarding Connection closed.");
        }
    };
}

From source file:org.jnode.net.ipv4.tcp.TCPInChannel.java

/**
 * Read data from the input buffer up to len bytes long. Block until there is data available.
 *
 * @param dst//from  www.  j  a va 2 s.c o  m
 * @param off
 * @param len
 * @return The number of bytes read
 */
public synchronized int read(byte[] dst, int off, int len) throws SocketException {
    while ((dataBuffer.getUsed() == 0) && !controlBlock.isReset() && !isEOF()) {
        try {
            wait();
        } catch (InterruptedException ex) {
            // Ignore
        }
    }
    if (controlBlock.isReset()) {
        throw new SocketException("Connection reset");
    } else if (isEOF()) {
        return -1;
    } else {
        return dataBuffer.read(dst, off, len);
    }
}

From source file:org.jnode.net.ipv4.udp.UDPProtocol.java

/**
 * Register a datagram socket/*from  w  w  w  . j a  v  a 2 s.  c  om*/
 * 
 * @param socket
 */
protected synchronized void bind(UDPDatagramSocketImpl socket) throws SocketException {
    Integer lport = new Integer(socket.getLocalPort());

    if (lport.compareTo(zero) != 0 && sockets.containsKey(lport)) {
        throw new SocketException("Port already bound (" + lport + ")");
    } else {
        Integer ran;

        while (lport.compareTo(zero) == 0) {
            ran = new Integer(random.nextInt(stopRandom) + startRandom);

            if (!sockets.containsKey(ran)) {
                // hmmm..... should we have one stop condition more??
                lport = ran;
                socket.setLocalPort(lport.intValue());
            }
        }

        sockets.put(lport, socket);
    }
}

From source file:org.jnode.net.ipv4.icmp.ICMPProtocol.java

/**
 * Create a type specific ICMP header. The type is read from the first first
 * in the skbuf./*from w  w  w.  j a  v a2  s  . co m*/
 * 
 * @param skbuf
 * @throws SocketException
 */
private ICMPHeader createHeader(SocketBuffer skbuf) throws SocketException {
    final int type = skbuf.get(0);
    switch (type) {
    case ICMP_DEST_UNREACH:
        return new ICMPUnreachableHeader(skbuf);

    case ICMP_TIMESTAMP:
    case ICMP_TIMESTAMPREPLY:
        return new ICMPTimestampHeader(skbuf);

    case ICMP_ADDRESS:
    case ICMP_ADDRESSREPLY:
        return new ICMPAddressMaskHeader(skbuf);

    case ICMP_ECHOREPLY:
    case ICMP_ECHO:
        return new ICMPEchoHeader(skbuf);

    case ICMP_SOURCE_QUENCH:
    case ICMP_REDIRECT:
    case ICMP_TIME_EXCEEDED:
    case ICMP_PARAMETERPROB:
    case ICMP_INFO_REQUEST:
    case ICMP_INFO_REPLY:
        throw new SocketException("Not implemented");
    default:
        throw new SocketException("Unknown ICMP type " + type);
    }
}

From source file:org.apache.hama.pipes.Application.java

/**
 * Start the child process to handle the task for us.
 * //from w  w  w.  ja  v  a  2 s.  c o  m
 * @param peer the current peer including the task's configuration
 * @throws InterruptedException
 * @throws IOException
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
Application(BSPPeer<K1, V1, K2, V2, BytesWritable> peer) throws IOException, InterruptedException {

    Map<String, String> env = new HashMap<String, String>();
    boolean streamingEnabled = peer.getConfiguration().getBoolean("hama.streaming.enabled", false);

    if (!streamingEnabled) {
        serverSocket = new ServerSocket(0);
        env.put("hama.pipes.command.port", Integer.toString(serverSocket.getLocalPort()));
    }
    // add TMPDIR environment variable with the value of java.io.tmpdir
    env.put("TMPDIR", System.getProperty("java.io.tmpdir"));

    /* Set Logging Environment from Configuration */
    env.put("hama.pipes.logging", peer.getConfiguration().getBoolean("hama.pipes.logging", false) ? "1" : "0");
    LOG.debug("DEBUG hama.pipes.logging: " + peer.getConfiguration().getBoolean("hama.pipes.logging", false));

    List<String> cmd = new ArrayList<String>();
    String interpretor = peer.getConfiguration().get("hama.pipes.executable.interpretor");
    if (interpretor != null) {
        cmd.add(interpretor);
    }

    String executable = null;
    try {
        LOG.debug("DEBUG LocalCacheFilesCount: "
                + DistributedCache.getLocalCacheFiles(peer.getConfiguration()).length);
        for (Path u : DistributedCache.getLocalCacheFiles(peer.getConfiguration()))
            LOG.debug("DEBUG LocalCacheFiles: " + u);

        executable = DistributedCache.getLocalCacheFiles(peer.getConfiguration())[0].toString();

        LOG.info("executable: " + executable);

    } catch (Exception e) {
        LOG.error("Executable: " + executable + " fs.default.name: "
                + peer.getConfiguration().get("fs.default.name"));

        throw new IOException("Executable is missing!");
    }

    if (!new File(executable).canExecute()) {
        // LinuxTaskController sets +x permissions on all distcache files already.
        // In case of DefaultTaskController, set permissions here.
        FileUtil.chmod(executable, "u+x");
    }
    cmd.add(executable);

    String additionalArgs = peer.getConfiguration().get("hama.pipes.executable.args");
    // if true, we are resolving filenames with the linked paths in
    // DistributedCache
    boolean resolveArguments = peer.getConfiguration().getBoolean("hama.pipes.resolve.executable.args", false);
    if (additionalArgs != null && !additionalArgs.isEmpty()) {
        String[] split = additionalArgs.split(" ");
        for (String s : split) {
            if (resolveArguments) {
                for (Path u : DistributedCache.getLocalCacheFiles(peer.getConfiguration())) {
                    if (u.getName().equals(s)) {
                        LOG.info("Resolved argument \"" + s + "\" with fully qualified path \"" + u.toString()
                                + "\"!");
                        cmd.add(u.toString());
                        break;
                    }
                }
            } else {
                cmd.add(s);
            }
        }
    }

    // wrap the command in a stdout/stderr capture
    TaskAttemptID taskid = peer.getTaskId();
    File stdout = TaskLog.getTaskLogFile(taskid, TaskLog.LogName.STDOUT);
    File stderr = TaskLog.getTaskLogFile(taskid, TaskLog.LogName.STDERR);
    // Get the desired maximum length of task's logs.
    long logLength = TaskLog.getTaskLogLength(peer.getConfiguration());
    if (!streamingEnabled) {
        cmd = TaskLog.captureOutAndError(null, cmd, stdout, stderr, logLength);
    } else {
        // use tee in streaming to get the output to file
        cmd = TaskLog.captureOutAndErrorTee(null, cmd, stdout, stderr, logLength);
    }

    if (!stdout.getParentFile().exists()) {
        stdout.getParentFile().mkdirs();
        LOG.info("STDOUT: " + stdout.getParentFile().getAbsolutePath() + " created!");
    }
    LOG.info("STDOUT: " + stdout.getAbsolutePath());

    if (!stderr.getParentFile().exists()) {
        stderr.getParentFile().mkdirs();
        LOG.info("STDERR: " + stderr.getParentFile().getAbsolutePath() + " created!");
    }
    LOG.info("STDERR: " + stderr.getAbsolutePath());

    LOG.info("DEBUG: cmd: " + cmd);

    process = runClient(cmd, env); // fork c++ binary

    try {
        if (streamingEnabled) {
            downlink = new StreamingProtocol(peer, process.getOutputStream(), process.getInputStream());
        } else {
            LOG.info("DEBUG: waiting for Client at " + serverSocket.getLocalSocketAddress());
            serverSocket.setSoTimeout(2000);
            clientSocket = serverSocket.accept();
            downlink = new BinaryProtocol<K1, V1, K2, V2>(peer, clientSocket.getOutputStream(),
                    clientSocket.getInputStream());
        }
        downlink.start();

    } catch (SocketException e) {
        throw new SocketException("Timout: Client pipes application was not connecting!");
    }
}

From source file:org.apache.hadoop.hdfs.server.datanode.BlockSender.java

/**
 * Converts an IOExcpetion (not subclasses) to SocketException.
 * This is typically done to indicate to upper layers that the error 
 * was a socket error rather than often more serious exceptions like 
 * disk errors.//  ww w.j ava  2s.  com
 */
private static IOException ioeToSocketException(IOException ioe) {
    if (ioe.getClass().equals(IOException.class)) {
        // "se" could be a new class in stead of SocketException.
        IOException se = new SocketException("Original Exception : " + ioe);
        se.initCause(ioe);
        /* Change the stacktrace so that original trace is not truncated
         * when printed.*/
        se.setStackTrace(ioe.getStackTrace());
        return se;
    }
    // otherwise just return the same exception.
    return ioe;
}

From source file:org.apache.hama.pipes.PipesApplication.java

/**
 * Start the child process to handle the task for us. Peer is not available
 * now, start child by using only the configuration! e.g., PipesPartitioner,
 * no peer is available at this time!// w  ww.j  a  v  a2  s  . co m
 * 
 * @param conf task's configuration
 * @throws InterruptedException
 * @throws IOException
 */
public void start(Configuration conf) throws IOException, InterruptedException {

    Map<String, String> env = setupEnvironment(conf);
    List<String> cmd = setupCommand(conf);

    // wrap the command in a stdout/stderr capture
    File stdout = TaskLog.getLocalTaskLogFile(TaskLog.LogName.STDOUT, "yyyyMMdd'_partitioner_'HHmmss");
    File stderr = TaskLog.getLocalTaskLogFile(TaskLog.LogName.STDERR, "yyyyMMdd'_partitioner_'HHmmss");

    // Get the desired maximum length of task's logs.
    long logLength = TaskLog.getTaskLogLength(conf);

    if (!streamingEnabled) {
        cmd = TaskLog.captureOutAndError(null, cmd, stdout, stderr, logLength);
    } else {
        // use tee in streaming to get the output to file
        cmd = TaskLog.captureOutAndErrorTee(null, cmd, stdout, stderr, logLength);
    }

    /* Check if Parent folders for STDOUT exist */
    checkParentFile(stdout);
    LOG.debug("STDOUT: " + stdout.getAbsolutePath());
    /* Check if Parent folders for STDERR exist */
    checkParentFile(stderr);
    LOG.debug("STDERR: " + stderr.getAbsolutePath());

    LOG.debug("DEBUG: cmd: " + cmd);
    process = runClient(cmd, env); // fork c++ binary

    try {
        if (!streamingEnabled) {
            LOG.debug("DEBUG: waiting for Client at " + serverSocket.getLocalSocketAddress());
            serverSocket.setSoTimeout(SERVER_SOCKET_TIMEOUT);
            clientSocket = serverSocket.accept();
            LOG.debug("DEBUG: Client connected! - start BinaryProtocol!");

            downlink = new BinaryProtocol<K1, V1, K2, V2, M>(conf, clientSocket.getOutputStream(),
                    clientSocket.getInputStream());

            downlink.start();
        }

    } catch (SocketException e) {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(stderr)));

        String inputLine;
        while ((inputLine = br.readLine()) != null) {
            LOG.error("PipesApp Error: " + inputLine);
        }
        br.close();

        throw new SocketException("Timout: Client pipes application did not connect!");
    }
}

From source file:org.apache.tomcat.util.net.puretls.PureTLSSocketFactory.java

public Socket acceptSocket(ServerSocket socket) throws IOException {
    try {/* w w  w.j av a2s. co m*/
        Socket sock = socket.accept();
        return sock;
    } catch (SSLException e) {
        logger.debug("SSL handshake error", e);
        throw new SocketException("SSL handshake error" + e.toString());
    }
}