Example usage for java.io InterruptedIOException InterruptedIOException

List of usage examples for java.io InterruptedIOException InterruptedIOException

Introduction

In this page you can find the example usage for java.io InterruptedIOException InterruptedIOException.

Prototype

public InterruptedIOException() 

Source Link

Document

Constructs an InterruptedIOException with null as its error detail message.

Usage

From source file:org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster.java

private static boolean waitForServerUp(int port, long timeout) throws IOException {
    long start = System.currentTimeMillis();
    while (true) {
        try {//from   w w  w  .  ja v  a2  s  . com
            Socket sock = new Socket("localhost", port);
            BufferedReader reader = null;
            try {
                OutputStream outstream = sock.getOutputStream();
                outstream.write("stat".getBytes());
                outstream.flush();

                Reader isr = new InputStreamReader(sock.getInputStream());
                reader = new BufferedReader(isr);
                String line = reader.readLine();
                if (line != null && line.startsWith("Zookeeper version:")) {
                    return true;
                }
            } finally {
                sock.close();
                if (reader != null) {
                    reader.close();
                }
            }
        } catch (IOException e) {
            // ignore as this is expected
            LOG.info("server localhost:" + port + " not up " + e);
        }

        if (System.currentTimeMillis() > start + timeout) {
            break;
        }
        try {
            Thread.sleep(250);
        } catch (InterruptedException e) {
            throw (InterruptedIOException) new InterruptedIOException().initCause(e);
        }
    }
    return false;
}

From source file:org.csanchez.jenkins.plugins.kubernetes.pipeline.ContainerExecDecorator.java

@Override
public void close() throws IOException {
    if (watch != null) {
        try {//from   ww  w  . j  av a2s  . c o  m
            watch.close();
        } catch (IllegalStateException e) {
            LOGGER.log(Level.INFO, "Watch was already closed: {0}", e.getMessage());
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, "Error closing watch", e);
        } finally {
            watch = null;
        }
    }

    if (proc != null) {
        try {
            proc.kill();
        } catch (InterruptedException e) {
            throw new InterruptedIOException();
        }
    }
}

From source file:org.apache.hadoop.hbase.rest.client.RemoteHTable.java

private Result[] getResults(String spec) throws IOException {
    for (int i = 0; i < maxRetries; i++) {
        Response response = client.get(spec, Constants.MIMETYPE_PROTOBUF);
        int code = response.getCode();
        switch (code) {
        case 200:
            CellSetModel model = new CellSetModel();
            model.getObjectFromMessage(response.getBody());
            Result[] results = buildResultFromModel(model);
            if (results.length > 0) {
                return results;
            }/*from   w w w  .j  a  v  a2 s  .  c o m*/
            // fall through
        case 404:
            return new Result[0];

        case 509:
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                throw (InterruptedIOException) new InterruptedIOException().initCause(e);
            }
            break;
        default:
            throw new IOException("get request returned " + code);
        }
    }
    throw new IOException("get request timed out");
}

From source file:com.sa.npopa.samples.hbase.rest.client.RemoteHTable.java

private Result[] getResults(String spec) throws IOException {
    for (int i = 0; i < maxRetries; i++) {
        Response response = client.get(spec, Constants.MIMETYPE_PROTOBUF);
        int code = response.getCode();
        switch (code) {
        case 200:
            CellSetModel model = new CellSetModel();
            model.getObjectFromMessage(response.getBody());
            Result[] results = buildResultFromModel(model);
            if (results.length > 0) {
                return results;
            }/*w w w . ja v  a2s .c o m*/
            // fall through
        case 404:
            return new Result[0];

        case 401:
            LOG.warn("Negotiate not supported!");
            break;
        case 509:
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                throw (InterruptedIOException) new InterruptedIOException().initCause(e);
            }
            break;
        default:
            throw new IOException("get request returned " + code);
        }
    }
    throw new IOException("get request timed out");
}

From source file:org.apache.hadoop.hbase.master.AssignmentManager.java

/**
 * Constructs a new assignment manager.//  ww  w  .  j  a  v  a  2 s .c o m
 *
 * @param server
 * @param serverManager
 * @param catalogTracker
 * @param service
 * @throws KeeperException
 * @throws IOException
 */
