Example usage for java.io IOException getClass

List of usage examples for java.io IOException getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.dasein.cloud.google.compute.server.ServerSupport.java

@Override
public void reboot(@Nonnull String vmId) throws CloudException, InternalException {
    APITrace.begin(getProvider(), "rebootVM");
    try {//from   w  w  w. jav  a  2 s.c om
        try {
            Operation job = null;
            String zone = null;
            for (VirtualMachine vm : listVirtualMachines()) {
                if (vm.getProviderVirtualMachineId().equalsIgnoreCase(vmId)) {
                    zone = vm.getProviderDataCenterId();
                    Compute gce = provider.getGoogleCompute();
                    job = gce.instances().reset(provider.getContext().getAccountNumber(),
                            vm.getProviderDataCenterId(), getVmNameFromId(vmId)).execute();
                    break;
                }
            }
            if (job != null) {
                GoogleMethod method = new GoogleMethod(provider);
                method.getOperationComplete(provider.getContext(), job, GoogleOperationType.ZONE_OPERATION,
                        null, zone);
            }
        } catch (IOException ex) {
            logger.error(ex.getMessage());
            if (ex.getClass() == GoogleJsonResponseException.class) {
                GoogleJsonResponseException gjre = (GoogleJsonResponseException) ex;
                throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(),
                        gjre.getDetails().getMessage());
            } else
                throw new CloudException(
                        "An error occurred while rebooting VM: " + vmId + ": " + ex.getMessage());
        }
    } finally {
        APITrace.end();
    }
}

From source file:org.dasein.cloud.google.compute.server.ServerSupport.java

@Override
public @Nonnull Iterable<VirtualMachine> listVirtualMachines(VMFilterOptions options)
        throws InternalException, CloudException {
    APITrace.begin(getProvider(), "listVirtualMachines");
    try {//ww  w .j  a  v a 2 s  .  co m
        try {
            ArrayList<VirtualMachine> vms = new ArrayList<VirtualMachine>();
            Compute gce = provider.getGoogleCompute();
            InstanceAggregatedList instances = gce.instances()
                    .aggregatedList(provider.getContext().getAccountNumber()).execute();
            Iterator<String> it = instances.getItems().keySet().iterator();
            while (it.hasNext()) {
                String zone = it.next();
                if (getContext().getRegionId()
                        .equals(provider.getDataCenterServices().getRegionFromZone(zone))) {
                    if (instances.getItems() != null && instances.getItems().get(zone) != null
                            && instances.getItems().get(zone).getInstances() != null) {
                        for (Instance instance : instances.getItems().get(zone).getInstances()) {
                            VirtualMachine vm = toVirtualMachine(instance);
                            if (options == null || options.matches(vm)) {
                                vms.add(vm);
                            }
                        }
                    }
                }
            }
            return vms;
        } catch (IOException ex) {
            logger.error(ex.getMessage());
            if (ex.getClass() == GoogleJsonResponseException.class) {
                GoogleJsonResponseException gjre = (GoogleJsonResponseException) ex;
                throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(),
                        gjre.getDetails().getMessage());
            } else
                throw new CloudException("An error occurred while listing Virtual Machines.");
        }
    } finally {
        APITrace.end();
    }
}

From source file:org.dasein.cloud.google.compute.server.ServerSupport.java

public void terminateVm(@Nonnull String vmId, String reason) throws InternalException, CloudException {
    try {//from w  w  w  .  j ava  2s .co m
        APITrace.begin(getProvider(), "terminateVM");
        Operation job = null;
        GoogleMethod method = null;
        String zone = null;
        Compute gce = provider.getGoogleCompute();
        VirtualMachine vm = getVirtualMachine(vmId);

        if (null == vm) {
            throw new CloudException("Virtual Machine " + vmId + " was not found.");
        }

        try {
            zone = vm.getProviderDataCenterId();
            job = gce.instances().delete(provider.getContext().getAccountNumber(), zone, getVmNameFromId(vmId))
                    .execute();
            if (job != null) {
                method = new GoogleMethod(provider);
                if (false == method.getOperationComplete(provider.getContext(), job,
                        GoogleOperationType.ZONE_OPERATION, null, zone)) {
                    throw new CloudException(
                            "An error occurred while terminating the VM. Note: The root disk might also still exist");
                }
            }
        } catch (IOException ex) {
            logger.error(ex.getMessage());
            if (ex.getClass() == GoogleJsonResponseException.class) {
                GoogleJsonResponseException gjre = (GoogleJsonResponseException) ex;
                throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(),
                        gjre.getDetails().getMessage());
            } else
                throw new CloudException(
                        "An error occurred while terminating VM: " + vmId + ": " + ex.getMessage());
        } catch (Exception ex) {
            throw new CloudException(ex); // catch exception from getOperationComplete
        }

    } finally {
        APITrace.end();
    }
}

