Java Code Examples for java.net.SocketTimeoutException

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project fest-reflect, under directory /src/test/java/org/fest/reflect/field/.

Source file: FieldDecoratorIgnoreExceptionTest.java

  17 
vote

@Test public void should_not_ignore_pre_decorator_exceptions() throws SocketTimeoutException {
  expectedException.expect(SocketTimeoutException.class);
  String expectedExceptionMsg="Expected test exception";
  expectedException.expectMessage(JUnitMatchers.containsString(expectedExceptionMsg));
  IUploadFileService uploadFileServiceMock=mock(IUploadFileService.class);
  INotifierService notifierServiceMock=mock(INotifierService.class);
  when(uploadFileServiceMock.upload(anyString(),anyString())).thenThrow(new SocketTimeoutException(expectedExceptionMsg));
  FileManager fileManager=new FileManager();
  field("uploadFileService").ofType(IUploadFileService.class).in(fileManager).preDecorateWith(uploadFileServiceMock).ignoringDecoratorExceptions();
  field("notifierService").ofType(INotifierService.class).in(fileManager).set(notifierServiceMock);
  String fileName="testFileName";
  fileManager.manage(fileName);
}
 

Example 2

From project gansenbang, under directory /s4/s4-driver/java/src/main/java/io/s4/client/util/.

Source file: ByteArrayIOChannel.java

  17 
vote

public byte[] recv(int timeout) throws IOException {
  byte[] s={0,0,0,0};
  int tUsed=readBytes(s,4,timeout);
  if (timeout > 0 && (timeout - tUsed <= 1)) {
    throw new SocketTimeoutException("recv timed out");
  }
  int size=(int)((0xff & s[0]) << 24 | (0xff & s[1]) << 16 | (0xff & s[2]) << 8 | (0xff & s[3]) << 0);
  if (size == 0)   return null;
  byte[] v=new byte[size];
  int tRem=(timeout > 0 ? timeout - tUsed : 0);
  readBytes(v,size,tRem);
  return v;
}
 

Example 3

From project httpClient, under directory /httpclient-cache/src/test/java/org/apache/http/impl/client/cache/.

Source file: TestProtocolRequirements.java

  17 
vote

protected void testGenerates504IfCannotRevalidateStaleResponse(HttpResponse staleResponse) throws Exception {
  HttpRequest req1=new BasicHttpRequest("GET","/",HttpVersion.HTTP_1_1);
  backendExpectsAnyRequest().andReturn(staleResponse);
  HttpRequest req2=new BasicHttpRequest("GET","/",HttpVersion.HTTP_1_1);
  backendExpectsAnyRequest().andThrow(new SocketTimeoutException());
  replayMocks();
  impl.execute(host,req1);
  HttpResponse result=impl.execute(host,req2);
  verifyMocks();
  Assert.assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT,result.getStatusLine().getStatusCode());
}
 

Example 4

From project httpcore, under directory /httpcore-nio/src/main/java/org/apache/http/nio/protocol/.

Source file: HttpAsyncRequestExecutor.java

  17 
vote

public void timeout(final NHttpClientConnection conn) throws IOException {
  State state=getState(conn);
  if (state != null) {
    if (state.getRequestState() == MessageState.ACK_EXPECTED) {
      int timeout=state.getTimeout();
      conn.setSocketTimeout(timeout);
      conn.requestOutput();
      state.setRequestState(MessageState.BODY_STREAM);
      return;
    }
 else {
      state.invalidate();
      closeHandler(getHandler(conn),new SocketTimeoutException());
    }
  }
  if (conn.getStatus() == NHttpConnection.ACTIVE) {
    conn.close();
    if (conn.getStatus() == NHttpConnection.CLOSING) {
      conn.setSocketTimeout(250);
    }
  }
 else {
    conn.shutdown();
  }
}
 

Example 5

From project maven-wagon, under directory /wagon-providers/wagon-webdav-jackrabbit/src/test/java/org/apache/maven/wagon/providers/webdav/.

Source file: WebDavWagonTest.java

  17 
vote

protected int execute(HttpMethod httpMethod) throws HttpException, IOException {
  if (httpMethod.getPath().contains(TIMEOUT_TRIGGER)) {
    throw new SocketTimeoutException("Timeout triggered by request for '" + httpMethod.getPath() + "'");
  }
 else {
    return super.execute(httpMethod);
  }
}
 

Example 6

From project netifera, under directory /platform/com.netifera.platform.net.dns/com.netifera.platform.net.dns.service/src/com/netifera/platform/net/dns/service/client/.

Source file: SimpleResolver.java

  17 
vote

public synchronized void checkTimeOut(){
  long now=System.currentTimeMillis();
  List<Integer> timedOutKeys=new ArrayList<Integer>();
  for (  Integer key : contexts.keySet())   if (now > contexts.get(key).deadline)   timedOutKeys.add(key);
  for (  Integer key : timedOutKeys) {
    ResponseContext context=contexts.remove(key);
    context.listener.handleException(key,new SocketTimeoutException("Request " + key + " timed out"));
  }
}
 

Example 7

From project OpenComm, under directory /RtpStreamer/src/org/sipdroid/net/impl/.

Source file: PlainDatagramSocketImpl.java

  17 
vote

@Override public void receive(DatagramPacket pack) throws java.io.IOException {
  try {
    if (isNativeConnected) {
      netImpl.recvConnectedDatagram(fd,pack,pack.getData(),pack.getOffset(),pack.getLength(),receiveTimeout,false);
      updatePacketRecvAddress(pack);
    }
 else {
      netImpl.receiveDatagram(fd,pack,pack.getData(),pack.getOffset(),pack.getLength(),receiveTimeout,false);
    }
  }
 catch (  InterruptedIOException e) {
    throw new SocketTimeoutException(e.getMessage());
  }
}
 

Example 8

From project OpenComm_andr, under directory /sipvoip/src/org/hsc/net/.

Source file: PlainDatagramSocketImpl.java

  17 
vote

@Override public void receive(DatagramPacket pack) throws java.io.IOException {
  try {
    if (isNativeConnected) {
      netImpl.recvConnectedDatagram(fd,pack,pack.getData(),pack.getOffset(),pack.getLength(),receiveTimeout,false);
      updatePacketRecvAddress(pack);
    }
 else {
      netImpl.receiveDatagram(fd,pack,pack.getData(),pack.getOffset(),pack.getLength(),receiveTimeout,false);
    }
  }
 catch (  InterruptedIOException e) {
    throw new SocketTimeoutException(e.getMessage());
  }
}
 

Example 9

From project rabbitmq-java-client, under directory /src/com/rabbitmq/client/impl/.

Source file: AMQConnection.java

  17 
vote

/** 
 * Called when a frame-read operation times out
 * @throws MissedHeartbeatException if heart-beats have been missed
 */
private void handleSocketTimeout() throws SocketTimeoutException {
  if (_inConnectionNegotiation) {
    throw new SocketTimeoutException("Timeout during Connection negotiation");
  }
  if (_heartbeat == 0) {
    return;
  }
  if (++_missedHeartbeats > (2 * 4)) {
    throw new MissedHeartbeatException("Heartbeat missing with heartbeat = " + _heartbeat + " seconds");
  }
}
 

Example 10

From project s4, under directory /s4-driver/java/src/main/java/org/apache/s4/client/util/.

Source file: ByteArrayIOChannel.java

  17 
vote

public byte[] recv(int timeout) throws IOException {
  byte[] s={0,0,0,0};
  int tUsed=readBytes(s,4,timeout);
  if (timeout > 0 && (timeout - tUsed <= 1)) {
    throw new SocketTimeoutException("recv timed out");
  }
  int size=(int)((0xff & s[0]) << 24 | (0xff & s[1]) << 16 | (0xff & s[2]) << 8 | (0xff & s[3]) << 0);
  if (size == 0)   return null;
  byte[] v=new byte[size];
  int tRem=(timeout > 0 ? timeout - tUsed : 0);
  readBytes(v,size,tRem);
  return v;
}
 

Example 11

From project Solbase, under directory /src/org/apache/hadoop/hbase/ipc/.

Source file: HBaseClient.java

  17 
vote

/** 
 * Take an IOException and the address we were trying to connect to and return an IOException with the input exception as the cause. The new exception provides the stack trace of the place where the exception is thrown and some extra diagnostics information. If the exception is ConnectException or SocketTimeoutException, return a new one of the same type; Otherwise return an IOException.
 * @param addr target address
 * @param exception the relevant exception
 * @return an exception to throw
 */
@SuppressWarnings({"ThrowableInstanceNeverThrown"}) private IOException wrapException(InetSocketAddress addr,IOException exception){
  if (exception instanceof ConnectException) {
    return (ConnectException)new ConnectException("Call to " + addr + " failed on connection exception: "+ exception).initCause(exception);
  }
 else   if (exception instanceof SocketTimeoutException) {
    return (SocketTimeoutException)new SocketTimeoutException("Call to " + addr + " failed on socket timeout exception: "+ exception).initCause(exception);
  }
 else {
    return (IOException)new IOException("Call to " + addr + " failed on local exception: "+ exception).initCause(exception);
  }
}
 

Example 12

From project openshift-java-client, under directory /src/test/java/com/openshift/internal/client/.

Source file: ApplicationResourceTest.java

  16 
vote

@Test public void shouldNotAddCartridgeToApplication() throws Throwable {
  when(mockClient.get(urlEndsWith("/domains/foobar/applications"))).thenReturn(GET_APPLICATIONS_WITH2APPS_JSON.getContentAsString());
  when(mockClient.get(urlEndsWith("/domains/foobar/applications/sample"))).thenReturn(GET_APPLICATION_WITH1CARTRIDGE1ALIAS_JSON.getContentAsString());
  when(mockClient.get(urlEndsWith("/domains/foobar/applications/sample/cartridges"))).thenReturn(GET_APPLICATION_CARTRIDGES_WITH1ELEMENT_JSON.getContentAsString());
  when(mockClient.post(anyForm(),urlEndsWith("/domains/foobar/applications/sample/cartridges"))).thenThrow(new SocketTimeoutException("mock..."));
  final IApplication app=domain.getApplicationByName("sample");
  assertThat(app.getEmbeddedCartridges()).hasSize(1);
  try {
    app.addEmbeddableCartridge(IEmbeddableCartridge.MYSQL_51);
    fail("Expected an exception here...");
  }
 catch (  OpenShiftTimeoutException e) {
  }
  verify(mockClient,times(1)).post(anyForm(),urlEndsWith("/domains/foobar/applications/sample/cartridges"));
  assertThat(app.getEmbeddedCartridge("mysql-5.1")).isNull();
  assertThat(app.getEmbeddedCartridges()).hasSize(1);
}
 

Example 13

From project tinos, under directory /projects/org.pouzinsociety.org.jnode.net.ipv4.udp/src/main/java/org/jnode/net/ipv4/datagram/.

Source file: AbstractDatagramSocketImpl.java

  16 
vote

/** 
 * @see java.net.DatagramSocketImpl#receive(java.net.DatagramPacket)
 */