public AssignmentManager(Server server, ServerManager serverManager, CatalogTracker catalogTracker,
        final LoadBalancer balancer, final ExecutorService service, MetricsMaster metricsMaster,
        final TableLockManager tableLockManager)
        throws KeeperException, IOException, CoordinatedStateException {
    super(server.getZooKeeper());
    this.server = server;
    this.serverManager = serverManager;
    this.catalogTracker = catalogTracker;
    this.executorService = service;
    this.regionsToReopen = Collections.synchronizedMap(new HashMap<String, HRegionInfo>());
    Configuration conf = server.getConfiguration();
    // Only read favored nodes if using the favored nodes load balancer.
    this.shouldAssignRegionsWithFavoredNodes = conf
            .getClass(HConstants.HBASE_MASTER_LOADBALANCER_CLASS, Object.class)
            .equals(FavoredNodeLoadBalancer.class);
    try {
        if (server.getCoordinatedStateManager() != null) {
            this.tableStateManager = server.getCoordinatedStateManager().getTableStateManager();
        } else {
            this.tableStateManager = null;
        }
    } catch (InterruptedException e) {
        throw new InterruptedIOException();
    }
    // This is the max attempts, not retries, so it should be at least 1.
    this.maximumAttempts = Math.max(1,
            this.server.getConfiguration().getInt("hbase.assignment.maximum.attempts", 10));
    this.sleepTimeBeforeRetryingMetaAssignment = this.server.getConfiguration()
            .getLong("hbase.meta.assignment.retry.sleeptime", 1000l);
    this.balancer = balancer;
    int maxThreads = conf.getInt("hbase.assignment.threads.max", 30);
    this.threadPoolExecutorService = Threads.getBoundedCachedThreadPool(maxThreads, 60L, TimeUnit.SECONDS,
            Threads.newDaemonThreadFactory("AM."));
    this.regionStates = new RegionStates(server, serverManager);

    this.bulkAssignWaitTillAllAssigned = conf.getBoolean("hbase.bulk.assignment.waittillallassigned", false);
    this.bulkAssignThresholdRegions = conf.getInt("hbase.bulk.assignment.threshold.regions", 7);
    this.bulkAssignThresholdServers = conf.getInt("hbase.bulk.assignment.threshold.servers", 3);

    int workers = conf.getInt("hbase.assignment.zkevent.workers", 20);
    ThreadFactory threadFactory = Threads.newDaemonThreadFactory("AM.ZK.Worker");
    zkEventWorkers = Threads.getBoundedCachedThreadPool(workers, 60L, TimeUnit.SECONDS, threadFactory);
    this.tableLockManager = tableLockManager;

    this.metricsAssignmentManager = new MetricsAssignmentManager();
}

From source file:org.apache.hadoop.hbase.zookeeper.ZooKeeperWrapper.java

public void connectToZk(int retryNum, int retryFreq) throws IOException {
    try {/*from w  ww. j a  v  a  2  s.  c om*/
        LOG.info("[" + instanceName + "] Connecting to zookeeper");
        if (recoverableZK != null) {
            recoverableZK.close();
            LOG.error("<" + instanceName + ">" + " Closed existing zookeeper client");
        }
        recoverableZK = new RecoverableZooKeeper(quorumServers, sessionTimeout, this, retryNum, retryFreq);
        LOG.debug("<" + instanceName + ">" + " Connected to zookeeper");
        // Ensure we are actually connected
        ensureZkAvailable();
    } catch (IOException e) {
        LOG.error("<" + instanceName + "> " + "Failed to create ZooKeeper object: " + e);
        throw e;
    } catch (InterruptedException e) {
        LOG.error("<" + instanceName + " >" + "Error closing ZK connection: " + e);
        throw new InterruptedIOException();
    }
}

From source file:org.apache.hadoop.hbase.rest.client.RemoteHTable.java

public void put(Put put) throws IOException {
    CellSetModel model = buildModelFromPut(put);
    StringBuilder sb = new StringBuilder();
    sb.append('/');
    sb.append(Bytes.toStringBinary(name));
    sb.append('/');
    sb.append(Bytes.toStringBinary(put.getRow()));
    for (int i = 0; i < maxRetries; i++) {
        Response response = client.put(sb.toString(), Constants.MIMETYPE_PROTOBUF,
                model.createProtobufOutput());
        int code = response.getCode();
        switch (code) {
        case 200:
            return;
        case 509:
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                throw (InterruptedIOException) new InterruptedIOException().initCause(e);
            }// ww  w. j a v a2  s  . c  om
            break;
        default:
            throw new IOException("put request failed with " + code);
        }
    }
    throw new IOException("put request timed out");
}

