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.openhab.binding.lifx.internal.LifxLightDiscovery.java

protected void doScan() {
    try {/*from  ww  w .j ava2 s  . c  om*/
        if (!isScanning) {
            isScanning = true;
            if (selector != null) {
                closeSelector(selector, LOG_ID);
            }

            logger.debug("The LIFX discovery service will use '{}' as source identifier",
                    Long.toString(sourceId, 16));

            Selector localSelector = Selector.open();
            selector = localSelector;

            broadcastKey = openBroadcastChannel(localSelector, LOG_ID, BROADCAST_PORT);
            networkJob = scheduler.schedule(this::receiveAndHandlePackets, 0, TimeUnit.MILLISECONDS);

            LifxSelectorContext selectorContext = new LifxSelectorContext(localSelector, sourceId,
                    sequenceNumberSupplier, LOG_ID, broadcastKey);
            broadcastPacket(selectorContext, new GetServiceRequest());
        } else {
            logger.info("A discovery scan for LIFX lights is already underway");
        }
    } catch (IOException e) {
        logger.debug("{} while discovering LIFX lights : {}", e.getClass().getSimpleName(), e.getMessage());
        isScanning = false;
    }
}

From source file:org.zaproxy.zap.extension.ascanrulesAlpha.ElmahScanner.java

@Override
public void scan() {

    // Check if the user stopped things. One request per URL so check before
    // sending the request
    if (isStop()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Scanner " + getName() + " Stopping.");
        }/* w  w w .ja va2  s.co m*/
        return;
    }

    HttpMessage newRequest = getNewMsg();
    newRequest.getRequestHeader().setMethod(HttpRequestHeader.GET);
    URI baseUri = getBaseMsg().getRequestHeader().getURI();
    URI elmahUri = null;
    try {
        elmahUri = new URI(baseUri.getScheme(), null, baseUri.getHost(), baseUri.getPort(), "/elmah.axd");
    } catch (URIException uEx) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(
                    "An error occurred creating a URI for the: " + getName() + " scanner. " + uEx.getMessage(),
                    uEx);
        }
        return;
    }
    try {
        newRequest.getRequestHeader().setURI(elmahUri);
    } catch (URIException uEx) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("An error occurred setting the URI for a new request used by: " + getName() + " scanner. "
                    + uEx.getMessage(), uEx);
        }
        return;
    }
    try {
        sendAndReceive(newRequest, false);
    } catch (IOException e) {
        LOG.warn("An error occurred while checking [" + newRequest.getRequestHeader().getMethod() + "] ["
                + newRequest.getRequestHeader().getURI() + "] for " + getName() + " Caught "
                + e.getClass().getName() + " " + e.getMessage());
        return;
    }
    int statusCode = newRequest.getResponseHeader().getStatusCode();
    if (statusCode == HttpStatusCode.OK) {
        raiseAlert(newRequest, getRisk(), "");
    } else if (statusCode == HttpStatusCode.UNAUTHORIZED || statusCode == HttpStatusCode.FORBIDDEN) {
        raiseAlert(newRequest, Alert.RISK_INFO, getOtherInfo());
    }
}

From source file:com.hippoapp.asyncmvp.http.RetryHandler.java

@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    boolean retry;

    Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
    boolean sent = (b != null && b.booleanValue());

    if (executionCount > DEFAULT_MAX_RETRIES) {
        retry = false;/*from   www.ja  v a2  s. c  om*/
    } else if (sUnretriedExceptionSet.contains(exception.getClass())) {
        retry = false;
    } else if (sRetriedExceptionSet.contains(exception.getClass())) {
        retry = true;
    } else if (!sent) {
        // for most other errors, retry only if request hasn't been fully
        // sent yet
        retry = true;
    } else {
        // resend all idempotent requests
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        String requestType = currentReq.getMethod();
        if (!requestType.equals("POST")) {
            retry = true;
        } else {
            // otherwise do not retry
            retry = false;
        }
    }

    if (retry) {
        SystemClock.sleep(RETRY_SLEEP_TIME_IN_MILLS);
    } else {
        exception.printStackTrace();
    }

    return retry;
}