protected final void receive(DatagramPacket p) throws IOException {
  if (closed) {
    throw new SocketException("DatagramSocket has been closed");
  }
  final SocketBuffer skbuf=(SocketBuffer)receiveQueue.get(timeout);
  if (skbuf == null) {
    if (closed) {
      throw new SocketException("DatagramSocket has been closed");
    }
 else {
      throw new SocketTimeoutException("Timeout in receive");
    }
  }
 else {
    onReceive(p,skbuf);
  }
}
 

Example 14

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/www/http/.

Source file: Webserver.java

  15 
vote

public void run(){
  if (socket == null)   return;
  try {
    do {
      restart();
      parseRequest();
      if (asyncMode != null) {
        asyncTimeout=asyncMode.getTimeout();
        if (asyncTimeout > 0)         asyncTimeout+=System.currentTimeMillis();
        return;
      }
      finalizerequest();
    }
 while (keepAlive && serve.isKeepAlive() && timesRequested < serve.getMaxTimesConnectionUse());
  }
 catch (  IOException ioe) {
    if (ioe instanceof SocketTimeoutException) {
    }
 else {
      String errMsg=ioe.getMessage();
      if ((errMsg == null || errMsg.indexOf("ocket closed") < 0) && ioe instanceof java.nio.channels.AsynchronousCloseException == false)       if (socket != null)       Utils.log("IO error: " + ioe + " in processing a request from "+ socket.getInetAddress()+ ":"+ socket.getLocalPort()+ " / "+ socket.getClass().getName(),System.err);
 else       serve.log("IO error: " + ioe + "(socket NULL)");
 else synchronized (this) {
        socket=null;
      }
    }
  }
 finally {
    if (asyncMode == null)     close();
  }
}
 

Example 15

From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/message/.

Source file: AclsClient.java

  15 
vote

public Response serverSendReceive(Request r) throws AclsException {
  try {
    Socket aclsSocket=new Socket();
    try {
      aclsSocket.setSoTimeout(timeout);
      aclsSocket.connect(new InetSocketAddress(serverHost,serverPort),timeout);
      BufferedWriter w=new BufferedWriter(new OutputStreamWriter(aclsSocket.getOutputStream()));
      InputStream is=aclsSocket.getInputStream();
      LOG.debug("Sending ACLS server request " + r.getType().name() + "("+ r.unparse(true)+ ")");
      w.append(r.unparse(false) + "\r\n").flush();
      return new ResponseReaderImpl().readWithStatusLine(is);
    }
  finally {
      aclsSocket.close();
    }
  }
 catch (  SocketTimeoutException ex) {
    LOG.info("ACLS send / receive timed out");
    throw new AclsNoResponseException("Timeout while connecting or talking to ACLS server (" + serverHost + ":"+ serverPort+ ")",ex);
  }
catch (  IOException ex) {
    LOG.info("ACLS send / receive gave IO exception: " + ex.getMessage());
    throw new AclsCommsException("IO error while trying to talk to ACLS server (" + serverHost + ":"+ serverPort+ ")",ex);
  }
}
 

Example 16

From project activemq-apollo, under directory /apollo-util/src/test/scala/org/apache/activemq/apollo/util/.

Source file: SocketProxy.java

  15 
vote

public void run(){
  try {
    while (!socket.isClosed()) {
      pause.get().await();
      try {
        Socket source=socket.accept();
        LOG.info("accepted " + source);
synchronized (connections) {
          connections.add(new Connection(source,target));
        }
      }
 catch (      SocketTimeoutException expected) {
      }
    }
  }
 catch (  Exception e) {
    LOG.debug("acceptor: finished for reason: " + e.getLocalizedMessage());
  }
}
 

Example 17

From project airlift, under directory /http-client/src/test/java/io/airlift/http/client/.

Source file: ApacheHttpClientTest.java

  15 
vote

@Test(expectedExceptions=SocketTimeoutException.class) public void testConnectTimeout() throws Exception {
  ServerSocket serverSocket=new ServerSocket(0,1);
  Socket clientSocket=new Socket("localhost",serverSocket.getLocalPort());
  HttpClientConfig config=new HttpClientConfig();
  config.setConnectTimeout(new Duration(5,TimeUnit.MILLISECONDS));
  ApacheHttpClient client=new ApacheHttpClient(config);
  Request request=prepareGet().setUri(URI.create("http://localhost:" + serverSocket.getLocalPort() + "/")).build();
  try {
    client.execute(request,new ResponseToStringHandler());
  }
  finally {
    clientSocket.close();
    serverSocket.close();
  }
}
 

Example 18

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/conn/.

Source file: MultihomePlainSocketFactory.java

  15 
vote

/** 
 * Attempts to connects the socket to any of the  {@link InetAddress}es the given host name resolves to. If connection to all addresses fail, the last I/O exception is propagated to the caller.
 * @param sock socket to connect to any of the given addresses
 * @param host Host name to connect to
 * @param port the port to connect to
 * @param localAddress local address
 * @param localPort local port
 * @param params HTTP parameters
 * @throws IOException if an error occurs during the connection
 * @throws SocketTimeoutException if timeout expires before connecting
 */
public Socket connectSocket(Socket sock,String host,int port,InetAddress localAddress,int localPort,HttpParams params) throws IOException {
  if (host == null) {
    throw new IllegalArgumentException("Target host may not be null.");
  }
  if (params == null) {
    throw new IllegalArgumentException("Parameters may not be null.");
  }
  if (sock == null)   sock=createSocket();
  if ((localAddress != null) || (localPort > 0)) {
    if (localPort < 0)     localPort=0;
    InetSocketAddress isa=new InetSocketAddress(localAddress,localPort);
    sock.bind(isa);
  }
  int timeout=HttpConnectionParams.getConnectionTimeout(params);
  InetAddress[] inetadrs=InetAddress.getAllByName(host);
  List<InetAddress> addresses=new ArrayList<InetAddress>(inetadrs.length);
  addresses.addAll(Arrays.asList(inetadrs));
  Collections.shuffle(addresses);
  IOException lastEx=null;
  for (  InetAddress remoteAddress : addresses) {
    try {
      sock.connect(new InetSocketAddress(remoteAddress,port),timeout);
      break;
    }
 catch (    SocketTimeoutException ex) {
      throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
    }
catch (    IOException ex) {
      sock=new Socket();
      lastEx=ex;
    }
  }
  if (lastEx != null) {
    throw lastEx;
  }
  return sock;
}
 

Example 19

From project android-client, under directory /xwiki-android-rest/src/org/xwiki/android/rest/.

Source file: HttpConnector.java

  15 
vote

/** 
 * Checks whether user credentials are valid in the provided remote XWiki
 * @param username username of the XWiki user account
 * @param password password of the XWiki user account
 * @param Url URL of the XWiki instance
 * @return HTTP response code of the connectionor  21408(RESP_CODE_CLIENT_CON_TIMEOUT) when client connection timed out, 
 * @throws RestConnectionException 
 */
public int checkLogin(String username,String password,String Url) throws RestConnectionException {
  initialize();
  HttpGet request=new HttpGet();
  String Uri;
  int responseCode=0;
  Uri="http://" + Url + "/xwiki/rest/";
  try {
    requestUri=new URI(Uri);
  }
 catch (  URISyntaxException e) {
    e.printStackTrace();
  }
  if (username != "" && username != null && password != "" && password != null) {
    setAuthenticaion(username,password);
  }
  setCredentials();
  request.setURI(requestUri);
  Log.d("GET Login Request URL",Uri);
  try {
    response=client.execute(request);
    Log.d("Response status",response.getStatusLine().toString());
    String[] responseParts=response.getStatusLine().toString().split(" ");
    responseCode=Integer.parseInt(responseParts[1]);
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  SocketTimeoutException e) {
    Log.d(this.getClass().getSimpleName(),"Connection timeout",e);
    responseCode=RESP_CODE_CLIENT_CON_TIMEOUT;
  }
catch (  IOException e) {
    e.printStackTrace();
    throw new RestConnectionException(e);
  }
  Log.d("response code",String.valueOf(responseCode));
  return responseCode;
}
 

Example 20

From project android-joedayz, under directory /Proyectos/client/src/org/springframework/android/showcase/rest/.

Source file: HttpGetSetRequestTimeoutActivity.java

  15 
vote

@Override protected String doInBackground(Void... params){
  try {
    final String url=getString(R.string.base_uri) + "/delay/{seconds}";
    HttpComponentsClientHttpRequestFactory requestFactory=new HttpComponentsClientHttpRequestFactory();
    requestFactory.setReadTimeout(requestTimeout);
    RestTemplate restTemplate=new RestTemplate(requestFactory);
    String response=restTemplate.getForObject(url,String.class,serverDelay);
    return response;
  }
 catch (  ResourceAccessException e) {
    Log.e(TAG,e.getMessage(),e);
    if (e.getCause() instanceof SocketTimeoutException) {
      return "Request timed out";
    }
  }
catch (  Exception e) {
    Log.e(TAG,e.getMessage(),e);
    return "An error occurred";
  }
  return null;
}
 

Example 21

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/winterwell/jtwitter/.

Source file: URLConnectionHttpClient.java

  15 
vote

/** 
 * Called on error. What to throw? 
 */
private TwitterException getPage2_ex(Exception ex,String url){
  if (ex instanceof TwitterException)   return (TwitterException)ex;
  if (ex instanceof SocketTimeoutException) {
    return new TwitterException.Timeout(url);
  }
  if (ex instanceof IOException) {
    return new TwitterException.IO((IOException)ex);
  }
  return new TwitterException(ex);
}
 

Example 22

From project andstatus, under directory /src/org/andstatus/app/account/.

Source file: AccountSettings.java

  15 
vote

@Override protected JSONObject doInBackground(Void... arg0){
  JSONObject jso=null;
  int what=MSG_NONE;
  String message="";
  if (!skip) {
    what=MSG_ACCOUNT_INVALID;
    try {
      if (state.myAccount.verifyCredentials(true)) {
        what=MSG_ACCOUNT_VALID;
      }
    }
 catch (    ConnectionException e) {
      what=MSG_CONNECTION_EXCEPTION;
      message=e.toString();
    }
catch (    ConnectionAuthenticationException e) {
      what=MSG_ACCOUNT_INVALID;
    }
catch (    ConnectionCredentialsOfOtherUserException e) {
      what=MSG_CREDENTIALS_OF_OTHER_USER;
    }
catch (    ConnectionUnavailableException e) {
      what=MSG_SERVICE_UNAVAILABLE_ERROR;
    }
catch (    SocketTimeoutException e) {
      what=MSG_SOCKET_TIMEOUT_EXCEPTION;
    }
  }
  try {
    jso=new JSONObject();
    jso.put("what",what);
    jso.put("message",message);
  }
 catch (  JSONException e) {
    e.printStackTrace();
  }
  return jso;
}
 

Example 23

From project avro, under directory /lang/java/ipc/src/test/java/org/apache/avro/.

Source file: TestProtocolHttp.java

  15 
vote