From source file:org.dasein.cloud.google.compute.server.ServerSupport.java

public @Nonnull Iterable<VirtualMachineProduct> listProducts(@Nonnull Architecture architecture,
        String preferredDataCenterId) throws InternalException, CloudException {
    MachineTypeAggregatedList machineTypes = null;

    Compute gce = provider.getGoogleCompute();
    Iterable<MachineTypeAggregatedList> machineTypesCachedList = machineTypesCache.get(provider.getContext());

    if (machineTypesCachedList != null) {
        Iterator<MachineTypeAggregatedList> machineTypesCachedListIterator = machineTypesCachedList.iterator();
        if (machineTypesCachedListIterator.hasNext())
            machineTypes = machineTypesCachedListIterator.next();
    } else {//w w w .j a v  a2  s .  c o m
        try {
            machineTypes = gce.machineTypes().aggregatedList(provider.getContext().getAccountNumber())
                    .execute();
            machineTypesCache.put(provider.getContext(), Arrays.asList(machineTypes));
        } catch (IOException ex) {
            logger.error(ex.getMessage());
            if (ex.getClass() == GoogleJsonResponseException.class) {
                GoogleJsonResponseException gjre = (GoogleJsonResponseException) ex;
                throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(),
                        gjre.getDetails().getMessage());
            } else
                throw new CloudException("An error occurred listing VM products.");
        }
    }

    Collection<VirtualMachineProduct> products = new ArrayList<VirtualMachineProduct>();

    Iterator<String> it = machineTypes.getItems().keySet().iterator();
    while (it.hasNext()) {
        Object dataCenterId = it.next();
        if ((preferredDataCenterId == null) || (dataCenterId.toString().endsWith(preferredDataCenterId)))
            for (MachineType type : machineTypes.getItems().get(dataCenterId).getMachineTypes()) {
                //TODO: Filter out deprecated states somehow
                if ((preferredDataCenterId == null) || (type.getZone().equals(preferredDataCenterId))) {
                    VirtualMachineProduct product = toProduct(type);
                    products.add(product);
                }
            }
    }

    return products;
}

From source file:org.dasein.cloud.google.compute.server.ServerSupport.java