From source file:org.apache.hadoop.hbase.trace.IntegrationTestSendTraceRequests.java

private void doScans(ExecutorService service, final LinkedBlockingQueue<Long> rks) {

    for (int i = 0; i < 100; i++) {
        Runnable runnable = new Runnable() {
            private TraceScope innerScope = null;
            private final LinkedBlockingQueue<Long> rowKeyQueue = rks;

            @Override//  www.j av  a  2 s  .  co  m
            public void run() {
                ResultScanner rs = null;
                try {
                    innerScope = Trace.startSpan("Scan", Sampler.ALWAYS);
                    HTable ht = new HTable(util.getConfiguration(), tableName);
                    Scan s = new Scan();
                    s.setStartRow(Bytes.toBytes(rowKeyQueue.take()));
                    s.setBatch(7);
                    rs = ht.getScanner(s);
                    // Something to keep the jvm from removing the loop.
                    long accum = 0;

                    for (int x = 0; x < 1000; x++) {
                        Result r = rs.next();
                        accum |= Bytes.toLong(r.getRow());
                    }

                    innerScope.getSpan().addTimelineAnnotation("Accum result = " + accum);

                    ht.close();
                    ht = null;
                } catch (IOException e) {
                    e.printStackTrace();

                    innerScope.getSpan().addKVAnnotation(Bytes.toBytes("exception"),
                            Bytes.toBytes(e.getClass().getSimpleName()));

                } catch (Exception e) {
                } finally {
                    if (innerScope != null)
                        innerScope.close();
                    if (rs != null)
                        rs.close();
                }

            }
        };
        service.submit(runnable);
    }

}

From source file:fr.isen.browser5.Util.UrlLoader.java