@Test(expected=SocketTimeoutException.class) public void testTimeout() throws Throwable {
  ServerSocket s=new ServerSocket(0);
  HttpTransceiver client=new HttpTransceiver(new URL("http://127.0.0.1:" + s.getLocalPort() + "/"));
  client.setTimeout(100);
  Simple proxy=SpecificRequestor.getClient(Simple.class,client);
  try {
    proxy.hello("foo");
  }
 catch (  AvroRemoteException e) {
    throw e.getCause();
  }
 finally {
    s.close();
  }
}
 

Example 24

From project beanmill_1, under directory /src/main/java/com/traxel/lumbermill/event/.

Source file: EventListenerServer.java

  15 
vote

@Override public void run(){
  while (!stopRequest) {
    try {
      listen(serverSocket.accept());
    }
 catch (    final SocketTimeoutException e) {
    }
catch (    final SocketException e) {
      LOG.error("error during listening",e);
      pleaseStop();
    }
catch (    final IOException e) {
      LOG.error("error during listening",e);
      pleaseStop();
    }
  }
}
 

Example 25

From project blacktie, under directory /stompconnect-1.0/src/main/java/org/codehaus/stomp/tcp/.

Source file: TcpTransportServer.java

  15 
vote

/** 
 * pull Sockets from the ServerSocket
 */
public void run(){
  while (!stopped.get()) {
    Socket socket=null;
    try {
      socket=serverSocket.accept();
      if (socket != null) {
        if (stopped.get()) {
          socket.close();
        }
 else {
          TcpTransport transport=new TcpTransport(socket);
          stompHandlerFactory.assignProtocolConverter(transport);
          transport.start();
          connections.add(transport);
        }
      }
    }
 catch (    SocketTimeoutException ste) {
    }
catch (    Exception e) {
      if (!stopped.get()) {
        log.error("Received accept error: " + e,e);
        try {
          stop();
        }
 catch (        Exception e1) {
          log.error("Failed to shut down: " + e,e);
        }
      }
    }
  }
}
 

Example 26

From project CIShell, under directory /core/org.cishell.utilities/src/org/cishell/utilities/network/.

Source file: DownloadHandler.java

  15 
vote

/** 
 * Perform the communication to the  {@linkplain URL url} defined in thegiven  {@linkplain HttpURLConnection connection}. The numberOfRetries defines the number of attends if the network timeout is reach. Throw exception if connection failed else do nothing Caller is responsible to close the connection if connection success
 * @throws NetworkConnectionException if download timeout due to network connection issue
 * @throws InvalidUrlException if the given URL is not valid
 */
public static void startConnect(HttpURLConnection connection,int numberOfRetries) throws InvalidUrlException, NetworkConnectionException {
  if (numberOfRetries < 0) {
    throw new IllegalArgumentException("numberOfRetries must be more than 0.");
  }
  int retry=numberOfRetries;
  while (retry > 0) {
    try {
      connection.connect();
      break;
    }
 catch (    IOException e) {
      connection.disconnect();
      retry--;
      if (retry == 0) {
        if (e instanceof SocketTimeoutException) {
          throw new NetworkConnectionException("Failed to connect to " + connection.getURL() + ". The host or your local network connection is too weak.",e);
        }
 else {
          throw new InvalidUrlException("Failed to connect to " + connection.getURL() + ". Please valify the URL.",e);
        }
      }
    }
  }
}
 

Example 27

From project cometd, under directory /cometd-java/cometd-java-oort/src/test/java/org/cometd/oort/.

Source file: OortMulticastConfigurerTest.java

  15 
vote

@Before public void assumeMulticast() throws Exception {
  InetAddress multicastAddress=InetAddress.getByName("239.255.0.1");
  MulticastSocket receiver=new MulticastSocket(0);
  receiver.joinGroup(multicastAddress);
  MulticastSocket sender=new MulticastSocket();
  sender.setTimeToLive(1);
  sender.send(new DatagramPacket(new byte[]{1},0,1,multicastAddress,receiver.getLocalPort()));
  sender.close();
  byte[] buffer=new byte[1];
  receiver.setSoTimeout(1000);
  try {
    receiver.receive(new DatagramPacket(buffer,0,buffer.length));
  }
 catch (  SocketTimeoutException x) {
    Assume.assumeNoException(x);
  }
 finally {
    receiver.close();
  }
}
 

Example 28

From project crest, under directory /integration/client/src/main/java/org/codegist/crest/timeout/.

Source file: TimeoutsTest.java

  15 
vote

@Test(expected=SocketTimeoutException.class) public void testSocketTimeout_Timeout() throws Throwable {
  try {
    toTest.socketTimeout(300);
  }
 catch (  CRestException e) {
    Thread.sleep(110);
    throw e.getCause();
  }
}
 

Example 29

From project daap, under directory /src/main/java/org/ardverk/daap/bio/.

Source file: DaapConnectionBIO.java

  15 
vote

public void run(){
  try {
    do {
      try {
        read();
      }
 catch (      SocketTimeoutException err) {
        if (isDaapConnection() && err.bytesTransferred == 0) {
          clearLibraryQueue();
        }
 else {
          throw err;
        }
      }
    }
 while (running && write());
  }
 catch (  DaapStreamException err) {
  }
catch (  SocketException err) {
  }
catch (  IOException err) {
    LOG.error("IOException",err);
  }
 finally {
    close();
  }
}
 

Example 30

From project fed4j, under directory /src/main/java/com/jute/fed4j/engine/component/http/.

Source file: HttpDispatcherImpl_Jakarta.java

  15 
vote

public void run(HttpComponent component){
  this.commponent=component;
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,component.connectTimeout);
  HttpConnectionParams.setSoTimeout(params,component.readTimeout);
  try {
    this.init(component);
    HttpClient httpclient=new MyHttpClient(getConnectionManager(params,component.enablePersistentConnection),params);
    if (component.enableProxy && "http".equals(component.proxyType)) {
      HttpHost proxy=new HttpHost(component.proxyHost,component.proxyPort,component.proxyType);
      httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
    }
    HttpUriRequest request=new HttpRequest(component.method,component.uri);
    MyHttpResponseHandler responseHandler=new MyHttpResponseHandler(component.responseCharset);
    String body=httpclient.execute(request,responseHandler);
    this.onResponse(component,responseHandler.code,body);
  }
 catch (  SocketTimeoutException e) {
    onException(component,-2," socket timeout error occurs: " + e.getMessage());
  }
catch (  ClientProtocolException e) {
    onException(component,-3," error resposed from server: " + e.getMessage());
  }
catch (  IOException e) {
    onException(component,-4," error occurs during dispatch: " + e.getMessage());
  }
catch (  Exception e) {
    onException(component,-5,"error occurs during parsing xml:" + e.getMessage());
  }
}
 

Example 31

From project flexmojos, under directory /flexmojos-testing/flexmojos-tester/src/main/java/net/flexmojos/oss/test/monitor/.

Source file: AbstractSocketThread.java

  15 
vote

public void run(){
  try {
    openServerSocket();
    status=ThreadStatus.STARTED;
    openClientSocket();
    handleRequest();
    if (!ThreadStatus.ERROR.equals(status)) {
      status=ThreadStatus.DONE;
    }
  }
 catch (  SocketTimeoutException e) {
    status=ThreadStatus.ERROR;
    error=e;
  }
catch (  IOException e) {
    status=ThreadStatus.ERROR;
    error=e;
  }
 finally {
    closeClientSocket();
    closeServerSocket();
  }
}
 

Example 32

From project Fotolia-API, under directory /java/libs/httpcomponents-client-4.1.2/examples/org/apache/http/examples/client/.

Source file: ClientExecuteSOCKS.java

  15 
vote

public Socket connectSocket(final Socket socket,final InetSocketAddress remoteAddress,final InetSocketAddress localAddress,final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
  if (remoteAddress == null) {
    throw new IllegalArgumentException("Remote address may not be null");
  }
  if (params == null) {
    throw new IllegalArgumentException("HTTP parameters may not be null");
  }
  Socket sock;
  if (socket != null) {
    sock=socket;
  }
 else {
    sock=createSocket(params);
  }
  if (localAddress != null) {
    sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
    sock.bind(localAddress);
  }
  int timeout=HttpConnectionParams.getConnectionTimeout(params);
  try {
    sock.connect(remoteAddress,timeout);
  }
 catch (  SocketTimeoutException ex) {
    throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"+ remoteAddress.getAddress()+ " timed out");
  }
  return sock;
}
 

Example 33

From project gatein-common, under directory /common/src/main/java/org/gatein/common/net/.

Source file: URLTools.java

  15 
vote

/** 
 * Fetches content from URL as an InputStream. The timeout values must not be negative integers, when it is equals to zero it means that it does not setup a timeout and use the default values.
 * @param url               the URL the URL of the resource
 * @param soTimeoutMillis   the socket connection timeout in millis
 * @param connTimeoutMillis the connection timeout in millis
 * @return the buffered content for the URL
 * @throws IllegalArgumentException if the URL is null or any time out value is negative
 * @since 1.1
 */
public static InputStream getContentAsInputStream(URL url,int soTimeoutMillis,int connTimeoutMillis) throws IOException {
  if (url == null) {
    throw new IllegalArgumentException();
  }
  if (soTimeoutMillis < 0) {
    throw new IllegalArgumentException("No negative socket timeout " + soTimeoutMillis);
  }
  if (connTimeoutMillis < 0) {
    throw new IllegalArgumentException("No negative connection timeout" + connTimeoutMillis);
  }
  if (System.getProperty("http.proxyUser") != null) {
    Authenticator.setDefault(new Authenticator(){
      protected PasswordAuthentication getPasswordAuthentication(){
        return (new PasswordAuthentication(System.getProperty("http.proxyUser"),System.getProperty("http.proxyPassword").toCharArray()));
      }
    }
);
  }
  URLConnection conn;
  try {
    conn=url.openConnection();
  }
 catch (  IOException e) {
    return null;
  }
  conn.setConnectTimeout(soTimeoutMillis);
  conn.setReadTimeout(connTimeoutMillis);
  conn.connect();
  try {
    return new BufferedInputStream(conn.getInputStream());
  }
 catch (  SocketTimeoutException e) {
    log.debug("Time out on: " + url);
    throw e;
  }
}
 

Example 34

From project Gmote, under directory /gmotecommon/src/org/gmote/common/.

Source file: TcpConnection.java

  15 
vote

/** 
 * Allows the caller to read a packet. This should only be used in conjunction with connectToServerSync().
 * @param timeout milliseconds to wait for read operation.
 */
public AbstractPacket readPacket(int timeout) throws IOException, ClassNotFoundException, SocketTimeoutException {
  try {
    connectionSocket.setSoTimeout(timeout);
    return (AbstractPacket)connectionInput.readObject();
  }
  finally {
    connectionSocket.setSoTimeout(0);
  }
}
 

Example 35

From project heritrix3, under directory /modules/src/main/java/org/archive/modules/fetcher/.

Source file: HeritrixHttpMethodRetryHandler.java

  15 
vote