@Override
public @Nullable String getUserData(@Nonnull String vmId) throws InternalException, CloudException {
    APITrace.begin(getProvider(), "getVirtualMachine");
    try {//from   w w  w  .jav  a 2 s.  c om
        try {
            Compute gce = provider.getGoogleCompute();
            InstanceAggregatedList instances = gce.instances()
                    .aggregatedList(provider.getContext().getAccountNumber())
                    .setFilter("name eq " + getVmNameFromId(vmId)).execute();
            Iterator<String> it = instances.getItems().keySet().iterator();
            while (it.hasNext()) {
                String zone = it.next();
                if (instances.getItems() != null && instances.getItems().get(zone) != null
                        && instances.getItems().get(zone).getInstances() != null) {
                    for (Instance instance : instances.getItems().get(zone).getInstances()) {
                        if (instance.getName().equals(getVmNameFromId(vmId))) {
                            Metadata metadata = instance.getMetadata();
                            if (null != metadata) {
                                List<Items> items = metadata.getItems();
                                if (null != items) {
                                    for (Items item : items) {
                                        if ("startup-script".equals(item.getKey())) {
                                            return item.getValue();
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
            }
            return null; // not found
        } catch (IOException ex) {
            logger.error(ex.getMessage());
            if (ex.getClass() == GoogleJsonResponseException.class) {
                GoogleJsonResponseException gjre = (GoogleJsonResponseException) ex;
                throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(),
                        gjre.getDetails().getMessage());
            } else
                throw new CloudException("An error occurred retrieving VM: " + vmId + ": " + ex.getMessage());
        }
    } finally {
        APITrace.end();
    }
}

From source file:org.multibit.file.FileHandler.java

/**
 * Secure delete the wallet and the wallet info file.
 * //from  ww w.  ja va  2  s  . c o  m
 * @param perWalletModelData
 */
public void deleteWalletAndWalletInfo(WalletData perWalletModelData) {
    if (perWalletModelData == null) {
        return;
    }

    File walletFile = new File(perWalletModelData.getWalletFilename());
    WalletInfoData walletInfo = perWalletModelData.getWalletInfo();
    String walletInfoFilenameAsString = WalletInfoData
            .createWalletInfoFilename(perWalletModelData.getWalletFilename());
    File walletInfoFile = new File(walletInfoFilenameAsString);

    synchronized (walletInfo) {
        // See if either of the files are readonly - abort.
        if (!walletFile.canWrite() || !walletInfoFile.canWrite()) {
            throw new DeleteWalletException(
                    controller.getLocaliser().getString("deleteWalletException.walletWasReadonly"));
        }

        // Delete the wallet info file first, then the wallet.
        try {
            FileHandler.secureDelete(walletInfoFile);
            FileHandler.secureDelete(walletFile);
            walletInfo.setDeleted(true);
        } catch (IOException ioe) {
            log.error(ioe.getClass().getCanonicalName() + " " + ioe.getMessage());
            throw new DeleteWalletException(
                    controller.getLocaliser().getString("deleteWalletException.genericCouldNotDelete",
                            new String[] { perWalletModelData.getWalletFilename() }));
        }
    }

    // If the wallet was deleted, delete the model data.
    if (walletInfo.isDeleted()) {
        this.bitcoinController.getModel().remove(perWalletModelData);
    }
    return;
}

From source file:org.opendap.d1.DAPResourceHandler.java

/**
 * This function is called from the REST API servlet and handles each request
 * //w ww.  j  ava 2s . c om
 * @param httpVerb (GET, HEAD, POST)
 */
public void handle(byte httpVerb) {

    try {
        // Set the Session member; null indicates no session info
        // FIXME getSession();

        try {
            // get the resource
            String resource = request.getPathInfo();

            log.debug("handling verb {} request with resource '{}'", httpVerb, resource);

            // In the web.xml for the DAPRestServlet, I set the url pattern
            // like this: <url-pattern>/d1/mn/*</url-pattern> which means
            // that the leading '/d1/mn/' is removed by the servlet container.
            // Since this servlet implements only the 'v1' API, I've hardcoded
            // that value here. It could be read from the config file using
            // the org.opendap.d1.mnCore.serviceVersion and mnRead...
            // properties. jhrg 5/20/14
            resource = parseTrailing(resource, API_VERSION);

            log.debug("processed resource: '" + resource + "'");

            // default to node info
            if (resource == null || resource.equals("")) {
                resource = RESOURCE_NODE;
            }

            // get the rest of the path info
            String extra = null;
            boolean status = false;

            if (resource.startsWith(RESOURCE_NODE)) {
                log.debug("Using resource '" + RESOURCE_NODE + "'");

                if (httpVerb == GET) {
                    // node (aka getCapabilities) response. The method uses
                    // the output stream to serialize the result and throws
                    // an
                    // exception if there's a problem.
                    sendNodeResponse();
                    status = true;
                }
            } else if (resource.startsWith(RESOURCE_META)) {
                log.debug("Using resource '" + RESOURCE_META + "'");

                if (httpVerb == GET) {
                    // after the command
                    extra = parseTrailing(resource, RESOURCE_META);
                    // NB: When Tomcat is configured to allow URL encoded paths into the servlets,
                    // it does the decoding before  making the doGet(), ..., calls.
                    // However, here's code to decode the PID, if it's ever needed. jhrg 6/13/14
                    // logDAP.debug("PID before decoding: " + parseTrailing(resource, RESOURCE_META));
                    // extra = new URI(parseTrailing(resource, RESOURCE_META)).getPath();
                    // logDAP.debug("PID after decoding: " + extra);

                    sendSysmetaResponse(extra);
                    status = true;
                }
            } else if (resource.startsWith(RESOURCE_OBJECTS)) {
                // This is the get() call which returns SDOs and SMOs
                // or the describe() call for the same depending on the
                // HTTP verb (GET or HEAD)
                log.debug("Using resource '" + RESOURCE_OBJECTS + "'");
                // 'extra' is text that follows the command in the URL's path.
                extra = parseTrailing(resource, RESOURCE_OBJECTS);
                log.debug("objectId: " + extra);
                log.debug("verb:" + httpVerb);

                if (httpVerb == GET) {
                    if (extra == null || extra.isEmpty()) {
                        Hashtable<String, String[]> params = new Hashtable<String, String[]>();
                        initParams(params);

                        sendListObjects(params);
                    } else {
                        // In the line that follows, I cannot get Event.READ to work but I know
                        // that simple strings work.
                        logDb.addEntry(extra, request.getRemoteAddr(), request.getHeader("user-agent"),
                                Constants.SUBJECT_PUBLIC, "read");
                        sendObject(extra);
                    }
                    status = true;
                } else if (httpVerb == HEAD) {
                    sendDescribeObject(extra);
                    status = true;
                }
            } else if (resource.startsWith(RESOURCE_LOG)) {
                log.debug("Using resource '" + RESOURCE_LOG + "'");
                // handle log events
                if (httpVerb == GET) {
                    Hashtable<String, String[]> params = new Hashtable<String, String[]>();
                    initParams(params);

                    sendLogEntries(params);
                    status = true;
                }
            } else if (resource.startsWith(RESOURCE_CHECKSUM)) {
                log.debug("Using resource '" + RESOURCE_CHECKSUM + "'");
                // handle checksum requests
                if (httpVerb == GET) {
                    // 'extra' is text that follows the command in the URL's path.
                    extra = parseTrailing(resource, RESOURCE_CHECKSUM);
                    String algorithm = "SHA-1";
                    sendChecksum(extra, algorithm);
                    status = true;
                }
            } else if (resource.startsWith(RESOURCE_REPLICA)) {
                log.debug("Using resource '" + RESOURCE_REPLICA + "'");
                // handle replica requests
                if (httpVerb == GET) {
                    extra = parseTrailing(resource, RESOURCE_REPLICA);
                    sendReplica(extra);
                    status = true;
                }

            } else if (resource.startsWith(RESOURCE_MONITOR)) {
                log.debug("Processing resource '" + RESOURCE_MONITOR + "'");
                // there are various parts to monitoring
                if (httpVerb == GET) {
                    extra = parseTrailing(resource, RESOURCE_MONITOR);

                    // ping
                    if (extra.toLowerCase().equals("ping")) {
                        log.debug("processing ping request");

                        Date result = DAPMNodeService.getInstance(request, db, logDb).ping();
                        if (result != null) {
                            log.debug("processing ping result: " + result.toString());

                            response.setDateHeader("Date", result.getTime());
                            response.setStatus(200);

                            response.getWriter().println(result.toString());
                        } else {
                            log.debug("processing ping result: null");
                            response.setStatus(400);

                            response.getWriter().println("No response from the underlying DAP server.");
                        }

                        status = true;
                    }
                }
            } else if (resource.startsWith(RESOURCE_ERROR)) {
                log.debug("Processing resource '{}'", RESOURCE_ERROR);
                SynchronizationFailed sf = collectSynchronizationFailed();
                DAPMNodeService.getInstance(request, db, logDb).synchronizationFailed(sf);
                status = true;
            } else {
                throw new InvalidRequest("0000", "No resource matched for " + resource);
            }

            if (!status) {
                throw new ServiceFailure("0000", "Unknown error while processing resource: " + resource);
            }

        } catch (BaseException be) {
            // report Exceptions as clearly as possible
            OutputStream out = null;
            try {
                out = response.getOutputStream();
            } catch (IOException e) {
                log.error("Could not get output stream from response", e);
            }
            serializeException(be, out);
        } catch (Exception e) {
            // report Exceptions as clearly and generically as possible
            log.error(e.getClass() + ": " + e.getMessage(), e);
            OutputStream out = null;
            try {
                out = response.getOutputStream();
            } catch (IOException ioe) {
                log.error("Could not get output stream from response", ioe);
            }
            ServiceFailure se = new ServiceFailure("2162", e.getMessage());
            serializeException(se, out);
        }

    } catch (Exception e) {
        response.setStatus(400);
        printError("Incorrect resource!", response);
        log.error(e.getClass() + ": " + e.getMessage(), e);
    }
}

From source file:org.apache.http.impl.client.DefaultRequestDirector.java

/**
 * Establish connection either directly or through a tunnel and retry in case of
 * a recoverable I/O failure/* www .  j  a v  a 2 s.c o m*/
 */
private void tryConnect(final RoutedRequest req, final HttpContext context) throws HttpException, IOException {
    final HttpRoute route = req.getRoute();
    final HttpRequest wrapper = req.getRequest();

    int connectCount = 0;
    for (;;) {
        context.setAttribute(ExecutionContext.HTTP_REQUEST, wrapper);
        // Increment connect count
        connectCount++;
        try {
            if (!managedConn.isOpen()) {
                managedConn.open(route, context, params);
            } else {
                managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
            }
            establishRoute(route, context);
            break;
        } catch (final IOException ex) {
            try {
                managedConn.close();
            } catch (final IOException ignore) {
            }
            if (retryHandler.retryRequest(ex, connectCount, context)) {
                if (this.log.isInfoEnabled()) {
                    this.log.info("I/O exception (" + ex.getClass().getName() + ") caught when connecting to "
                            + route + ": " + ex.getMessage());
                    if (this.log.isDebugEnabled()) {
                        this.log.debug(ex.getMessage(), ex);
                    }
                    this.log.info("Retrying connect to " + route);
                }
            } else {
                throw ex;
            }
        }
    }
}

From source file:org.apache.http2.impl.client.DefaultRequestDirector.java

/**
 * Establish connection either directly or through a tunnel and retry in case of
 * a recoverable I/O failure//from w  w  w  .j  ava 2 s.com
 */
private void tryConnect(final RoutedRequest req, final HttpContext context) throws HttpException, IOException {
    HttpRoute route = req.getRoute();
    HttpRequest wrapper = req.getRequest();

    int connectCount = 0;
    for (;;) {
        context.setAttribute(ExecutionContext.HTTP_REQUEST, wrapper);
        // Increment connect count
        connectCount++;
        try {
            if (!managedConn.isOpen()) {
                managedConn.open(route, context, params);
            } else {
                managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
            }
            establishRoute(route, context);
            break;
        } catch (IOException ex) {
            try {
                managedConn.close();
            } catch (IOException ignore) {
            }
            if (retryHandler.retryRequest(ex, connectCount, context)) {
                if (this.log.isInfoEnabled()) {
                    this.log.info("I/O exception (" + ex.getClass().getName()
                            + ") caught when connecting to the target host: " + ex.getMessage());
                    if (this.log.isDebugEnabled()) {
                        this.log.debug(ex.getMessage(), ex);
                    }
                    this.log.info("Retrying connect");
                }
            } else {
                throw ex;
            }
        }
    }
}

From source file:org.apache.hadoop.hbase.tool.LoadIncrementalHFiles.java

/**
 * Attempts to do an atomic load of many hfiles into a region. If it fails, it returns a list of
 * hfiles that need to be retried. If it is successful it will return an empty list.
 * <p>//  w w w  .j a  v  a 2  s .c  om
 * NOTE: To maintain row atomicity guarantees, region server callable should succeed atomically
 * and fails atomically.
 * <p>
 * Protected for testing.
 * @return empty list if success, list of items to retry on recoverable failure
 */
@VisibleForTesting
protected List<LoadQueueItem> tryAtomicRegionLoad(ClientServiceCallable<byte[]> serviceCallable,
        final TableName tableName, final byte[] first, final Collection<LoadQueueItem> lqis)
        throws IOException {
    List<LoadQueueItem> toRetry = new ArrayList<>();
    try {
        Configuration conf = getConf();
        byte[] region = RpcRetryingCallerFactory.instantiate(conf, null).<byte[]>newCaller()
                .callWithRetries(serviceCallable, Integer.MAX_VALUE);
        if (region == null) {
            LOG.warn("Attempt to bulk load region containing " + Bytes.toStringBinary(first) + " into table "
                    + tableName + " with files " + lqis
                    + " failed.  This is recoverable and they will be retried.");
            toRetry.addAll(lqis); // return lqi's to retry
        }
        // success
        return toRetry;
    } catch (IOException e) {
        LOG.error("Encountered unrecoverable error from region server, additional details: "
                + serviceCallable.getExceptionMessageAdditionalDetail(), e);
        LOG.warn("Received a " + e.getClass().getSimpleName() + " from region server: "
                + serviceCallable.getExceptionMessageAdditionalDetail(), e);
        if (getConf().getBoolean(RETRY_ON_IO_EXCEPTION, false)
                && numRetries.get() < getConf().getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
                        HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER)) {
            LOG.warn("Will attempt to retry loading failed HFiles. Retry #" + numRetries.incrementAndGet());
            toRetry.addAll(lqis);
            return toRetry;
        }
        LOG.error(RETRY_ON_IO_EXCEPTION + " is disabled. Unable to recover");
        throw e;
    }
}