private void load(String url, Object... args) {
    String method = null, action = null;
    HashMap<String, String> params = null;
    if (args.length == 3) {
        method = (String) args[0];
        action = (String) args[1];
        params = (HashMap<String, String>) args[2];
    }/* w ww.  ja va2 s. c o  m*/
    try {
        url = Str.checkProtocol(url);
        String urlParameters = "";
        if (method != null) {
            url = Str.removeLastSlash(url);
            if (action.startsWith("/")) {
                action = action.substring(1);
            }
            if (action.startsWith("http://") || action.startsWith("https://")) {
                url = action;
            } else {
                url += "/" + action;
            }

            int i = 0;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                urlParameters += entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "UTF-8");
                if (!(i++ == params.size() - 1)) {
                    urlParameters += "&";
                }
            }

            if (method.equals("GET")) {
                url += "?" + urlParameters;
            }
        } else {
            method = "GET";
        }

        System.out.println();
        System.out.println("Loading url: " + url);

        URL obj = new URL(url);
        connection = (HttpURLConnection) obj.openConnection();
        connection.setReadTimeout(10000);
        connection.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
        connection.addRequestProperty("User-Agent", "Lynx/2.8.8dev.3 libwww-FM/2.14 SSL-MM/1.4.1");
        connection.setRequestMethod(method);

        if (method.equals("POST")) {
            byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(postData.length));
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                wr.write(postData);
            }
        }

        if (handleRedirects())
            return;

        handleConnectionResponse();
    } catch (IOException ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, ex.getMessage(), ex.getClass().getSimpleName(),
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:de.tudarmstadt.lt.ltbot.writer.PlainTextDocumentWriter.java

@Override
protected void innerProcess(CrawlURI curi) throws InterruptedException {
    try {//  w  w w.  j  av  a 2  s  .  c o m
        File basedir = getPath().getFile();
        FileUtils.ensureWriteableDirectory(basedir);
    } catch (IOException e) {
        throw new RuntimeException(String.format("Could not ensure writeable base directory '%s'. %s: %s.",
                getPath(), e.getClass().getName(), e.getMessage()), e);
    }
    _num_uris.getAndIncrement();
    RecordingInputStream recis = curi.getRecorder().getRecordedInput();
    if (0L == recis.getResponseContentLength()) {
        return;
    }

    // content already written for this URI.
    boolean is_revisited = curi.getData().containsKey(TEXT_EXTRACT_KEY);
    if (is_revisited)
        return;

    try {
        String cleaned_plaintext = _textExtractorInstance.getCleanedUtf8PlainText(curi);
        updateOuputFile();
        writeplaintext(curi, cleaned_plaintext);
        String cleaned_plaintext_abbr = StringUtils.abbreviate(cleaned_plaintext, 50);
        curi.getData().put(TEXT_EXTRACT_KEY, cleaned_plaintext_abbr);
    } catch (IOException e) {
        curi.getNonFatalFailures().add(e);
    }
}

From source file:org.zodiark.protocol.ProtocolTest.java

@Test
public void testInvalidEnvelop() throws IOException {
    IOException ex = null;
    try {//from   w  w w.j  av  a 2  s  . c  o  m
        Envelope e = mapper.readValue(testInvalidEnvelopPath, Envelope.class);

        assertNotNull(e);

        e.getPath().toString();
        fail();
    } catch (com.fasterxml.jackson.databind.JsonMappingException jme) {
        ex = jme;
    }
    assertEquals(com.fasterxml.jackson.databind.JsonMappingException.class, ex.getClass());
}

From source file:org.zaproxy.zap.extension.ascanrulesAlpha.AbstractAppFilePlugin.java

@Override
public void scan() {
    // Check if the user stopped things. One request per URL so check before
    // sending the request
    if (isStop()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Scanner " + getName() + " Stopping.");
        }/*from w ww  . ja v a 2  s  .  co m*/
        return;
    }

    HttpMessage newRequest = getNewMsg();
    newRequest.getRequestHeader().setMethod(HttpRequestHeader.GET);
    URI baseUri = getBaseMsg().getRequestHeader().getURI();
    URI newUri = null;
    try {
        String baseUriPath = baseUri.getPath() == null ? "" : baseUri.getPath();
        newUri = new URI(baseUri.getScheme(), null, baseUri.getHost(), baseUri.getPort(),
                createTestablePath(baseUriPath));
    } catch (URIException uEx) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(
                    "An error occurred creating a URI for the: " + getName() + " scanner. " + uEx.getMessage(),
                    uEx);
        }
        return;
    }
    try {
        newRequest.getRequestHeader().setURI(newUri);
    } catch (URIException uEx) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("An error occurred setting the URI for a new request used by: " + getName() + " scanner. "
                    + uEx.getMessage(), uEx);
        }
        return;
    }
    // Until https://github.com/zaproxy/zaproxy/issues/3563 is addressed
    // track completed in Kb
    // TODO change this when possible
    synchronized (getKb()) {
        if (getKb().getBoolean(newUri, messagePrefix)) {
            return;
        }
        getKb().add(newUri, messagePrefix, Boolean.TRUE);
    }
    try {
        sendAndReceive(newRequest, false);
    } catch (IOException e) {
        LOG.warn("An error occurred while checking [" + newRequest.getRequestHeader().getMethod() + "] ["
                + newRequest.getRequestHeader().getURI() + "] for " + getName() + " Caught "
                + e.getClass().getName() + " " + e.getMessage());
        return;
    }
    if (isFalsePositive(newRequest)) {
        return;
    }
    int statusCode = newRequest.getResponseHeader().getStatusCode();
    if (statusCode == HttpStatusCode.OK) {
        raiseAlert(newRequest, getRisk(), "");
    } else if (statusCode == HttpStatusCode.UNAUTHORIZED || statusCode == HttpStatusCode.FORBIDDEN) {
        raiseAlert(newRequest, Alert.RISK_INFO, getOtherInfo());
    }
}

From source file:com.intel.ssg.dcst.panthera.cli.PantheraCliDriver.java