public boolean retryMethod(HttpMethod method,IOException exception,int executionCount){
  if (exception instanceof SocketTimeoutException) {
    return false;
  }
  if (executionCount >= this.maxRetryCount) {
    return false;
  }
  if (exception instanceof NoHttpResponseException) {
    return true;
  }
  if (!method.isRequestSent() && (!(method instanceof PostMethod))) {
    return true;
  }
  return false;
}
 

Example 36

From project httpserver, under directory /src/test/java/.

Source file: B6393710.java

  15 
vote

public static void main(String[] args) throws Exception {
  Handler handler=new Handler();
  InetSocketAddress addr=new InetSocketAddress(0);
  HttpServer server=HttpServer.create(addr,0);
  HttpContext ctx=server.createContext("/test",handler);
  ctx.setAuthenticator(new BasicAuthenticator("test"){
    public boolean checkCredentials(    String user,    String pass){
      return user.equals("fred") && pass.equals("fredpassword");
    }
  }
);
  server.start();
  Socket s=new Socket("localhost",server.getAddress().getPort());
  s.setSoTimeout(5000);
  OutputStream os=s.getOutputStream();
  os.write(cmd.getBytes());
  InputStream is=s.getInputStream();
  try {
    ok=readAndCheck(is,"401 Unauthorized") && readAndCheck(is,"200 OK");
  }
 catch (  SocketTimeoutException e) {
    System.out.println("Did not received expected data");
    ok=false;
  }
 finally {
    s.close();
    server.stop(2);
  }
  if (requests != 1) {
    throw new RuntimeException("server handler did not receive the request");
  }
  if (!ok) {
    throw new RuntimeException("did not get 200 OK");
  }
  System.out.println("OK");
}
 

Example 37

From project ihatovgram, under directory /src/client/android/ihatovgram/lib/httpcomponents-client-4.1.3/examples/org/apache/http/examples/client/.

Source file: ClientExecuteSOCKS.java

  15 
vote

public Socket connectSocket(final Socket socket,final InetSocketAddress remoteAddress,final InetSocketAddress localAddress,final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
  if (remoteAddress == null) {
    throw new IllegalArgumentException("Remote address may not be null");
  }
  if (params == null) {
    throw new IllegalArgumentException("HTTP parameters may not be null");
  }
  Socket sock;
  if (socket != null) {
    sock=socket;
  }
 else {
    sock=createSocket(params);
  }
  if (localAddress != null) {
    sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
    sock.bind(localAddress);
  }
  int timeout=HttpConnectionParams.getConnectionTimeout(params);
  try {
    sock.connect(remoteAddress,timeout);
  }
 catch (  SocketTimeoutException ex) {
    throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"+ remoteAddress.getAddress()+ " timed out");
  }
  return sock;
}
 

Example 38

From project IOCipherServer, under directory /src/Acme/Serve/.

Source file: Serve.java

  15 
vote

public void run(){
  if (socket == null)   return;
  try {
    do {
      restart();
      parseRequest();
      if (asyncMode != null) {
        asyncTimeout=asyncMode.getTimeout();
        if (asyncTimeout > 0)         asyncTimeout+=System.currentTimeMillis();
        return;
      }
      finalizerequest();
    }
 while (keepAlive && serve.isKeepAlive() && timesRequested < serve.getMaxTimesConnectionUse());
  }
 catch (  IOException ioe) {
    if (ioe instanceof SocketTimeoutException) {
    }
 else {
      String errMsg=ioe.getMessage();
      if ((errMsg == null || errMsg.indexOf("ocket closed") < 0) && ioe instanceof java.nio.channels.AsynchronousCloseException == false)       if (socket != null)       serve.log("TJWS: IO error: " + ioe + " in processing a request from "+ socket.getInetAddress()+ ":"+ socket.getLocalPort()+ " / "+ socket.getClass().getName());
 else       serve.log("TJWS: IO error: " + ioe + "(socket NULL)");
 else synchronized (this) {
        socket=null;
      }
    }
  }
 finally {
    if (asyncMode == null)     close();
  }
}
 

Example 39

From project jackrabbit-oak, under directory /oak-mk-remote/src/main/java/org/apache/jackrabbit/mk/server/.

Source file: Server.java

  15 
vote

/** 
 * Process a connection attempt by a client.
 * @param socket client socket
 */
void process(Socket socket){
  try {
    socket.setTcpNoDelay(true);
  }
 catch (  IOException e) {
  }
  HttpProcessor processor=new HttpProcessor(socket,new Servlet(){
    @Override public void service(    Request request,    Response response) throws IOException {
      Server.this.service(request,response);
    }
  }
);
  try {
    processor.process();
  }
 catch (  SocketTimeoutException e) {
  }
catch (  EOFException e) {
  }
catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 40

From project jdeltasync, under directory /src/main/java/com/googlecode/jdeltasync/pop/.

Source file: PopProxy.java

  15 
vote

@Override public void run(){
  try {
    log.info("Listening on " + bindAddress);
    while (!isInterrupted()) {
      try {
        Socket socket=serverSocket.accept();
        PopHandler handler=new PopHandler(socket,deltaSyncClient,store);
        handler.setUseHardwiredInbox(useHardwiredInbox);
        executor.execute(handler);
      }
 catch (      SocketTimeoutException e) {
      }
    }
  }
 catch (  Throwable t) {
    log.error("Exception caught",t);
  }
}
 

Example 41

From project JGlobus, under directory /gridftp/src/main/java/org/globus/ftp/vanilla/.

Source file: FTPControlChannel.java

  15 
vote

private int checkSocketDone(Flag aborted,int ioDelay,int maxWait) throws ServerException, IOException, InterruptedException {
  int oldTOValue=this.socket.getSoTimeout();
  int c=-10;
  int time=0;
  boolean done=false;
  if (ioDelay <= 0) {
    ioDelay=2000;
  }
  while (!done) {
    try {
      if (aborted.flag) {
        throw new InterruptedException();
      }
      this.socket.setSoTimeout(ioDelay);
      ftpIn.mark(2);
      c=ftpIn.read();
      done=true;
    }
 catch (    SocketTimeoutException e) {
      logger.debug("temp timeout" + e);
    }
catch (    Exception e) {
      throw new InterruptedException();
    }
 finally {
      ftpIn.reset();
      this.socket.setSoTimeout(oldTOValue);
    }
    time+=ioDelay;
    if (time > maxWait && maxWait != WAIT_FOREVER) {
      throw new ServerException(ServerException.REPLY_TIMEOUT);
    }
  }
  return c;
}
 

Example 42

From project joshua, under directory /src/joshua/util/.

Source file: SocketUtility.java

  15 
vote

public static ClientConnection open_connection_client(String hostname,int port){
  ClientConnection res=new ClientConnection();
  try {
    InetAddress addr=InetAddress.getByName(hostname);
    SocketAddress sockaddr=new InetSocketAddress(addr,port);
    res.socket=new Socket();
    int timeoutMs=3000;
    res.socket.connect(sockaddr,timeoutMs);
    res.socket.setKeepAlive(true);
    res.in=new BufferedReader(new InputStreamReader(res.socket.getInputStream()));
    res.out=new PrintWriter(new OutputStreamWriter(res.socket.getOutputStream()));
  }
 catch (  UnknownHostException e) {
    System.out.println("unknown host exception");
    System.exit(1);
  }
catch (  SocketTimeoutException e) {
    System.out.println("socket timeout exception");
    System.exit(1);
  }
catch (  IOException e) {
    System.out.println("io exception");
    System.exit(1);
  }
  return res;
}
 

Example 43

From project jsmpp, under directory /jsmpp/src/main/java/org/jsmpp/session/.

Source file: SMPPServerSession.java

  15 
vote

private void readPDU(){
  try {
    Command pduHeader=null;
    byte[] pdu=null;
    pduHeader=pduReader.readPDUHeader(in);
    pdu=pduReader.readPDU(in,pduHeader);
    PDUProcessServerTask task=new PDUProcessServerTask(pduHeader,pdu,sessionContext.getStateProcessor(),sessionContext,responseHandler,onIOExceptionTask);
    executorService.execute(task);
  }
 catch (  InvalidCommandLengthException e) {
    logger.warn("Receive invalid command length",e);
    try {
      pduSender().sendGenericNack(out,SMPPConstant.STAT_ESME_RINVCMDLEN,0);
    }
 catch (    IOException ee) {
      logger.warn("Failed sending generic nack",ee);
    }
    unbindAndClose();
  }
catch (  SocketTimeoutException e) {
    notifyNoActivity();
  }
catch (  IOException e) {
    close();
  }
}
 

Example 44

From project Kayak, under directory /Kayak-core/src/main/java/com/github/kayak/core/.

Source file: SocketcandConnection.java

  15 
vote

/** 
 * This method reads data from an  {@link InputStreamReader} and tries toextract elements that are enclosed by '<' and '>'. The Reader must be set via setInput() before calling getElement(). A buffer is used to construct elements that need multiple reads. Whitespace between the elements is ignored. The method blocks until an element can be returned.
 * @param in the InputStreamReader from which should be read
 * @return the first element read
 * @throws IOException
 */
protected String getElement() throws IOException, InterruptedException, SocketTimeoutException {
  int pos=0;
  boolean inElement=false;
  while (true) {
    char c=(char)reader.read();
    if (!inElement) {
      if (c == '<') {
        inElement=true;
        elementBuffer[pos]=c;
        pos++;
      }
    }
 else {
      if (pos >= ELEMENT_SIZE - 1) {
        logger.log(Level.WARNING,"Found frame that is too large. Ignoring...");
        pos=0;
        inElement=false;
      }
 else       if (c == '>') {
        elementBuffer[pos]=c;
        pos++;
        break;
      }
 else {
        elementBuffer[pos]=c;
        pos++;
      }
    }
  }
  return String.valueOf(elementBuffer,0,pos);
}
 

Example 45

From project legacy-maven-support, under directory /maven-plugin/src/main/java/hudson/maven/.

Source file: AbstractMavenProcessFactory.java

  15 
vote

/** 
 * Starts maven process.
 */
public ProcessCache.NewProcess newProcess(BuildListener listener,OutputStream out) throws IOException, InterruptedException {
  if (MavenProcessFactory.debug)   listener.getLogger().println("Using env variables: " + envVars);
  try {
    final Acceptor acceptor=launcher.getChannel().call(new SocketHandler());
    Charset charset;
    try {
      charset=Charset.forName(launcher.getChannel().call(new GetCharset()));
    }
 catch (    UnsupportedCharsetException e) {
      charset=Charset.forName("iso-8859-1");
    }
    MavenConsoleAnnotator mca=new MavenConsoleAnnotator(out,charset);
    final ArgumentListBuilder cmdLine=buildMavenAgentCmdLine(listener,acceptor.getPort());
    String[] cmds=cmdLine.toCommandArray();
    final Proc proc=launcher.launch().cmds(cmds).envs(envVars).stdout(mca).pwd(workDir).start();
    Connection con;
    try {
      con=acceptor.accept();
    }
 catch (    SocketTimeoutException e) {
      if (!proc.isAlive())       throw new AbortException("Failed to launch Maven. Exit code = " + proc.join());
      throw e;
    }
    return new NewProcess(Channels.forProcess("Channel to Maven " + Arrays.toString(cmds),Computer.threadPoolForRemoting,new BufferedInputStream(con.in),new BufferedOutputStream(con.out),listener.getLogger(),proc),proc);
  }
 catch (  IOException e) {
    if (fixNull(e.getMessage()).contains("java: not found")) {
      JDK jdk=mms.getJDK();
      if (jdk == null)       throw new IOException2(mms.getDisplayName() + " is not configured with a JDK, but your PATH doesn't include Java",e);
    }
    throw e;
  }
}
 

Example 46

From project liquidfeedback-java-sdk, under directory /core/src/main/java/lfapi/v2/services/impl/.

Source file: LiquidFeedbackApiGateway.java

  15 
vote

/** 
 * Call api delete.
 * @param ub the ub
 * @param expected the expected
 * @return the input stream
 */
protected InputStream callDelete(LiquidFeedbackServiceBase.URL.Builder ub,int expected){
  String apiUrl=ub.buildUrl();
  try {
    URL url=new URL(mBaseUrl + apiUrl);
    HttpURLConnection request=(HttpURLConnection)url.openConnection();
    if (mConnectTimeout != null) {
      request.setConnectTimeout(mConnectTimeout);
    }
    if (mReadTimeout != null) {
      request.setReadTimeout(mReadTimeout);
    }
    for (    String headerName : mRequestHeaders.keySet()) {
      request.setRequestProperty(headerName,mRequestHeaders.get(headerName));
    }
    request.setRequestMethod("DELETE");
    request.connect();
    if (request.getResponseCode() != expected) {
      throw new LiquidFeedbackException(LiquidFeedbackException.ErrorType.RESPONSE_ERROR,convertStreamToString(getWrappedInputStream(request.getErrorStream(),Constants.GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()))));
    }
 else {
      return getWrappedInputStream(request.getInputStream(),Constants.GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()));
    }
  }
 catch (  SocketTimeoutException ste) {
    throw new LiquidFeedbackException(ste,ErrorType.TIMEOUT);
  }
