Example usage for java.net ServerSocket accept

List of usage examples for java.net ServerSocket accept

Introduction

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

Prototype

public Socket accept() throws IOException 

Source Link

Document

Listens for a connection to be made to this socket and accepts it.

Usage

From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java

@Test
public void testNetNegotiate() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();/* w w  w  .j a  v a2  s.  co m*/
                Socket socket = server.accept();
                int i = 0;
                while (true) {
                    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                    Object in = null;
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    if (i == 0) {
                        in = ois.readObject();
                        logger.debug("read object: " + in);
                        oos.writeObject("world!");
                        ois = new ObjectInputStream(socket.getInputStream());
                        oos = new ObjectOutputStream(socket.getOutputStream());
                        in = ois.readObject();
                        logger.debug("read object: " + in);
                        oos.writeObject("world!");
                        ois = new ObjectInputStream(socket.getInputStream());
                        oos = new ObjectOutputStream(socket.getOutputStream());
                    }
                    in = ois.readObject();
                    oos.writeObject("Reply" + (++i));
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
    ccf.setSerializer(new DefaultSerializer());
    ccf.setDeserializer(new DefaultDeserializer());
    ccf.setSoTimeout(10000);
    TcpConnectionInterceptorFactoryChain fc = new TcpConnectionInterceptorFactoryChain();
    fc.setInterceptors(new TcpConnectionInterceptorFactory[] { new HelloWorldInterceptorFactory(),
            new HelloWorldInterceptorFactory() });
    ccf.setInterceptorFactoryChain(fc);
    ccf.start();
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setConnectionFactory(ccf);
    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    Message<?> mOut = channel.receive(10000);
    assertNotNull(mOut);
    assertEquals("Reply1", mOut.getPayload());
    mOut = channel.receive(10000);
    assertNotNull(mOut);
    assertEquals("Reply2", mOut.getPayload());
    done.set(true);
    ccf.stop();
}

From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java

@Test
public void testNioNegotiate() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();//w  w  w .  j  a va  2 s.c  o m
                Socket socket = server.accept();
                int i = 100;
                while (true) {
                    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                    Object in;
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    if (i == 100) {
                        in = ois.readObject();
                        logger.debug("read object: " + in);
                        oos.writeObject("world!");
                        ois = new ObjectInputStream(socket.getInputStream());
                        oos = new ObjectOutputStream(socket.getOutputStream());
                        Thread.sleep(500);
                    }
                    in = ois.readObject();
                    oos.writeObject("Reply" + (i++));
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port);
    ccf.setSerializer(new DefaultSerializer());
    ccf.setDeserializer(new DefaultDeserializer());
    ccf.setSoTimeout(10000);
    TcpConnectionInterceptorFactoryChain fc = new TcpConnectionInterceptorFactoryChain();
    fc.setInterceptors(new TcpConnectionInterceptorFactory[] { new HelloWorldInterceptorFactory() });
    ccf.setInterceptorFactoryChain(fc);
    ccf.start();
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setConnectionFactory(ccf);
    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    for (int i = 0; i < 1000; i++) {
        handler.handleMessage(MessageBuilder.withPayload("Test").build());
    }
    Set<String> results = new TreeSet<String>();
    for (int i = 0; i < 1000; i++) {
        Message<?> mOut = channel.receive(10000);
        assertNotNull(mOut);
        results.add((String) mOut.getPayload());
    }
    logger.debug("results: " + results);
    for (int i = 100; i < 1100; i++) {
        assertTrue("Missing Reply" + i, results.remove("Reply" + i));
    }
    done.set(true);
    ccf.stop();
}

From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java

@Test
public void testNetSingleUseNoInbound() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final Semaphore semaphore = new Semaphore(0);
    final AtomicBoolean done = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();//from   w  w w  .j  a v  a 2s  .  c o  m
                for (int i = 0; i < 2; i++) {
                    Socket socket = server.accept();
                    semaphore.release();
                    byte[] b = new byte[6];
                    readFully(socket.getInputStream(), b);
                    semaphore.release();
                    socket.close();
                }
                server.close();
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
    ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer();
    ccf.setSerializer(serializer);
    ccf.setDeserializer(serializer);
    ccf.setSoTimeout(10000);
    ccf.start();
    ccf.setSingleUse(true);
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    assertTrue(semaphore.tryAcquire(4, 10000, TimeUnit.MILLISECONDS));
    done.set(true);
    ccf.stop();
}