int processLocalCmd(String cmd, CommandProcessor proc, CliSessionState ss) {
    int tryCount = 0;
    boolean needRetry;
    int ret = 0;/*  ww  w  . ja v a 2s. c  o m*/

    do {
        try {
            needRetry = false;
            if (proc != null) {
                if (proc instanceof Driver) {
                    SkinDriver qp = (SkinDriver) proc;
                    PrintStream out = ss.out;
                    long start = System.currentTimeMillis();
                    if (ss.getIsVerbose()) {
                        out.println(cmd);
                    }

                    qp.setTryCount(tryCount);
                    ret = qp.run(cmd).getResponseCode();
                    if (ret != 0) {
                        qp.close();
                        return ret;
                    }

                    ArrayList<String> res = new ArrayList<String>();

                    printHeader(qp, out);

                    int counter = 0;
                    try {
                        while (qp.getResults(res)) {
                            for (String r : res) {
                                out.println(r);
                            }
                            counter += res.size();
                            res.clear();
                            if (out.checkError()) {
                                break;
                            }
                        }
                    } catch (IOException e) {
                        console.printError(
                                "Failed with exception " + e.getClass().getName() + ":" + e.getMessage(),
                                "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e));
                        ret = 1;
                    }

                    int cret = qp.close();
                    if (ret == 0) {
                        ret = cret;
                    }

                    long end = System.currentTimeMillis();
                    double timeTaken = (end - start) / 1000.0;
                    console.printInfo("Time taken: " + timeTaken + " seconds"
                            + (counter == 0 ? "" : ", Fetched: " + counter + " row(s)"));

                } else {
                    String firstToken = tokenizeCmd(cmd.trim())[0];
                    String cmd_1 = getFirstCmd(cmd.trim(), firstToken.length());

                    if (ss.getIsVerbose()) {
                        ss.out.println(firstToken + " " + cmd_1);
                    }
                    CommandProcessorResponse res = proc.run(cmd_1);
                    if (res.getResponseCode() != 0) {
                        ss.out.println("Query returned non-zero code: " + res.getResponseCode() + ", cause: "
                                + res.getErrorMessage());
                    }
                    ret = res.getResponseCode();
                }
            }
        } catch (CommandNeedRetryException e) {
            console.printInfo("Retry query with a different approach...");
            tryCount++;
            needRetry = true;
        }
    } while (needRetry);

    return ret;
}

From source file:info.magnolia.cms.servlets.ResourceDispatcher.java

/**
 * Get the requested resource and copy it to the ServletOutputStream, bit by bit.
 *
 * @param req HttpServletRequest as given by the servlet container
 * @param res HttpServletResponse as given by the servlet container
 * @throws IOException standard servlet exception
 *//*ww w . j  ava2  s  .c o  m*/
private void handleResourceRequest(HttpServletRequest req, HttpServletResponse res) throws IOException {

    String resourceHandle = (String) req.getAttribute(Aggregator.HANDLE);
    if (log.isDebugEnabled()) {
        log.debug("handleResourceRequest, resourceHandle=\"" + resourceHandle + "\""); //$NON-NLS-1$ //$NON-NLS-2$
    }
    if (StringUtils.isNotEmpty(resourceHandle)) {
        HierarchyManager hm = (HierarchyManager) req.getAttribute(Aggregator.HIERARCHY_MANAGER);
        InputStream is = null;
        try {
            is = getNodedataAstream(resourceHandle, hm, res);
            if (null != is) {
                // todo find better way to discover if resource could be compressed, implement as in "cache"
                // browsers will always send header saying either it can decompress or not, but
                // resources like jpeg which is already compressed should be not be written on
                // zipped stream otherwise some browsers takes a long time to render
                sendUnCompressed(is, res);
                IOUtils.closeQuietly(is);
                return;
            }
        } catch (IOException e) {
            // don't log at error level since tomcat tipically throws a
            // org.apache.catalina.connector.ClientAbortException if the user stops loading the page
            if (log.isDebugEnabled())
                log.debug("Exception while dispatching resource  " + e.getClass().getName() + ": " //$NON-NLS-1$//$NON-NLS-2$
                        + e.getMessage(), e);
        } catch (Exception e) {
            log.error("Exception while dispatching resource  " + e.getClass().getName() + ": " + e.getMessage(), //$NON-NLS-1$//$NON-NLS-2$
                    e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Resource not found, redirecting request for [" + req.getRequestURI() + "] to 404 URI"); //$NON-NLS-1$
    }

    if (!res.isCommitted()) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {
        log.info("Unable to redirect to 404 page, response is already committed"); //$NON-NLS-1$
    }

}