catch (  IOException e) {
    throw new LiquidFeedbackException(e,ErrorType.RESPONSE_ERROR);
  }
 finally {
  }
}
 

Example 47

From project livetribe-slp, under directory /core/src/main/java/org/livetribe/slp/spi/net/.

Source file: SocketTCPConnector.java

  15 
vote

public byte[] writeAndRead(InetSocketAddress address,byte[] bytes){
  Socket socket=null;
  try {
    socket=new Socket(address.getAddress(),address.getPort());
    write(socket,bytes);
    return read(socket);
  }
 catch (  SocketTimeoutException x) {
    throw new ServiceLocationException(x,SLPError.NETWORK_TIMED_OUT);
  }
catch (  IOException x) {
    throw new ServiceLocationException(x,SLPError.NETWORK_ERROR);
  }
 finally {
    close(socket);
  }
}
 

Example 48

From project lullaby, under directory /src/net/sileht/lullaby/player/.

Source file: StreamCacher.java

  15 
vote

@Override public void run(){
  while (!mStopServer) {
    try {
      final Socket client=mSocket.accept();
      if (client == null) {
        continue;
      }
      Runnable r=new Runnable(){
        @Override public void run(){
          processCachingAndStreaming(client);
        }
      }
;
      new Thread(r).start();
    }
 catch (    SocketTimeoutException e) {
    }
catch (    IOException e) {
      Log.e(TAG,"Error connecting to client",e);
    }
  }
}
 

Example 49

From project medsavant, under directory /MedSavantShared/src/org/ut/biolab/medsavant/util/.

Source file: SeekableFTPStream.java

  15 
vote

private int readFromStream(byte[] bytes,int offset,int len) throws IOException {
  FTPClient client=getFTPClient();
  if (position != 0) {
    client.setRestartOffset(position);
  }
  InputStream is=client.retrieveFileStream(fileName);
  long oldPos=position;
  if (is != null) {
    int n=0;
    while (n < len) {
      int bytesRead=is.read(bytes,offset + n,len - n);
      if (bytesRead < 0) {
        if (n == 0)         return -1;
 else         break;
      }
      n+=bytesRead;
    }
    is.close();
    LOG.info(String.format("FTP read %d bytes at %d: %02x %02x %02x %02x %02x %02x %02x %02x...",len,oldPos,bytes[offset],bytes[offset + 1],bytes[offset + 2],bytes[offset + 3],bytes[offset + 4],bytes[offset + 5],bytes[offset + 6],bytes[offset + 7]));
    try {
      client.completePendingCommand();
    }
 catch (    FTPConnectionClosedException suppressed) {
    }
catch (    SocketTimeoutException stx) {
      LOG.info("Timed out during read.  Disconnecting.");
      disconnect();
    }
    position+=n;
    return n;
  }
 else {
    String msg=String.format("Unable to retrieve input stream for file (reply code %d).",client.getReplyCode());
    LOG.error(msg);
    throw new IOException(msg);
  }
}
 

Example 50

From project milton, under directory /milton/milton-client/src/main/java/com/ettrema/httpclient/.

Source file: Host.java

  15 
vote

private synchronized void doOptions(String url) throws NotFoundException, java.net.ConnectException, NotAuthorizedException, java.net.UnknownHostException, SocketTimeoutException, IOException, com.ettrema.httpclient.HttpException {
  notifyStartRequest();
  String uri=url;
  log.trace("doOptions: {}",url);
  HttpOptions m=new HttpOptions(uri);
  InputStream in=null;
  try {
    int res=Utils.executeHttpWithStatus(client,m,null);
    log.trace("result code: " + res);
    if (res == 301 || res == 302) {
      return;
    }
    Utils.processResultCode(res,url);
  }
 catch (  ConflictException ex) {
    throw new RuntimeException(ex);
  }
catch (  BadRequestException ex) {
    throw new RuntimeException(ex);
  }
 finally {
    Utils.close(in);
    notifyFinishRequest();
  }
}
 

Example 51

From project milton2, under directory /milton-client/src/main/java/io/milton/httpclient/.

Source file: Host.java

  15 
vote

private synchronized void doOptions(String url) throws NotFoundException, java.net.ConnectException, NotAuthorizedException, java.net.UnknownHostException, SocketTimeoutException, IOException, io.milton.httpclient.HttpException {
  notifyStartRequest();
  String uri=url;
  log.trace("doOptions: {}",url);
  HttpOptions m=new HttpOptions(uri);
  InputStream in=null;
  try {
    int res=Utils.executeHttpWithStatus(client,m,null);
    log.trace("result code: " + res);
    if (res == 301 || res == 302) {
      return;
    }
    Utils.processResultCode(res,url);
  }
 catch (  ConflictException ex) {
    throw new RuntimeException(ex);
  }
catch (  BadRequestException ex) {
    throw new RuntimeException(ex);
  }
 finally {
    Utils.close(in);
    notifyFinishRequest();
  }
}
 

Example 52

From project netty, under directory /transport/src/main/java/io/netty/channel/socket/oio/.

Source file: OioDatagramChannel.java

  15 
vote

@Override protected int doReadMessages(MessageBuf<Object> buf) throws Exception {
  if (readSuspended) {
    try {
      Thread.sleep(SO_TIMEOUT);
    }
 catch (    InterruptedException e) {
    }
    return 0;
  }
  int packetSize=config().getReceivePacketSize();
  byte[] data=new byte[packetSize];
  tmpPacket.setData(data);
  try {
    socket.receive(tmpPacket);
    InetSocketAddress remoteAddr=(InetSocketAddress)tmpPacket.getSocketAddress();
    if (remoteAddr == null) {
      remoteAddr=remoteAddress();
    }
    buf.add(new DatagramPacket(Unpooled.wrappedBuffer(data,tmpPacket.getOffset(),tmpPacket.getLength()),remoteAddr));
    if (readSuspended) {
      return 0;
    }
 else {
      return 1;
    }
  }
 catch (  SocketTimeoutException e) {
    return 0;
  }
catch (  SocketException e) {
    if (!e.getMessage().toLowerCase(Locale.US).contains("socket closed")) {
      throw e;
    }
    return -1;
  }
}
 

Example 53

From project npr-android-app, under directory /src/org/npr/android/news/.

Source file: StreamProxy.java

  15 
vote

@Override public void run(){
  Log.d(LOG_TAG,"running");
  while (isRunning) {
    try {
      Socket client=socket.accept();
      if (client == null) {
        continue;
      }
      Log.d(LOG_TAG,"client connected");
      HttpRequest request=readRequest(client);
      processRequest(request,client);
    }
 catch (    SocketTimeoutException e) {
    }
catch (    IOException e) {
      Log.e(LOG_TAG,"Error connecting to client",e);
    }
  }
  Log.d(LOG_TAG,"Proxy interrupted. Shutting down.");
}
 

Example 54

From project nuxeo-distribution, under directory /nuxeo-launcher/src/main/java/org/nuxeo/launcher/monitoring/.

Source file: StatusServletClient.java

  15 
vote

/** 
 * @return true if succeed to connect on StatusServlet
 * @throws SocketTimeoutException
 */
public boolean init() throws SocketTimeoutException {
  try {
    timeout=TIMEOUT;
    connect("GET");
  }
 catch (  SocketTimeoutException e) {
    throw e;
  }
catch (  IOException e) {
    return false;
  }
 finally {
    disconnect();
  }
  return true;
}
 

Example 55

From project onebusaway-uk, under directory /onebusaway-uk-network-rail-gtfs-realtime/src/main/java/org/onebusaway/uk/network_rail/gtfs_realtime/.

Source file: MessageListenerService.java

  15 
vote

private MessagePayload getNextMessage() throws Exception {
  StompFrame message=null;
  try {
    message=_connection.receive();
  }
 catch (  SocketTimeoutException ex) {
    _log.warn("timeout");
    return null;
  }
  MessagePayload payload=new MessagePayload();
  payload.type=getMessageTypeForMessage(message);
  payload.body=message.getBody();
  _connection.ack(message,"tx2");
  return payload;
}
 

Example 56

From project OpenSettlers, under directory /src/java/soc/client/.

Source file: ConnectOrPracticePanel.java

  15 
vote

/** 
 * Check with the  {@link java.lang.SecurityManager} about being a tcp server.Port  {@link PlayerClient#SOC_PORT_DEFAULT} and some subsequent ports are checked (to be above 1024).
 * @return True if we have perms to start a server and listen on a port
 */
public static boolean checkCanLaunchServer(){
  try {
    SecurityManager sm=System.getSecurityManager();
    if (sm == null)     return true;
    try {
      sm.checkAccept("localhost",PlayerClient.SOC_PORT_DEFAULT);
      sm.checkListen(PlayerClient.SOC_PORT_DEFAULT);
    }
 catch (    SecurityException se) {
      return false;
    }
  }
 catch (  SecurityException se) {
    int port=PlayerClient.SOC_PORT_DEFAULT;
    for (int i=0; i <= 100; ++i) {
      ServerSocket ss=null;
      try {
        ss=new ServerSocket(i + port);
        ss.setReuseAddress(true);
        ss.setSoTimeout(11);
        ss.accept();
        ss.close();
      }
 catch (      SocketTimeoutException ste) {
        try {
          ss.close();
        }
 catch (        IOException ie) {
        }
        return true;
      }
catch (      IOException ie) {
      }
catch (      SecurityException se2) {
        return false;
      }
    }
  }
  return false;
}
 