From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java

@Test
public void testNioSingleUseNoInbound() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final Semaphore semaphore = new Semaphore(0);
    final AtomicBoolean done = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();// w  w  w .  ja v  a  2 s. c o  m
                for (int i = 0; i < 2; i++) {
                    Socket socket = server.accept();
                    semaphore.release();
                    byte[] b = new byte[8];
                    readFully(socket.getInputStream(), b);
                    semaphore.release();
                    socket.close();
                }
                server.close();
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port);
    ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer();
    ccf.setSerializer(serializer);
    ccf.setDeserializer(serializer);
    ccf.setSoTimeout(5000);
    ccf.start();
    ccf.setSingleUse(true);
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    handler.handleMessage(MessageBuilder.withPayload("Test.1").build());
    handler.handleMessage(MessageBuilder.withPayload("Test.2").build());
    assertTrue(semaphore.tryAcquire(4, 10000, TimeUnit.MILLISECONDS));
    done.set(true);
    ccf.stop();
}

From source file:org.urbanstew.soundcloudapi.SoundCloudAPI.java

/**
 * Completes the OAuth 1.0a authorization steps with SoundCloud, assuming the consumer application
 * can use a local port to receive the verification code.
 * //from  w ww  .  j  ava2s  .  c  om
 * <p>The function acts as a minimal HTTP server and will listen on the port specified in the
 * <code>url</code> (or the default HTTP port, if no port is specified in the <code>url</code>).  It will provide the
 * specified <code>response</code> when it receives a request for the path specified in the <code>url</code>, and
 * assuming the request includes the verification code, terminate successfully.
 * To all other requests it will respond with a <code>Not Found</code> error, and continue listening.
 * 
 * <p>The following example assumes the consumer application is running on the client's computer / device.
 * Hence, it uses a local URL ("http://localhost:8088/") to receive the verification code callback. The function
 * will listen on specified port 8088 to receive the callback.</p>
 * 
 * <pre>
 * {@code
 *  soundcloudapi.authorizeUsingUrl
*   (
*      "http://localhost:8088/",
*      "Thank you for authorizing",
*      new AuthorizationURLOpener()
*      {
*         public void openAuthorizationURL(String authorizationURL)
*         {
*            System.out.println("Please visit " + authorizationURL);
*         }
*      }
*   );
* }
* </pre>
* 
 * @param url - a callback URL via which the user can provide the verification code.
 * @param response - a response given back to the user when they allow access and get redirected to the callback URL.
 * @param URLOpener - an AuthorizationURLOpener which can open the authorization URL to the user when needed.
*
 * @return true if the process is completed successfully, false if the process was canceled via <code>cancelAuthorizeUsingUrl</code>.  
 *  
 * @throws OAuthCommunicationException 
 * @throws OAuthExpectationFailedException 
 * @throws OAuthNotAuthorizedException 
 * @throws OAuthMessageSignerException 
 * @throws IOException 
        
 * @since 0.9.1
 * @see #cancelAuthorizeUsingUrl()
*/
public boolean authorizeUsingUrl(final String url, final String response,
        final AuthorizationURLOpener URLOpener) throws OAuthMessageSignerException, OAuthNotAuthorizedException,
        OAuthExpectationFailedException, OAuthCommunicationException, IOException {
    mCancelAuthorization = false;
    unauthorize();

    URLOpener.openAuthorizationURL(obtainRequestToken(url));

    URL parsedUrl = new URL(url);
    int port = parsedUrl.getPort();
    if (port == -1)
        port = parsedUrl.getDefaultPort();

    ServerSocket server = null;
    String verificationCode = null;

    try {
        server = new ServerSocket(port);
        server.setSoTimeout(500);

        while (verificationCode == null) {
            Socket socket = null;
            BufferedReader in = null;
            PrintWriter out = null;

            try {
                try {
                    socket = server.accept();
                } catch (java.io.InterruptedIOException e) {
                    if (mCancelAuthorization) {
                        unauthorize();
                        return false;
                    } else
                        continue;
                }
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                String requestedUrl = in.readLine().split("\\s+")[1];

                URL parsedRequestedUrl = new URL("http://localhost" + requestedUrl);
                out = new PrintWriter(socket.getOutputStream(), true);

                if (!parsedRequestedUrl.getPath().equals(parsedUrl.getPath()))
                    out.print("HTTP/1.1 404 Not Found");
                else {
                    out.print("HTTP/1.1 200 OK\n\n" + response);
                    for (String parameter : parsedRequestedUrl.getQuery().split("&")) {
                        String[] keyValue = parameter.split("=");
                        if (keyValue[0].equals("oauth_verifier"))
                            verificationCode = keyValue[1];
                    }
                    if (verificationCode == null)
                        // problem - why didn't we get a verification code?
                        verificationCode = "";
                }
                out.flush();
            } finally {
                closeQuietly(in);
                closeQuietly(out);
                closeQuietly(socket);
            }
        }
    } finally {
        closeQuietly(server);
    }

    if (verificationCode.length() > 0) {
        obtainAccessToken(verificationCode);
        return true;
    } else
        return false;
}