From source file:com.xtremelabs.robolectric.tester.org.apache.http.impl.client.DefaultRequestDirector.java

public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws HttpException, IOException {

    HttpRequest orig = request;//  w  ww .  j  av a 2 s  .c om
    RequestWrapper origWrapper = wrapRequest(orig);
    origWrapper.setParams(params);
    HttpRoute origRoute = determineRoute(target, origWrapper, context);

    virtualHost = (HttpHost) orig.getParams().getParameter(ClientPNames.VIRTUAL_HOST);

    RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute);

    long timeout = ConnManagerParams.getTimeout(params);

    int execCount = 0;

    boolean reuse = false;
    boolean done = false;
    try {
        HttpResponse response = null;
        while (!done) {
            // In this loop, the RoutedRequest may be replaced by a
            // followup request and route. The request and route passed
            // in the method arguments will be replaced. The original
            // request is still available in 'orig'.

            RequestWrapper wrapper = roureq.getRequest();
            HttpRoute route = roureq.getRoute();
            response = null;

            // See if we have a user token bound to the execution context
            Object userToken = context.getAttribute(ClientContext.USER_TOKEN);

            // Allocate connection if needed
            if (managedConn == null) {
                ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken);
                if (orig instanceof AbortableHttpRequest) {
                    ((AbortableHttpRequest) orig).setConnectionRequest(connRequest);
                }

                try {
                    managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
                } catch (InterruptedException interrupted) {
                    InterruptedIOException iox = new InterruptedIOException();
                    iox.initCause(interrupted);
                    throw iox;
                }

                if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
                    // validate connection
                    if (managedConn.isOpen()) {
                        this.log.debug("Stale connection check");
                        if (managedConn.isStale()) {
                            this.log.debug("Stale connection detected");
                            managedConn.close();
                        }
                    }
                }
            }

            if (orig instanceof AbortableHttpRequest) {
                ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn);
            }

            // Reopen connection if needed
            if (!managedConn.isOpen()) {
                managedConn.open(route, context, params);
            } else {
                managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
            }

            try {
                establishRoute(route, context);
            } catch (TunnelRefusedException ex) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug(ex.getMessage());
                }
                response = ex.getResponse();
                break;
            }

            // Reset headers on the request wrapper
            wrapper.resetHeaders();

            // Re-write request URI if needed
            rewriteRequestURI(wrapper, route);

            // Use virtual host if set
            target = virtualHost;

            if (target == null) {
                target = route.getTargetHost();
            }

            HttpHost proxy = route.getProxyHost();

            // Populate the execution context
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
            context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
            context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);
            context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState);
            context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);

            // Run request protocol interceptors
            requestExec.preProcess(wrapper, httpProcessor, context);

            boolean retrying = true;
            Exception retryReason = null;
            while (retrying) {
                // Increment total exec count (with redirects)
                execCount++;
                // Increment exec count for this particular request
                wrapper.incrementExecCount();
                if (!wrapper.isRepeatable()) {
                    this.log.debug("Cannot retry non-repeatable request");
                    if (retryReason != null) {
                        throw new NonRepeatableRequestException("Cannot retry request "
                                + "with a non-repeatable request entity.  The cause lists the "
                                + "reason the original request failed: " + retryReason);
                    } else {
                        throw new NonRepeatableRequestException(
                                "Cannot retry request " + "with a non-repeatable request entity.");
                    }
                }

                try {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug("Attempt " + execCount + " to execute request");
                    }
                    response = requestExec.execute(wrapper, managedConn, context);
                    retrying = false;

                } catch (IOException ex) {
                    this.log.debug("Closing the connection.");
                    managedConn.close();
                    if (retryHandler.retryRequest(ex, wrapper.getExecCount(), context)) {
                        if (this.log.isInfoEnabled()) {
                            this.log.info("I/O exception (" + ex.getClass().getName()
                                    + ") caught when processing request: " + ex.getMessage());
                        }
                        if (this.log.isDebugEnabled()) {
                            this.log.debug(ex.getMessage(), ex);
                        }
                        this.log.info("Retrying request");
                        retryReason = ex;
                    } else {
                        throw ex;
                    }

                    // If we have a direct route to the target host
                    // just re-open connection and re-try the request
                    if (!route.isTunnelled()) {
                        this.log.debug("Reopening the direct connection.");
                        managedConn.open(route, context, params);
                    } else {
                        // otherwise give up
                        this.log.debug("Proxied connection. Need to start over.");
                        retrying = false;
                    }

                }

            }

            if (response == null) {
                // Need to start over
                continue;
            }

            // Run response protocol interceptors
            response.setParams(params);
            requestExec.postProcess(response, httpProcessor, context);

            // The connection is in or can be brought to a re-usable state.
            reuse = reuseStrategy.keepAlive(response, context);
            if (reuse) {
                // Set the idle duration of this connection
                long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
                managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);

                if (this.log.isDebugEnabled()) {
                    if (duration >= 0) {
                        this.log.debug("Connection can be kept alive for " + duration + " ms");
                    } else {
                        this.log.debug("Connection can be kept alive indefinitely");
                    }
                }
            }

            RoutedRequest followup = handleResponse(roureq, response, context);
            if (followup == null) {
                done = true;
            } else {
                if (reuse) {
                    // Make sure the response body is fully consumed, if present
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        entity.consumeContent();
                    }
                    // entity consumed above is not an auto-release entity,
                    // need to mark the connection re-usable explicitly
                    managedConn.markReusable();
                } else {
                    managedConn.close();
                }
                // check if we can use the same connection for the followup
                if (!followup.getRoute().equals(roureq.getRoute())) {
                    releaseConnection();
                }
                roureq = followup;
            }

            if (managedConn != null && userToken == null) {
                userToken = userTokenHandler.getUserToken(context);
                context.setAttribute(ClientContext.USER_TOKEN, userToken);
                if (userToken != null) {
                    managedConn.setState(userToken);
                }
            }

        } // while not done

        // check for entity, release connection if possible
        if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            if (reuse)
                managedConn.markReusable();
            releaseConnection();
        } else {
            // install an auto-release entity
            HttpEntity entity = response.getEntity();
            entity = new BasicManagedEntity(entity, managedConn, reuse);
            response.setEntity(entity);
        }

        return response;

    } catch (HttpException ex) {
        abortConnection();
        throw ex;
    } catch (IOException ex) {
        abortConnection();
        throw ex;
    } catch (RuntimeException ex) {
        abortConnection();
        throw ex;
    }
}