Example 57

From project OWASP-WebScarab, under directory /src/org/owasp/webscarab/model/.

Source file: Request.java

  15 
vote

/** 
 * initialises the Request from the supplied InputStream, using the supplied Url as a base. This will generally be useful where we are acting as a web server, and reading a line like "GET / HTTP/1.0". The request Url is then created relative to the supplied Url.
 * @param is the InputStream to read from
 * @param base the base Url to use for relative Urls
 * @throws IOException propagates any IOExceptions thrown by the InputStream
 */
public void read(InputStream is,HttpUrl base) throws IOException {
  String line=null;
  _logger.finer("Base: " + base);
  try {
    line=readLine(is);
    _logger.finest("Request: " + line);
  }
 catch (  SocketTimeoutException ste) {
    return;
  }
  if (line == null || line.equals("")) {
    return;
  }
  String[] parts=line.split(" ");
  if (parts.length == 2 || parts.length == 3) {
    setMethod(parts[0]);
    if (getMethod().equalsIgnoreCase("CONNECT")) {
      setURL(new HttpUrl("https://" + parts[1] + "/"));
    }
 else {
      setURL(new HttpUrl(base,parts[1]));
    }
  }
 else {
    throw new IOException("Invalid request line reading from the InputStream '" + line + "'");
  }
  if (parts.length == 3) {
    setVersion(parts[2]);
  }
 else {
    setVersion("HTTP/0.9");
  }
  super.read(is);
  if (_method.equals("CONNECT") || _method.equals("GET") || _method.equals("HEAD")|| _method.equals("TRACE")) {
    setNoBody();
  }
}
 

Example 58

From project PhonePledge, under directory /src/phonepledge/client/.

Source file: PledgeClient.java

  15 
vote

