use of java.net.SocketException in project jetty.project by eclipse.
the class ConnectorTimeoutTest method testMaxIdleWithRequest10NoClientClose.
@Test(timeout = 60000)
public void testMaxIdleWithRequest10NoClientClose() throws Exception {
final Exchanger<EndPoint> exchanger = new Exchanger<>();
configureServer(new HelloWorldHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
try {
exchanger.exchange(baseRequest.getHttpChannel().getEndPoint());
} catch (Exception e) {
e.printStackTrace();
}
super.handle(target, baseRequest, request, response);
}
});
Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort());
client.setSoTimeout(10000);
Assert.assertFalse(client.isClosed());
OutputStream os = client.getOutputStream();
InputStream is = client.getInputStream();
os.write(("GET / HTTP/1.0\r\n" + "host: " + _serverURI.getHost() + ":" + _serverURI.getPort() + "\r\n" + "connection: close\r\n" + "\r\n").getBytes("utf-8"));
os.flush();
// Get the server side endpoint
EndPoint endPoint = exchanger.exchange(null, 10, TimeUnit.SECONDS);
if (endPoint instanceof SslConnection.DecryptedEndPoint)
endPoint = endPoint.getConnection().getEndPoint();
// read the response
String result = IO.toString(is);
Assert.assertThat("OK", result, Matchers.containsString("200 OK"));
// check client reads EOF
Assert.assertEquals(-1, is.read());
// wait for idle timeout
TimeUnit.MILLISECONDS.sleep(3 * MAX_IDLE_TIME);
// further writes will get broken pipe or similar
try {
for (int i = 0; i < 1000; i++) {
os.write(("GET / HTTP/1.0\r\n" + "host: " + _serverURI.getHost() + ":" + _serverURI.getPort() + "\r\n" + "connection: keep-alive\r\n" + "\r\n").getBytes("utf-8"));
os.flush();
}
Assert.fail("half close should have timed out");
} catch (SocketException e) {
// expected
}
// check the server side is closed
Assert.assertFalse(endPoint.isOpen());
}
use of java.net.SocketException in project tomcat by apache.
the class TestMimeHeadersIntegration method runHeadersTest.
private void runHeadersTest(final boolean successExpected, final Tomcat tomcat, final int count, final int expectedMaxHeaderCount) throws Exception {
tomcat.start();
String header = "A:B" + SimpleHttpClient.CRLF;
StringBuilder request = new StringBuilder();
request.append("GET / HTTP/1.0" + SimpleHttpClient.CRLF);
for (int i = 0; i < count; i++) {
request.append(header);
}
request.append(SimpleHttpClient.CRLF);
Client client = new Client(tomcat);
client.setRequest(new String[] { request.toString() });
try {
client.connect();
client.processRequest();
client.disconnect();
} catch (SocketException ex) {
// Connection was closed by Tomcat
if (successExpected) {
// unexpected
log.error(ex.getMessage(), ex);
} else {
log.warn(ex.getMessage(), ex);
}
}
if (successExpected) {
alv.validateAccessLog(1, 200, 0, 3000);
// Response 200
assertTrue("Response line is: " + client.getResponseLine(), client.getResponseLine() != null && client.isResponse200());
assertEquals("OK", client.getResponseBody());
} else {
alv.validateAccessLog(1, 400, 0, 0);
// Connection aborted or response 400
assertTrue("Response line is: " + client.getResponseLine(), client.getResponseLine() == null || client.isResponse400());
}
int maxHeaderCount = ((Integer) tomcat.getConnector().getProperty("maxHeaderCount")).intValue();
assertEquals(expectedMaxHeaderCount, maxHeaderCount);
if (maxHeaderCount > 0) {
assertEquals(maxHeaderCount, alv.arraySize);
} else if (maxHeaderCount < 0) {
int maxHttpHeaderSize = ((Integer) tomcat.getConnector().getAttribute("maxHttpHeaderSize")).intValue();
int headerCount = Math.min(count, maxHttpHeaderSize / header.length() + 1);
int arraySize = 1;
while (arraySize < headerCount) {
arraySize <<= 1;
}
assertEquals(arraySize, alv.arraySize);
}
}
use of java.net.SocketException in project zookeeper by apache.
the class LeaderElection method lookForLeader.
/**
* Invoked in QuorumPeer to find or elect a new leader.
*
* @throws InterruptedException
*/
public Vote lookForLeader() throws InterruptedException {
try {
self.jmxLeaderElectionBean = new LeaderElectionBean();
MBeanRegistry.getInstance().register(self.jmxLeaderElectionBean, self.jmxLocalPeerBean);
} catch (Exception e) {
LOG.warn("Failed to register with JMX", e);
self.jmxLeaderElectionBean = null;
}
try {
self.setCurrentVote(new Vote(self.getId(), self.getLastLoggedZxid()));
// We are going to look for a leader by casting a vote for ourself
byte[] requestBytes = new byte[4];
ByteBuffer requestBuffer = ByteBuffer.wrap(requestBytes);
byte[] responseBytes = new byte[28];
ByteBuffer responseBuffer = ByteBuffer.wrap(responseBytes);
/* The current vote for the leader. Initially me! */
DatagramSocket s = null;
try {
s = new DatagramSocket();
s.setSoTimeout(200);
} catch (SocketException e1) {
LOG.error("Socket exception when creating socket for leader election", e1);
System.exit(4);
}
DatagramPacket requestPacket = new DatagramPacket(requestBytes, requestBytes.length);
DatagramPacket responsePacket = new DatagramPacket(responseBytes, responseBytes.length);
int xid = epochGen.nextInt();
while (self.isRunning()) {
HashMap<InetSocketAddress, Vote> votes = new HashMap<InetSocketAddress, Vote>(self.getVotingView().size());
requestBuffer.clear();
requestBuffer.putInt(xid);
requestPacket.setLength(4);
HashSet<Long> heardFrom = new HashSet<Long>();
for (QuorumServer server : self.getVotingView().values()) {
LOG.info("Server address: " + server.addr);
try {
requestPacket.setSocketAddress(server.addr);
} catch (IllegalArgumentException e) {
// in order to capture this critical detail.
throw new IllegalArgumentException("Unable to set socket address on packet, msg:" + e.getMessage() + " with addr:" + server.addr, e);
}
try {
s.send(requestPacket);
responsePacket.setLength(responseBytes.length);
s.receive(responsePacket);
if (responsePacket.getLength() != responseBytes.length) {
LOG.error("Got a short response: " + responsePacket.getLength());
continue;
}
responseBuffer.clear();
int recvedXid = responseBuffer.getInt();
if (recvedXid != xid) {
LOG.error("Got bad xid: expected " + xid + " got " + recvedXid);
continue;
}
long peerId = responseBuffer.getLong();
heardFrom.add(peerId);
//if(server.id != peerId){
Vote vote = new Vote(responseBuffer.getLong(), responseBuffer.getLong());
InetSocketAddress addr = (InetSocketAddress) responsePacket.getSocketAddress();
votes.put(addr, vote);
//}
} catch (IOException e) {
LOG.warn("Ignoring exception while looking for leader", e);
// Errors are okay, since hosts may be
// down
}
}
ElectionResult result = countVotes(votes, heardFrom);
// for a dead peer
if (result.numValidVotes == 0) {
self.setCurrentVote(new Vote(self.getId(), self.getLastLoggedZxid()));
} else {
if (result.winner.getId() >= 0) {
self.setCurrentVote(result.vote);
// To do: this doesn't use a quorum verifier
if (result.winningCount > (self.getVotingView().size() / 2)) {
self.setCurrentVote(result.winner);
s.close();
Vote current = self.getCurrentVote();
LOG.info("Found leader: my type is: " + self.getLearnerType());
/*
* We want to make sure we implement the state machine
* correctly. If we are a PARTICIPANT, once a leader
* is elected we can move either to LEADING or
* FOLLOWING. However if we are an OBSERVER, it is an
* error to be elected as a Leader.
*/
if (self.getLearnerType() == LearnerType.OBSERVER) {
if (current.getId() == self.getId()) {
// This should never happen!
LOG.error("OBSERVER elected as leader!");
Thread.sleep(100);
} else {
self.setPeerState(ServerState.OBSERVING);
Thread.sleep(100);
return current;
}
} else {
self.setPeerState((current.getId() == self.getId()) ? ServerState.LEADING : ServerState.FOLLOWING);
if (self.getPeerState() == ServerState.FOLLOWING) {
Thread.sleep(100);
}
return current;
}
}
}
}
Thread.sleep(1000);
}
return null;
} finally {
try {
if (self.jmxLeaderElectionBean != null) {
MBeanRegistry.getInstance().unregister(self.jmxLeaderElectionBean);
}
} catch (Exception e) {
LOG.warn("Failed to unregister with JMX", e);
}
self.jmxLeaderElectionBean = null;
}
}
use of java.net.SocketException in project zookeeper by apache.
the class QuorumPeer method startLeaderElection.
public synchronized void startLeaderElection() {
try {
if (getPeerState() == ServerState.LOOKING) {
currentVote = new Vote(myid, getLastLoggedZxid(), getCurrentEpoch());
}
} catch (IOException e) {
RuntimeException re = new RuntimeException(e.getMessage());
re.setStackTrace(e.getStackTrace());
throw re;
}
//}
if (electionType == 0) {
try {
udpSocket = new DatagramSocket(myQuorumAddr.getPort());
responder = new ResponderThread();
responder.start();
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
this.electionAlg = createElectionAlgorithm(electionType);
}
use of java.net.SocketException in project weave by continuuity.
the class SocketServer method run.
@Override
public void run() {
try {
runThread = Thread.currentThread();
while (running) {
try {
Socket socket = serverSocket.accept();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), Charsets.UTF_8));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
handleRequest(reader, writer);
} finally {
socket.close();
}
} catch (SocketException e) {
LOG.info("Socket exception: " + e);
}
}
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
Aggregations