From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java

@Test
public void testNetSingleUseWithInbound() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final Semaphore semaphore = new Semaphore(0);
    final AtomicBoolean done = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();/*  w w w.  j  a  v  a2s.  c  o m*/
                for (int i = 1; i < 3; i++) {
                    Socket socket = server.accept();
                    semaphore.release();
                    byte[] b = new byte[6];
                    readFully(socket.getInputStream(), b);
                    b = ("Reply" + i + "\r\n").getBytes();
                    socket.getOutputStream().write(b);
                    socket.close();
                }
                server.close();
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
    ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer();
    ccf.setSerializer(serializer);
    ccf.setDeserializer(serializer);
    ccf.setSoTimeout(10000);
    ccf.start();
    ccf.setSingleUse(true);
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setConnectionFactory(ccf);
    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    assertTrue(semaphore.tryAcquire(2, 10000, TimeUnit.MILLISECONDS));
    Set<String> replies = new HashSet<String>();
    for (int i = 0; i < 2; i++) {
        Message<?> mOut = channel.receive(10000);
        assertNotNull(mOut);
        replies.add(new String((byte[]) mOut.getPayload()));
    }
    assertTrue(replies.remove("Reply1"));
    assertTrue(replies.remove("Reply2"));
    done.set(true);
    ccf.stop();
}

From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java

@Test
public void testNioSingleUseWithInbound() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final Semaphore semaphore = new Semaphore(0);
    final AtomicBoolean done = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();//from  w ww  .j a v  a2 s.c  om
                for (int i = 1; i < 3; i++) {
                    Socket socket = server.accept();
                    semaphore.release();
                    byte[] b = new byte[6];
                    readFully(socket.getInputStream(), b);
                    b = ("Reply" + i + "\r\n").getBytes();
                    socket.getOutputStream().write(b);
                    socket.close();
                }
                server.close();
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port);
    ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer();
    ccf.setSerializer(serializer);
    ccf.setDeserializer(serializer);
    ccf.setSoTimeout(10000);
    ccf.start();
    ccf.setSingleUse(true);
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setConnectionFactory(ccf);
    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    assertTrue(semaphore.tryAcquire(2, 10000, TimeUnit.MILLISECONDS));
    Set<String> replies = new HashSet<String>();
    for (int i = 0; i < 2; i++) {
        Message<?> mOut = channel.receive(10000);
        assertNotNull(mOut);
        replies.add(new String((byte[]) mOut.getPayload()));
    }
    assertTrue(replies.remove("Reply1"));
    assertTrue(replies.remove("Reply2"));
    done.set(true);
    ccf.stop();
}

From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java

@Test
public void testNioSingleUseWithInboundMany() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final Semaphore semaphore = new Semaphore(0);
    final AtomicBoolean done = new AtomicBoolean();
    final List<Socket> serverSockets = new ArrayList<Socket>();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port, 100);
                latch.countDown();//from w  w w  .  j av  a  2 s  .c  o m
                for (int i = 0; i < 100; i++) {
                    Socket socket = server.accept();
                    serverSockets.add(socket);
                    semaphore.release();
                    byte[] b = new byte[9];
                    readFully(socket.getInputStream(), b);
                    b = ("Reply" + i + "\r\n").getBytes();
                    socket.getOutputStream().write(b);
                    socket.close();
                }
                server.close();
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port);
    ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer();
    ccf.setSerializer(serializer);
    ccf.setDeserializer(serializer);
    ccf.setSoTimeout(10000);
    ccf.setSingleUse(true);
    ccf.setTaskExecutor(Executors.newFixedThreadPool(100));
    ccf.start();
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setConnectionFactory(ccf);
    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    int i = 0;
    try {
        for (i = 100; i < 200; i++) {
            handler.handleMessage(MessageBuilder.withPayload("Test" + i).build());
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail("Exception at " + i);
    }
    assertTrue(semaphore.tryAcquire(100, 20000, TimeUnit.MILLISECONDS));
    Set<String> replies = new HashSet<String>();
    for (i = 100; i < 200; i++) {
        Message<?> mOut = channel.receive(20000);
        assertNotNull(mOut);
        replies.add(new String((byte[]) mOut.getPayload()));
    }
    for (i = 0; i < 100; i++) {
        assertTrue("Reply" + i + " missing", replies.remove("Reply" + i));
    }
    done.set(true);
    ccf.stop();
}