private boolean connect(){
  try {
    System.out.println("Connecting to server on port " + PledgeServer.SERVER_PORT);
    sock=new Socket(serverAddress,PledgeServer.SERVER_PORT);
    System.out.println("Connected to server");
    isConnected=true;
  }
 catch (  ConnectException e) {
    System.err.printf("Could not connect to server at %s:%d. Is it running?\n",serverAddress,PledgeServer.SERVER_PORT);
  }
catch (  SocketTimeoutException e) {
    System.err.println("Timeout connecting to Visualizer: " + e.getMessage());
    return false;
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  return isConnected;
}
 

Example 59

From project platform_3, under directory /http-client/src/test/java/com/proofpoint/http/client/.

Source file: ApacheHttpClientTest.java

  15 
vote

@Test(expectedExceptions=SocketTimeoutException.class) public void testConnectTimeout() throws Exception {
  ServerSocket serverSocket=new ServerSocket(0,1);
  Socket clientSocket=new Socket("localhost",serverSocket.getLocalPort());
  HttpClientConfig config=new HttpClientConfig();
  config.setConnectTimeout(new Duration(5,TimeUnit.MILLISECONDS));
  ApacheHttpClient client=new ApacheHttpClient(config);
  Request request=prepareGet().setUri(URI.create("http://localhost:" + serverSocket.getLocalPort() + "/")).build();
  try {
    client.execute(request,new ResponseToStringHandler());
  }
  finally {
    clientSocket.close();
    serverSocket.close();
  }
}
 

Example 60

From project platform_external_apache-http, under directory /src/org/apache/http/conn/.

Source file: MultihomePlainSocketFactory.java

  15 
vote

/** 
 * Attempts to connects the socket to any of the  {@link InetAddress}es the  given host name resolves to. If connection to all addresses fail, the   last I/O exception is propagated to the caller.
 * @param sock socket to connect to any of the given addresses
 * @param host Host name to connect to
 * @param port the port to connect to
 * @param localAddress local address
 * @param localPort local port
 * @param params HTTP parameters 
 * @throws IOException if an error occurs during the connection
 * @throws SocketTimeoutException if timeout expires before connecting
 */
public Socket connectSocket(Socket sock,String host,int port,InetAddress localAddress,int localPort,HttpParams params) throws IOException {
  if (host == null) {
    throw new IllegalArgumentException("Target host may not be null.");
  }
  if (params == null) {
    throw new IllegalArgumentException("Parameters may not be null.");
  }
  if (sock == null)   sock=createSocket();
  if ((localAddress != null) || (localPort > 0)) {
    if (localPort < 0)     localPort=0;
    InetSocketAddress isa=new InetSocketAddress(localAddress,localPort);
    sock.bind(isa);
  }
  int timeout=HttpConnectionParams.getConnectionTimeout(params);
  InetAddress[] inetadrs=InetAddress.getAllByName(host);
  List<InetAddress> addresses=new ArrayList<InetAddress>(inetadrs.length);
  addresses.addAll(Arrays.asList(inetadrs));
  Collections.shuffle(addresses);
  IOException lastEx=null;
  for (  InetAddress address : addresses) {
    try {
      sock.connect(new InetSocketAddress(address,port),timeout);
      break;
    }
 catch (    SocketTimeoutException ex) {
      throw ex;
    }
catch (    IOException ex) {
      sock=new Socket();
      lastEx=ex;
    }
  }
  if (lastEx != null) {
    throw lastEx;
  }
  return sock;
}
 

Example 61

From project Possom, under directory /generic.sesam/search-command-control/default/src/main/java/no/sesat/search/mode/command/.

Source file: GoogleSearchCommand.java

  15 
vote

@Override public ResultList<ResultItem> execute(){
  final ResultList<ResultItem> result=new BasicResultList<ResultItem>();
  final BufferedReader reader;
  try {
    reader=getRestful().getHttpReader("UTF8");
    if (null != reader) {
      final StringBuilder builder=new StringBuilder();
      String line;
      while (null != (line=reader.readLine())) {
        builder.append(line);
      }
      final DynaBean bean=(DynaBean)JSONSerializer.toJava(JSONSerializer.toJSON(builder.toString()));
      final DynaBean data=(DynaBean)bean.get("responseData");
      final String totalResults=((DynaBean)data.get("cursor")).get("estimatedResultCount").toString();
      result.setHitCount(Integer.parseInt(totalResults));
      final List<DynaBean> results=(List<DynaBean>)data.get("results");
      for (      DynaBean r : results) {
        result.addResult(createItem(r));
      }
    }
  }
 catch (  SocketTimeoutException ste) {
    LOG.error(getSearchConfiguration().getName() + " --> " + ste.getMessage());
    return new BasicResultList<ResultItem>();
  }
catch (  IOException ex) {
    throw new SearchCommandException(ex);
  }
  return result;
}
 

Example 62

From project PSP-NetParty, under directory /src/pspnetparty/client/swt/.

Source file: RoomWindow.java

  15 
vote

private void connectToRoomServer(final InetSocketAddress socketAddress){
  Runnable task=new Runnable(){
    @Override public void run(){
      try {
        application.connectTcp(socketAddress,roomProtocol);
        return;
      }
 catch (      SocketTimeoutException e) {
        ErrorLog log=new ErrorLog("??????????????????????");
        widgets.logViewer.appendMessage(log);
      }
catch (      IOException e) {
        ErrorLog log=new ErrorLog(e);
        widgets.logViewer.appendMessage(log);
      }
catch (      RuntimeException e) {
        ErrorLog log=new ErrorLog(e);
        widgets.logViewer.appendMessage(log);
      }
      changeStateTo(SessionState.OFFLINE);
    }
  }
;
  application.execute(task);
}
 

Example 63

From project Rhybudd, under directory /src/net/networksaremadeofstring/rhybudd/.

Source file: ZenossAPIv2.java

  15 
vote

public JSONObject GetEvents(Boolean Critical,Boolean Error,Boolean Warning,Boolean Info,Boolean Debug,boolean ProductionOnly,boolean Zenoss41) throws JSONException, ClientProtocolException, IOException, SocketTimeoutException, SocketException {
  String SeverityLevels="";
  if (Critical)   SeverityLevels+="5,";
  if (Error)   SeverityLevels+="4,";
  if (Warning)   SeverityLevels+="3,";
  if (Info)   SeverityLevels+="2,";
  if (Debug)   SeverityLevels+="1,";
  if (SeverityLevels.length() > 1) {
    SeverityLevels=SeverityLevels.substring(0,SeverityLevels.length() - 1);
  }
  return this.GetEvents(SeverityLevels,ProductionOnly,Zenoss41);
}
 

Example 64

From project riak-java-client, under directory /src/main/java/com/basho/riak/pbc/.

Source file: RiakConnectionPool.java

  15 
vote

/** 
 * @param attempts
 * @return
 */
private RiakConnection createConnection(int attempts) throws IOException {
  try {
    if (permits.tryAcquire(connectionWaitTimeoutNanos,TimeUnit.NANOSECONDS)) {
      boolean releasePermit=true;
      try {
        RiakConnection connection=new RiakConnection(host,port,bufferSizeKb,this,TimeUnit.MILLISECONDS.convert(connectionWaitTimeoutNanos,TimeUnit.NANOSECONDS),requestTimeoutMillis);
        releasePermit=false;
        return connection;
      }
 catch (      SocketTimeoutException e) {
        throw new AcquireConnectionTimeoutException("timeout from socket connection " + e.getMessage(),e);
      }
catch (      IOException e) {
        throw e;
      }
 finally {
        if (releasePermit) {
          permits.release();
        }
      }
    }
 else {
      throw new AcquireConnectionTimeoutException("timeout acquiring connection permit from pool");
    }
  }
 catch (  InterruptedException e) {
    Thread.currentThread().interrupt();
    if (attempts > 0) {
      return createConnection(attempts - 1);
    }
 else {
      throw new IOException("repeatedly interrupted whilst waiting to acquire connection");
    }
  }
}
 

Example 65

From project SchoolPlanner4Untis, under directory /src/edu/htl3r/schoolplanner/backend/network/json/.

Source file: JSONNetwork.java

  15 
vote

private ErrorMessage getErrorMessage(Exception e){
  ErrorMessage errorMessage=new ErrorMessage();
  int errorCode=ErrorCodes.IO_EXCEPTION;
  if (e instanceof JSONException) {
    errorCode=ErrorCodes.JSON_EXCEPTION;
  }
 else   if (e instanceof HttpHostConnectException)   errorCode=ErrorCodes.HTTP_HOST_CONNECTION_EXCEPTION;
 else   if (e instanceof UnknownHostException)   errorCode=ErrorCodes.UNKNOWN_HOST_EXCEPTION;
 else   if (e instanceof SSLForcedButUnavailableException)   errorCode=ErrorCodes.SSL_FORCED_BUT_UNAVAILABLE;
 else   if (e instanceof SocketTimeoutException)   errorCode=ErrorCodes.SOCKET_TIMEOUT_EXCEPTION;
 else   if (e instanceof WrongPortNumberException)   errorCode=ErrorCodes.WRONG_PORT_NUMBER;
  errorMessage.setErrorCode(errorCode);
  errorMessage.setException(e);
  return errorMessage;
}
 

Example 66

From project SimpleHTTPServer, under directory /src/test/java/org/simpleHTTPServer/.

Source file: ServerMultiThreadedWorkersTestCase.java

  15 
vote

/** 
 * Test that a 2nd connection can be made while a first one is still open - very basic multithreading test
 * @throws Exception If test has any errors
 */
public void testTwoParallelRequests() throws Exception {
  Socket socket1=new Socket(InetAddress.getLocalHost(),port);
  PrintWriter pw=new PrintWriter(socket1.getOutputStream());
  pw.print("GET");
  Socket socket2=new Socket(InetAddress.getLocalHost(),port);
  socket2.setSoTimeout(20);
  TestUtil.sendRequest(socket2);
  try {
    TestUtil.checkResponse(socket2);
  }
 catch (  SocketTimeoutException ex) {
    fail("Test failed, second socket did not respond while first one still busy: " + ex.toString());
  }
  socket1.close();
  socket2.close();
}
 

Example 67

From project sisu-litmus, under directory /litmus-testsupport/src/main/java/org/sonatype/sisu/litmus/testsupport/hamcrest/.

Source file: URLRespondsWithStatusMatcher.java

  15 
vote

@Override protected boolean matchesSafely(URL item){
  this.urlString=item.toString();
  try {
    URL url=new URL(item.toString());
    HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
    if (timeout > -1) {
      urlConnection.setConnectTimeout(timeout);
      urlConnection.setReadTimeout(timeout);
    }
    urlConnection.setUseCaches(false);
    urlConnection.connect();
    this.receivedStatusCode=urlConnection.getResponseCode();
  }
 catch (  SocketTimeoutException ste) {
    timedOut=true;
    this.e=ste;
  }
catch (  IOException ioe) {
    this.e=ioe;
  }
catch (  Exception e) {
    this.e=e;
  }
  return (!timedOut && e == null && this.receivedStatusCode == this.statusCode);
}
 

Example 68

From project spring-android-samples, under directory /spring-android-showcase/client/src/org/springframework/android/showcase/rest/.

Source file: HttpGetSetRequestTimeoutActivity.java

  15 
vote

@Override protected String doInBackground(Void... params){
  try {
    final String url=getString(R.string.base_uri) + "/delay/{seconds}";
    HttpComponentsClientHttpRequestFactory requestFactory=new HttpComponentsClientHttpRequestFactory();
    requestFactory.setReadTimeout(requestTimeout);
    RestTemplate restTemplate=new RestTemplate(requestFactory);
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    String response=restTemplate.getForObject(url,String.class,serverDelay);
    return response;
  }
 catch (  ResourceAccessException e) {
    Log.e(TAG,e.getMessage(),e);
    if (e.getCause() instanceof SocketTimeoutException) {
      return "Request timed out";
    }
  }
catch (  Exception e) {
    Log.e(TAG,e.getMessage(),e);
    return "An error occurred";
  }
  return null;
}
 

Example 69

From project subsonic, under directory /subsonic-android/src/github/daneren2005/dsub/service/ssl/.

Source file: SSLSocketFactory.java

  15 
vote

/** 
 * @since 4.1
 */
public Socket connectSocket(final Socket sock,final InetSocketAddress remoteAddress,final InetSocketAddress localAddress,final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
  if (remoteAddress == null) {
    throw new IllegalArgumentException("Remote address may not be null");
  }
  if (params == null) {
    throw new IllegalArgumentException("HTTP parameters may not be null");
  }
  SSLSocket sslsock=(SSLSocket)(sock != null ? sock : createSocket());
  if (localAddress != null) {
    sslsock.bind(localAddress);
  }
  int connTimeout=HttpConnectionParams.getConnectionTimeout(params);
  int soTimeout=HttpConnectionParams.getSoTimeout(params);
  try {
    sslsock.connect(remoteAddress,connTimeout);
  }
 catch (  SocketTimeoutException ex) {
    throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"+ remoteAddress.getAddress()+ " timed out");
  }
  sslsock.setSoTimeout(soTimeout);
  if (this.hostnameVerifier != null) {
    try {
      this.hostnameVerifier.verify(remoteAddress.getHostName(),sslsock);
    }
 catch (    IOException iox) {
      try {
        sslsock.close();
      }
 catch (      Exception x) {
      }
      throw iox;
    }
  }
  return sslsock;
}
 

Example 70

From project Subsonic-Android, under directory /src/net/sourceforge/subsonic/androidapp/service/ssl/.

Source file: SSLSocketFactory.java

  15 
vote

/** 
 * @since 4.1
 */
public Socket connectSocket(final Socket sock,final InetSocketAddress remoteAddress,final InetSocketAddress localAddress,final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
  if (remoteAddress == null) {
    throw new IllegalArgumentException("Remote address may not be null");
  }
  if (params == null) {
    throw new IllegalArgumentException("HTTP parameters may not be null");
  }
  SSLSocket sslsock=(SSLSocket)(sock != null ? sock : createSocket());
  if (localAddress != null) {
    sslsock.bind(localAddress);
  }
  int connTimeout=HttpConnectionParams.getConnectionTimeout(params);
  int soTimeout=HttpConnectionParams.getSoTimeout(params);
  try {
    sslsock.connect(remoteAddress,connTimeout);
  }
 catch (  SocketTimeoutException ex) {
    throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"+ remoteAddress.getAddress()+ " timed out");
  }
  sslsock.setSoTimeout(soTimeout);
  if (this.hostnameVerifier != null) {
    try {
      this.hostnameVerifier.verify(remoteAddress.getHostName(),sslsock);
    }
 catch (    IOException iox) {
      try {
        sslsock.close();
      }
 catch (      Exception x) {
      }
      throw iox;
    }
  }
  return sslsock;
}
 

Example 71

From project subsonic_1, under directory /subsonic-android/src/net/sourceforge/subsonic/androidapp/service/ssl/.

Source file: SSLSocketFactory.java

  15 
vote

/** 
 * @since 4.1
 */
public Socket connectSocket(final Socket sock,final InetSocketAddress remoteAddress,final InetSocketAddress localAddress,final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
  if (remoteAddress == null) {
    throw new IllegalArgumentException("Remote address may not be null");
  }
  if (params == null) {
    throw new IllegalArgumentException("HTTP parameters may not be null");
  }
  SSLSocket sslsock=(SSLSocket)(sock != null ? sock : createSocket());
  if (localAddress != null) {
    sslsock.bind(localAddress);
  }
  int connTimeout=HttpConnectionParams.getConnectionTimeout(params);
  int soTimeout=HttpConnectionParams.getSoTimeout(params);
  try {
    sslsock.connect(remoteAddress,connTimeout);
  }
 catch (  SocketTimeoutException ex) {
    throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"+ remoteAddress.getAddress()+ " timed out");
  }
  sslsock.setSoTimeout(soTimeout);
  if (this.hostnameVerifier != null) {
    try {
      this.hostnameVerifier.verify(remoteAddress.getHostName(),sslsock);
    }
 catch (    IOException iox) {
      try {
        sslsock.close();
      }
 catch (      Exception x) {
      }
      throw iox;
    }
  }
  return sslsock;
}
 

Example 72

From project subsonic_2, under directory /subsonic-android/src/net/sourceforge/subsonic/androidapp/service/ssl/.

Source file: SSLSocketFactory.java

  15 
vote

/** 
 * @since 4.1
 */
public Socket connectSocket(final Socket sock,final InetSocketAddress remoteAddress,final InetSocketAddress localAddress,final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
  if (remoteAddress == null) {
    throw new IllegalArgumentException("Remote address may not be null");
  }
  if (params == null) {
    throw new IllegalArgumentException("HTTP parameters may not be null");
  }
  SSLSocket sslsock=(SSLSocket)(sock != null ? sock : createSocket());
  if (localAddress != null) {
    sslsock.bind(localAddress);
  }
  int connTimeout=HttpConnectionParams.getConnectionTimeout(params);
  int soTimeout=HttpConnectionParams.getSoTimeout(params);
  try {
    sslsock.connect(remoteAddress,connTimeout);
  }
 catch (  SocketTimeoutException ex) {
    throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"+ remoteAddress.getAddress()+ " timed out");
  }
  sslsock.setSoTimeout(soTimeout);
  if (this.hostnameVerifier != null) {
    try {
      this.hostnameVerifier.verify(remoteAddress.getHostName(),sslsock);
    }
 catch (    IOException iox) {
      try {
        sslsock.close();
      }
 catch (      Exception x) {
      }
      throw iox;
    }
  }
  return sslsock;
}
 

Example 73

From project Supersonic, under directory /subsonic-android/src/net/sourceforge/subsonic/androidapp/service/ssl/.

Source file: SSLSocketFactory.java

  15 
vote

/** 
 * @since 4.1
 */
public Socket connectSocket(final Socket sock,final InetSocketAddress remoteAddress,final InetSocketAddress localAddress,final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
  if (remoteAddress == null) {
    throw new IllegalArgumentException("Remote address may not be null");
  }
  if (params == null) {
    throw new IllegalArgumentException("HTTP parameters may not be null");
  }
  SSLSocket sslsock=(SSLSocket)(sock != null ? sock : createSocket());
  if (localAddress != null) {
    sslsock.bind(localAddress);
  }
  int connTimeout=HttpConnectionParams.getConnectionTimeout(params);
  int soTimeout=HttpConnectionParams.getSoTimeout(params);
  try {
    sslsock.connect(remoteAddress,connTimeout);
  }
 catch (  SocketTimeoutException ex) {
    throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"+ remoteAddress.getAddress()+ " timed out");
  }
  sslsock.setSoTimeout(soTimeout);
  if (this.hostnameVerifier != null) {
    try {
      this.hostnameVerifier.verify(remoteAddress.getHostName(),sslsock);
    }
 catch (    IOException iox) {
      try {
        sslsock.close();
      }
 catch (      Exception x) {
      }
      throw iox;
    }
  }
  return sslsock;
}
 

Example 74

From project SWE12-Drone, under directory /SWE12-Drone/src/at/tugraz/ist/droned/dcf/config/.

Source file: DroneConfiguration.java

  15 
vote

public boolean readConfiguration(WiFiConnection wifi){
  config=new ArrayList<String>();
  Socket socket=null;
  boolean readConfig=true;
  int counter=0;
  while (readConfig) {
    try {
      if (socket != null) {
        socket.close();
      }
      socket=new Socket(wifi.ip_drone,wifi.CONF_PORT);
      socket.setSoTimeout(3000);
      BufferedReader inStream=new BufferedReader(new InputStreamReader(socket.getInputStream()));
      wifi.sendAtCommand("AT*CTRL=#SEQ#,4,0");
      String c="";
      config=new ArrayList<String>();
      while ((c=inStream.readLine()) != null) {
        config.add(c);
        if (c.contains("custom:session_desc")) {
          readConfig=false;
          break;
        }
      }
      inStream.close();
    }
 catch (    SocketTimeoutException e) {
      if (counter++ > 3)       return false;
    }
catch (    Exception e) {
      if (counter++ > 3)       return false;
    }
  }
  return true;
}
 

Example 75

From project syslog4j, under directory /src/main/java/com/nesscomputing/syslog4j/server/impl/net/tcp/.

Source file: TCPNetSyslogServer.java

  15 
vote

public void run(){
  boolean timeout=false;
  try {
    BufferedReader br=new BufferedReader(new InputStreamReader(this.socket.getInputStream(),Charsets.UTF_8));
    String line=br.readLine();
    if (line != null) {
      AbstractSyslogServer.handleSessionOpen(this.sessions,this.server,this.socket);
    }
    while (line != null && line.length() != 0) {
      SyslogServerEventIF event=createEvent(this.server.getConfig(),line,this.socket.getInetAddress());
      AbstractSyslogServer.handleEvent(this.sessions,this.server,this.socket,event);
      line=br.readLine();
    }
  }
 catch (  SocketTimeoutException ste) {
    timeout=true;
  }
catch (  SocketException se) {
    AbstractSyslogServer.handleException(this.sessions,this.server,this.socket.getRemoteSocketAddress(),se);
  }
catch (  IOException ioe) {
    AbstractSyslogServer.handleException(this.sessions,this.server,this.socket.getRemoteSocketAddress(),ioe);
  }
  try {
    AbstractSyslogServer.handleSessionClosed(this.sessions,this.server,this.socket,timeout);
    this.sessions.removeSocket(this.socket);
    this.socket.close();
  }
 catch (  IOException ioe) {
    AbstractSyslogServer.handleException(this.sessions,this.server,this.socket.getRemoteSocketAddress(),ioe);
  }
}
 

Example 76

From project teatrove, under directory /trove/src/main/java/org/teatrove/trove/util/.

Source file: BasicMulticastTransceiverImpl.java

  15 
vote

private Serializable poll(){
  try {
    byte[] buf=new byte[4096];
    DatagramPacket p=new DatagramPacket(buf,buf.length);
    mSocket.receive(p);
    ObjectInputStream in=new ObjectInputStream(new ByteArrayInputStream(buf));
    return (Serializable)in.readObject();
  }
 catch (  SocketTimeoutException e) {
    return null;
  }
catch (  Exception e) {
    throw new RuntimeException("Message receive failure on " + mGroup + ":"+ mPort,e);
  }
}
 

Example 77

From project TomP2P, under directory /src/main/java/net/tomp2p/natpmp/.

Source file: Message.java

  15 
vote

/** 
 * This handles the execution of the message sending and receiving process.
 */
private void sendMessageInternal() throws NatPmpException {
  for (int attempts=9; attempts > 0; attempts--) {
    try {
      byte[] payload=getRequestPayload();
      payload[0]=0;
      payload[1]=getOpcode();
      DatagramPacket packet=new DatagramPacket(payload,payload.length,socket.getRemoteSocketAddress());
      socket.send(packet);
    }
 catch (    PortUnreachableException ex) {
      throw new NatPmpException("The gateway is unreachable.");
    }
catch (    IOException ex) {
      throw new NatPmpException("Exception while sending packet.",ex);
    }
    try {
      byte[] localResponse=new byte[16];
      DatagramPacket packet=new DatagramPacket(localResponse,0,16);
      socket.receive(packet);
      if (packet.getLength() > 0) {
        this.response=localResponse;
        return;
      }
    }
 catch (    SocketTimeoutException ex) {
    }
catch (    PortUnreachableException ex) {
      throw new NatPmpException("The gateway is unreachable.");
    }
catch (    IOException ex) {
      throw new NatPmpException("Exception while waiting for packet to be received.",ex);
    }
    try {
      socket.setSoTimeout(socket.getSoTimeout() * 2);
    }
 catch (    SocketException ex) {
      throw new NatPmpException("Exception while increasing socket timeout time.",ex);
    }
  }
}
 

Example 78

From project TransFile, under directory /src/net/sourceforge/transfile/ui/swing/.

Source file: NetworkPanel.java

  15 
vote

/** 
 * TODO doc
 * @param throwable <br>Maybe null <br>Maybe shared
 */
final void postErrorMessage(final Throwable throwable){
  if (throwable == null) {
    return;
  }
  try {
    throw throwable;
  }
 catch (  final PeerURLFormatException exception) {
    getWindow().getStatusService().postStatusMessage(translate(new StatusMessage("connect_fail_invalid_peerurl")));
    getLoggerForThisMethod().log(Level.INFO,"failed to connect",exception);
  }
catch (  final UnknownHostException exception) {
    getWindow().getStatusService().postStatusMessage(translate(new StatusMessage("connect_fail_unknown_host")));
    getLoggerForThisMethod().log(Level.INFO,"failed to connect",exception);
  }
catch (  final IllegalStateException exception) {
    getWindow().getStatusService().postStatusMessage(translate(new StatusMessage("connect_fail_illegal_state"),exception));
    getLoggerForThisMethod().log(Level.SEVERE,"failed to connect",exception);
  }
catch (  final BilateralConnectException exception) {
    getWindow().getStatusService().postStatusMessage(translate(new StatusMessage("connect_fail_no_link")));
    getLoggerForThisMethod().log(Level.INFO,"failed to connect",exception);
  }
catch (  final InterruptedException exception) {
  }
catch (  final SocketTimeoutException exception) {
    getWindow().getStatusService().postStatusMessage(translate(new StatusMessage("connect_fail_timeout")));
    getLoggerForThisMethod().log(Level.INFO,"failed to connect",exception);
  }
catch (  final Throwable throwable2) {
    throwable2.printStackTrace();
    getWindow().getStatusService().postStatusMessage(translate(new StatusMessage("connect_fail_unknown")));
    getLoggerForThisMethod().log(Level.SEVERE,"failed to connect (unknown error)",throwable2);
  }
}
 

Example 79

From project TransportsRennes, under directory /TransportsBordeaux/src/fr/ybo/transportsbordeaux/twitter/.

Source file: GetTwitters.java

  15 
vote

public Collection<MessageTwitter> getMessages() throws TbcErreurReseaux {
  try {
    URL myUrl=new URL("http://support-twitter.herokuapp.com/tbc");
    URLConnection connection=myUrl.openConnection();
    connection.setConnectTimeout(20000);
    connection.setReadTimeout(20000);
    connection.addRequestProperty("Accept","application/json");
    Gson gson=new GsonBuilder().create();
    Type listType=new TypeToken<List<MessageTwitter>>(){
    }
.getType();
    return gson.fromJson(new InputStreamReader(connection.getInputStream()),listType);
  }
 catch (  SocketTimeoutException timeoutException) {
    throw new TbcErreurReseaux(timeoutException);
  }
catch (  UnknownHostException erreurReseau) {
    throw new TbcErreurReseaux(erreurReseau);
  }
catch (  IOException exception) {
    throw new TbcErreurReseaux(exception);
  }
catch (  JsonParseException exception) {
    throw new TbcErreurReseaux(exception);
  }
catch (  Exception e) {
    throw new TcbException("Erreur lors de l'interrogation de twitter",e);
  }
}
 

Example 80

From project ttorrent, under directory /src/main/java/com/turn/ttorrent/client/announce/.

Source file: UDPTrackerClient.java

  15 
vote

/** 
 * Receive a UDP packet from the tracker.
 * @param attempt The attempt number, used to calculate the timeout for thereceive operation.
 * @retun Returns a {@link ByteBuffer} containing the packet data.
 */
private ByteBuffer recv(int attempt) throws IOException, SocketException, SocketTimeoutException {
  int timeout=UDP_BASE_TIMEOUT_SECONDS * (int)Math.pow(2,attempt);
  logger.trace("Setting receive timeout to {}s for attempt {}...",timeout,attempt);
  this.socket.setSoTimeout(timeout * 1000);
  try {
    DatagramPacket p=new DatagramPacket(new byte[UDP_PACKET_LENGTH],UDP_PACKET_LENGTH);
    this.socket.receive(p);
    return ByteBuffer.wrap(p.getData(),0,p.getLength());
  }
 catch (  SocketTimeoutException ste) {
    throw ste;
  }
}
 

Example 81

From project vcap-java-client, under directory /cloudfoundry-caldecott-lib/src/main/java/org/cloudfoundry/caldecott/client/.

Source file: SocketClient.java

  15 
vote

public byte[] read() throws IOException {
  if (!open) {
    return null;
  }
  byte[] bytes=new byte[BUFFER_SIZE];
  int len;
  try {
    len=socket.getInputStream().read(bytes);
    idle=false;
  }
 catch (  SocketTimeoutException e) {
    len=0;
    if (logger.isTraceEnabled()) {
      logger.trace("Timeout on read " + e);
    }
    idle=true;
  }
  if (len < 0) {
    if (len < 0) {
      if (logger.isDebugEnabled()) {
        logger.debug("[" + len + "] detected closed stream");
      }
      open=false;
    }
    len=0;
  }
 else {
    if (logger.isTraceEnabled() && len > 0) {
      logger.trace("[" + len + " bytes] read from stream");
    }
  }
  return Arrays.copyOfRange(bytes,0,len);
}
 

Example 82

From project VisiCut, under directory /src/com/t_oster/visicut/.

Source file: VisicutModel.java

  15 
vote

public void sendJob(String name,ProgressListener pl) throws IllegalJobException, SocketTimeoutException, Exception {
  LaserCutter lasercutter=this.getSelectedLaserDevice().getLaserCutter();
  if (pl != null) {
    pl.taskChanged(this,"preparing job");
  }
  LaserJob job=this.prepareJob(name);
  if (pl != null) {
    pl.taskChanged(this,"sending job");
    lasercutter.sendJob(job,pl);
  }
 else {
    lasercutter.sendJob(job);
  }
}
 

Example 83

From project WeatherPortlet, under directory /src/main/java/org/jasig/portlet/weather/dao/worldwide/.

Source file: WorldWeatherOnlineDaoImpl.java

  15 
vote

public void afterPropertiesSet() throws Exception {
  final HttpConnectionManager httpConnectionManager=httpClient.getHttpConnectionManager();
  final HttpConnectionManagerParams params=httpConnectionManager.getParams();
  params.setConnectionTimeout(connectionTimeout);
  params.setSoTimeout(readTimeout);
  params.setParameter(HttpMethodParams.RETRY_HANDLER,new HttpMethodRetryHandler(){
    public boolean retryMethod(    final HttpMethod method,    final IOException exception,    int executionCount){
      if (executionCount >= timesToRetry) {
        return false;
      }
      if (exception instanceof NoHttpResponseException) {
        return true;
      }
      if (exception instanceof SocketException) {
        return true;
      }
      if (exception instanceof SocketTimeoutException) {
        return true;
      }
      if (!method.isRequestSent()) {
        return true;
      }
      return false;
    }
  }
);
}