From source file:com.sa.npopa.samples.hbase.rest.client.RemoteHTable.java

@Override
public void put(Put put) throws IOException {
    CellSetModel model = buildModelFromPut(put);
    StringBuilder sb = new StringBuilder();
    sb.append('/');
    sb.append(Bytes.toStringBinary(name));
    sb.append('/');
    sb.append(Bytes.toStringBinary(put.getRow()));
    for (int i = 0; i < maxRetries; i++) {
        Response response = client.put(sb.toString(), Constants.MIMETYPE_PROTOBUF,
                model.createProtobufOutput());
        int code = response.getCode();
        switch (code) {
        case 200:
            return;
        case 509:
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                throw (InterruptedIOException) new InterruptedIOException().initCause(e);
            }//from  w w  w  .  j a v a 2s .c o m
            break;
        default:
            throw new IOException("put request failed with " + code);
        }
    }
    throw new IOException("put request timed out");
}

From source file:org.vietspider.net.apache.DefaultRequestDirector.java

public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws HttpException, IOException {

    HttpRequest orig = request;//from   w  w w.ja v a  2s. com
    RequestWrapper origWrapper = wrapRequest(orig);
    origWrapper.setParams(params);
    HttpRoute origRoute = determineRoute(target, origWrapper, context);

    virtualHost = (HttpHost) orig.getParams().getParameter(ClientPNames.VIRTUAL_HOST);

    RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute);

    long timeout = HttpConnectionParams.getConnectionTimeout(params);

    boolean reuse = false;
    boolean done = false;
    try {
        HttpResponse response = null;
        while (!done) {
            // In this loop, the RoutedRequest may be replaced by a
            // followup request and route. The request and route passed
            // in the method arguments will be replaced. The original
            // request is still available in 'orig'.

            RequestWrapper wrapper = roureq.getRequest();
            HttpRoute route = roureq.getRoute();
            response = null;

            // See if we have a user token bound to the execution context
            Object userToken = context.getAttribute(ClientContext.USER_TOKEN);

            // Allocate connection if needed
            if (managedConn == null) {
                ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken);
                if (orig instanceof AbortableHttpRequest) {
                    ((AbortableHttpRequest) orig).setConnectionRequest(connRequest);
                }

                try {
                    //                      if(timeout < 1) timeout = 30000;
                    //                      System.out.println(" =========== chay vao day roi nhe " + timeout );
                    //                      System.out.println(connRequest);
                    managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
                    //                        System.out.println("get thuc chuyen nay");
                } catch (InterruptedException interrupted) {
                    InterruptedIOException iox = new InterruptedIOException();
                    iox.initCause(interrupted);
                    throw iox;
                }

                if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
                    // validate connection
                    if (managedConn.isOpen()) {
                        this.log.debug("Stale connection check");
                        if (managedConn.isStale()) {
                            this.log.debug("Stale connection detected");
                            managedConn.close();
                        }
                    }
                }
            }

            if (orig instanceof AbortableHttpRequest) {
                ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn);
            }

            try {
                tryConnect(roureq, context);
            } catch (TunnelRefusedException ex) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug(ex.getMessage());
                }
                response = ex.getResponse();
                break;
            }

            // Reset headers on the request wrapper
            wrapper.resetHeaders();

            // Re-write request URI if needed
            rewriteRequestURI(wrapper, route);

            // Use virtual host if set
            target = virtualHost;

            if (target == null) {
                target = route.getTargetHost();
            }

            HttpHost proxy = route.getProxyHost();

            // Populate the execution context
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
            context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
            context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);
            context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState);
            context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);

            // Run request protocol interceptors
            requestExec.preProcess(wrapper, httpProcessor, context);

            response = tryExecute(roureq, context);
            if (response == null) {
                // Need to start over
                continue;
            }

            // Run response protocol interceptors
            response.setParams(params);
            requestExec.postProcess(response, httpProcessor, context);

            // The connection is in or can be brought to a re-usable state.
            reuse = reuseStrategy.keepAlive(response, context);
            if (reuse) {
                // Set the idle duration of this connection
                long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
                if (this.log.isDebugEnabled()) {
                    String s;
                    if (duration > 0) {
                        s = "for " + duration + " " + TimeUnit.MILLISECONDS;
                    } else {
                        s = "indefinitely";
                    }
                    this.log.debug("Connection can be kept alive " + s);
                }
                managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);
            }

            RoutedRequest followup = handleResponse(roureq, response, context);
            if (followup == null) {
                done = true;
            } else {
                if (reuse) {
                    // Make sure the response body is fully consumed, if present
                    HttpEntity entity = response.getEntity();
                    EntityUtils.consume(entity);
                    // entity consumed above is not an auto-release entity,
                    // need to mark the connection re-usable explicitly
                    managedConn.markReusable();
                } else {
                    managedConn.close();
                }
                // check if we can use the same connection for the followup
                if (!followup.getRoute().equals(roureq.getRoute())) {
                    releaseConnection();
                }
                roureq = followup;
            }

            if (managedConn != null && userToken == null) {
                userToken = userTokenHandler.getUserToken(context);
                context.setAttribute(ClientContext.USER_TOKEN, userToken);
                if (userToken != null) {
                    managedConn.setState(userToken);
                }
            }

        } // while not done

        // check for entity, release connection if possible
        if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            if (reuse)
                managedConn.markReusable();
            releaseConnection();
        } else {
            // install an auto-release entity
            HttpEntity entity = response.getEntity();
            entity = new BasicManagedEntity(entity, managedConn, reuse);
            response.setEntity(entity);
        }

        return response;

    } catch (ConnectionShutdownException ex) {
        InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down");
        ioex.initCause(ex);
        throw ioex;
    } catch (HttpException ex) {
        abortConnection();
        throw ex;
    } catch (IOException ex) {
        abortConnection();
        throw ex;
    } catch (RuntimeException ex) {
        abortConnection();
        throw ex;
    }
}