From source file:org.hyperic.hq.bizapp.agent.client.AgentClient.java

private void verifyAgentRunning(ServerSocket startupSock) throws AgentInvokeException {
    try {/*www.  j  ava 2s.  c  om*/

        Socket conn = startupSock.accept();

        DataInputStream dIs = new DataInputStream(conn.getInputStream());

        if (dIs.readInt() != 1) {
            throw new AgentInvokeException("Agent reported an error " + "while starting up");
        }

    } catch (InterruptedIOException exc) {
        throw new AgentInvokeException("Timed out waiting for Agent " + "to report startup success");
    } catch (IOException exc) {
        throw new AgentInvokeException("Agent failure while starting");
    } finally {
        try {
            startupSock.close();
        } catch (IOException exc) {
        }
    }

    try {
        this.agtCommands.ping();
    } catch (Exception exc) {
        throw new AgentInvokeException("Unable to ping agent: " + exc.getMessage());
    }
}

From source file:org.kde.kdeconnect.Backends.LanBackend.LanLink.java

private void sendPackageInternal(NetworkPackage np, final Device.SendPackageStatusCallback callback,
        PublicKey key) {//from   w  ww . j  a  v a2 s.c o m
    if (session == null) {
        Log.e("KDE/sendPackage", "Not yet connected");
        callback.sendFailure(new NotYetConnectedException());
        return;
    }

    try {

        //Prepare socket for the payload
        final ServerSocket server;
        if (np.hasPayload()) {
            server = openTcpSocketOnFreePort();
            JSONObject payloadTransferInfo = new JSONObject();
            payloadTransferInfo.put("port", server.getLocalPort());
            np.setPayloadTransferInfo(payloadTransferInfo);
        } else {
            server = null;
        }

        //Encrypt if key provided
        if (key != null) {
            np = np.encrypt(key);
        }

        //Send body of the network package
        WriteFuture future = session.write(np.serialize());
        future.awaitUninterruptibly();
        if (!future.isWritten()) {
            //Log.e("KDE/sendPackage", "!future.isWritten()");
            callback.sendFailure(future.getException());
            return;
        }

        //Send payload
        if (server != null) {
            OutputStream socket = null;
            try {
                //Wait a maximum of 10 seconds for the other end to establish a connection with our socket, close it afterwards
                server.setSoTimeout(10 * 1000);
                socket = server.accept().getOutputStream();

                Log.i("KDE/LanLink", "Beginning to send payload");

                byte[] buffer = new byte[4096];
                int bytesRead;
                long progress = 0;
                InputStream stream = np.getPayload();
                while ((bytesRead = stream.read(buffer)) != -1) {
                    //Log.e("ok",""+bytesRead);
                    progress += bytesRead;
                    socket.write(buffer, 0, bytesRead);
                    if (np.getPayloadSize() > 0) {
                        callback.sendProgress((int) (progress / np.getPayloadSize()));
                    }
                }
                socket.flush();
                stream.close();
                Log.i("KDE/LanLink", "Finished sending payload (" + progress + " bytes written)");
            } catch (Exception e) {
                Log.e("KDE/sendPackage", "Exception: " + e);
                callback.sendFailure(e);
                return;
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (Exception e) {
                    }
                }
                try {
                    server.close();
                } catch (Exception e) {
                }
            }
        }

        callback.sendSuccess();

    } catch (Exception e) {
        if (callback != null) {
            callback.sendFailure(e);
        }
    } finally {
        //Make sure we close the payload stream, if any
        InputStream stream = np.getPayload();
        try {
            stream.close();
        } catch (Exception e) {
        }
    }
}