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:com.DGSD.DGUtils.Http.BetterHttpRequestRetryHandler.java

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

    this.timesRetried = executionCount;

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

    if (executionCount > maxRetries) {
        // Do not retry if over max retry count
        retry = false;// www.j a  va2 s. c  o m
    } else if (exceptionBlacklist.contains(exception.getClass())) {
        // immediately cancel retry if the error is blacklisted
        retry = false;
    } else if (exceptionWhitelist.contains(exception.getClass())) {
        // immediately retry if error is whitelisted
        retry = true;
    } else if (!sent) {
        // for all other errors, retry only if request hasn't been fully sent yet
        // TODO: refine to resend all idempotent requests
        retry = true;
    } else {
        // otherwise do not retry
        retry = false;
    }

    if (retry) {
        Log.e(BetterHttp.LOG_TAG,
                "request failed (" + exception.getClass().getCanonicalName() + ": " + exception.getMessage()
                        + " / attempt " + executionCount + "), will retry in "
                        + RETRY_SLEEP_TIME_MILLIS / 1000.0 + " seconds");
        SystemClock.sleep(RETRY_SLEEP_TIME_MILLIS);
    } else {
        Log.e(BetterHttp.LOG_TAG, "request failed after " + executionCount + " attempts");
        exception.printStackTrace();
    }

    return retry;
}

From source file:org.jwebsocket.sso.OAuth.java

/**
 *
 * @param aUsername//from   www  . ja  v a 2 s . co  m
 * @param aPassword
 * @param aTimeout
 * @return
 */
@Override
public String getSSOSession(String aUsername, String aPassword, long aTimeout) {
    if (mLog.isDebugEnabled()) {
        mLog.debug("Requesting SSO session for user: '" + aUsername + "', timeout: " + aTimeout + "ms...");
    }
    String lPostBody;
    String lJSONString;
    try {
        lPostBody = null;
        String lCredentials = Base64.encodeBase64String((aUsername + ":" + aPassword).getBytes("UTF-8"));
        Map lHeaders = new HashMap<String, String>();
        lHeaders.put("Authorization", "Basic " + lCredentials);
        lHeaders.put("Cache-Control", "no-cache");
        lHeaders.put("Content-Type", "application/x-www-form-urlencoded");
        lJSONString = HTTPSupport.request(mOAuthHost + mOAuthGetSessionURL, "GET", lHeaders, lPostBody,
                aTimeout);

        Map<String, Object> lJSON = parseJSON(lJSONString);
        mSessionId = (String) lJSON.get("smsession");
        if (mLog.isDebugEnabled()) {
            mLog.debug("SSO session obtained, response: '"
                    + lJSONString.replace("\n", "\\n").replace("\r", "\\r") + "'");
        }
        return lJSONString;
    } catch (IOException lEx) {
        mReturnCode = -1;
        mReturnMsg = lEx.getClass().getSimpleName() + " authenticating directly against OAuth host.";
        lJSONString = "{\"code\":-1, \"msg\":\"" + lEx.getClass().getSimpleName() + ": " + lEx.getMessage()
                + "\"}";
        mLog.error("SSO session could not be obtained, response: '"
                + lJSONString.replace("\n", "\\n").replace("\r", "\\r") + "'");
        return lJSONString;
    }
}

From source file:com.maverick.ssl.SSLTransportImpl.java

void sendMessage(int type, byte[] fragment, int off, int len) throws SSLException {

    // Compress the record?? - since were not using compression the
    // record remains the same
    byte[] encrypted;
    // Calculate the mac
    if (writeCipherSuite.getMACLength() > 0) {
        byte[] mac = writeCipherSuite.generateMAC(fragment, off, len, type, outgoingSequence);
        // Create the final encrypted packet
        encrypted = new byte[len + mac.length];
        System.arraycopy(fragment, off, encrypted, 0, len);
        System.arraycopy(mac, 0, encrypted, len, mac.length);

        // Encrypt the packet
        writeCipherSuite.encrypt(encrypted, 0, encrypted.length);
    } else {/*from  w  ww .  ja v  a  2  s. c  om*/
        if (off > 0 || fragment.length != len) {
            encrypted = new byte[len];
            System.arraycopy(fragment, off, encrypted, 0, len);
        } else {
            encrypted = fragment;
        }
    }

    // Create a record for sending
    ByteArrayOutputStream record = new ByteArrayOutputStream();

    try {
        record.write(type);
        record.write(SSLTransportImpl.VERSION_MAJOR);
        record.write(SSLTransportImpl.VERSION_MINOR);
        record.write((encrypted.length >> 8) & 0xFF);
        record.write(encrypted.length);
        record.write(encrypted);
    } catch (IOException ex) {
        throw new SSLException(SSLException.INTERNAL_ERROR,
                ex.getMessage() == null ? ex.getClass().getName() : ex.getMessage());
    }

    try {
        // Send the record
        rawOut.write(record.toByteArray());
    } catch (IOException ex) {
        throw new SSLException(SSLException.UNEXPECTED_TERMINATION,
                ex.getMessage() == null ? ex.getClass().getName() : ex.getMessage());
    }

    // TODO: check the limit and reset to zero if required
    outgoingSequence++;
}

From source file:com.yourmediashelf.fedora.cargo.FedoraHome.java

private void configureAkubra() throws InstallationFailedException {
    // Rewrite server/config/akubra-llstore.xml replacing the
    // /tmp/[object|datastream]Store constructor-arg values
    // with $FEDORA_HOME/data/[object|datastream]Store
    BufferedReader reader = null;
    PrintWriter writer = null;/*from  w ww  . jav  a  2 s .  c o m*/
    try {
        File file = new File(_installDir, "server/config/spring/akubra-llstore.xml");
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));

        File dataDir = new File(_installDir, "data");
        String oPath = dataDir.getPath() + File.separator + "objectStore";
        String dPath = dataDir.getPath() + File.separator + "datastreamStore";
        StringBuilder xml = new StringBuilder();

        String line = reader.readLine();
        while (line != null) {
            if (line.indexOf("/tmp/objectStore") != -1) {
                line = "    <constructor-arg value=\"" + oPath + "\"/>";
            } else if (line.indexOf("/tmp/datastreamStore") != -1) {
                line = "    <constructor-arg value=\"" + dPath + "\"/>";
            }
            xml.append(line + "\n");
            line = reader.readLine();
        }
        reader.close();

        writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
        writer.print(xml.toString());
        writer.close();
    } catch (IOException e) {
        IOUtils.closeQuietly(reader);
        IOUtils.closeQuietly(writer);
        throw new InstallationFailedException(e.getClass().getName() + ":" + e.getMessage());
    }
}

From source file:org.jwebsocket.sso.OAuth.java

/**
 *
 * @param aSessionId// w  w w .  j  av a2s.com
 * @param aTimeout
 * @return
 */
@Override
public String authSession(String aSessionId, long aTimeout) {
    if (mLog.isDebugEnabled()) {
        mLog.debug("Authenticating session '" + aSessionId + "'" + "', timeout: " + aTimeout + "ms...");
    }
    String lPostBody;
    String lJSONString;
    try {
        URLCodec lCodec = new URLCodec();
        lPostBody = "grant_type=password&" + SSO_SESSION_COOKIE_NAME + "=" + lCodec.encode(aSessionId, "UTF-8");
        Map lHeaders = new HashMap<String, String>();
        lHeaders.put("Content-Type", "application/x-www-form-urlencoded");
        String lAuthStr = Base64
                .encodeBase64String((getOAuthAppId() + ":" + getOAuthAppSecret()).getBytes("UTF-8"));
        lHeaders.put("Authorization", "Basic " + lAuthStr);
        lJSONString = HTTPSupport.request(mOAuthHost + OAUTH_AUTHSESSION_URL, "POST", lHeaders, lPostBody,
                aTimeout);
        Map<String, Object> lJSON = parseJSON(lJSONString);
        mAccessToken = (String) lJSON.get("access_token");
        mRefreshToken = (String) lJSON.get("refresh_token");
        if (mLog.isDebugEnabled()) {
            mLog.debug("Session authenticated, response: '"
                    + lJSONString.replace("\n", "\\n").replace("\r", "\\r") + "'");
        }
        return lJSONString;
    } catch (IOException lEx) {
        mReturnCode = -1;
        mReturnMsg = lEx.getClass().getSimpleName() + " authenticating session against OAuth host.";
        lJSONString = "{\"code\":-1, \"msg\":\"" + lEx.getClass().getSimpleName() + ": " + lEx.getMessage()
                + "\"}";
        mLog.error("Session could not be authenticated, response: '"
                + lJSONString.replace("\n", "\\n").replace("\r", "\\r") + "'");
        return lJSONString;
    }
}

From source file:org.jwebsocket.sso.OAuth.java

/**
 *
 * @param aRefreshToken//from  w w  w.j a  va2  s.  c o  m
 * @param aTimeout
 * @return
 */
public String refreshAccessToken(String aRefreshToken, long aTimeout) {
    if (mLog.isDebugEnabled()) {
        mLog.debug("Refreshing access-token with refresh token: '" + aRefreshToken + "', app-id: '"
                + getOAuthAppId() + "', app-secret: '******'" + "', timeout: " + aTimeout + "ms...");
    }
    String lPostBody;
    String lJSONString;
    try {
        lPostBody = "client_id=ro_client" + "&grant_type=refresh_token" + "&refresh_token="
                + URLEncoder.encode(aRefreshToken, "UTF-8");
        Map lHeaders = new HashMap<String, String>();
        lHeaders.put("Content-Type", "application/x-www-form-urlencoded");
        String lAuthStr = Base64
                .encodeBase64String((getOAuthAppId() + ":" + getOAuthAppSecret()).getBytes("UTF-8"));
        lHeaders.put("Authorization", "Basic " + lAuthStr);

        lJSONString = HTTPSupport.request(mOAuthHost + OAUTH_REFRESHTOKEN_URL, "POST", lHeaders, lPostBody,
                aTimeout);
        Map<String, Object> lJSON = parseJSON(lJSONString);
        mAccessToken = (String) lJSON.get("access_token");
        if (mLog.isDebugEnabled()) {
            mLog.debug("Access token refreshed, response: '"
                    + lJSONString.replace("\n", "\\n").replace("\r", "\\r") + "'");
        }
        return lJSONString;
    } catch (IOException lEx) {
        mReturnCode = -1;
        mReturnMsg = lEx.getClass().getSimpleName() + " refreshing acceess token from OAuth host.";
        lJSONString = "{\"code\":-1, \"msg\":\"" + lEx.getClass().getSimpleName() + ": " + lEx.getMessage()
                + "\"}";
        mLog.error("Token could not be refreshed, response: '"
                + lJSONString.replace("\n", "\\n").replace("\r", "\\r") + "'");
        return lJSONString;
    }
}

From source file:com.dongfang.net.http.RetryHandler.java

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

    if (exception == null || context == null) {
        return false;
    }/* w ww .  j av  a  2  s. c om*/

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

    if (retriedTimes > maxRetries) {
        retry = false;
    } else if (exceptionBlackList.contains(exception.getClass())) {
        retry = false;
    } else if (exceptionWhiteList.contains(exception.getClass())) {
        retry = true;
    } else if (!sent) {
        retry = true;
    }

    if (retry) {
        try {
            Object currRequest = context.getAttribute(ExecutionContext.HTTP_REQUEST);
            if (currRequest != null) {
                if (currRequest instanceof HttpRequestBase) {
                    HttpRequestBase requestBase = (HttpRequestBase) currRequest;
                    retry = "GET".equals(requestBase.getMethod());
                } else if (currRequest instanceof RequestWrapper) {
                    RequestWrapper requestWrapper = (RequestWrapper) currRequest;
                    retry = "GET".equals(requestWrapper.getMethod());
                }
            } else {
                retry = false;
                ULog.e("retry error, curr request is null");
            }
        } catch (Throwable e) {
            retry = false;
            ULog.e("retry error", e);
        }
    }

    if (retry) {
        SystemClock.sleep(RETRY_SLEEP_INTERVAL); // sleep a while and retry http request again.
    }

    return retry;
}

From source file:org.sakaiproject.calendaring.api.ExternalCalendaringServiceImpl.java

/**
 * {@inheritDoc}//from ww w. j  av  a 2  s  .  c om
 */
public String toFile(Calendar calendar) {

    if (!isIcsEnabled()) {
        log.debug(
                "ExternalCalendaringService is disabled. Enable via calendar.ics.generation.enabled=true in sakai.properties");
        return null;
    }

    //null check
    if (calendar == null) {
        log.error("Calendar is null, cannot generate ICS file.");
        return null;
    }

    String path = generateFilePath(UUID.randomUUID().toString());

    //test file
    File file = new File(path);
    try {
        if (!file.createNewFile()) {
            log.error("Couldn't write file to: " + path);
            return null;
        }
    } catch (IOException e) {
        log.error("An error occurred trying to write file to: " + path + " : " + e.getClass() + " : "
                + e.getMessage());
        return null;
    }

    //if cleanup enabled, mark for deletion when the JVM exits.
    if (sakaiProxy.isCleanupEnabled()) {
        file.deleteOnExit();
    }

    FileOutputStream fout;
    try {
        fout = new FileOutputStream(file);

        CalendarOutputter outputter = new CalendarOutputter();
        outputter.output(calendar, fout);

        fout.flush();
        fout.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ValidationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return path;

}

From source file:org.apache.hadoop.hbase.master.assignment.RegionTransitionProcedure.java

@Override
public void remoteCallFailed(final MasterProcedureEnv env, final ServerName serverName,
        final IOException exception) {
    final RegionStateNode regionNode = getRegionState(env);
    assert serverName.equals(regionNode.getRegionLocation());
    String msg = exception.getMessage() == null ? exception.getClass().getSimpleName() : exception.getMessage();
    LOG.warn("Failed " + this + "; " + regionNode.toShortString() + "; exception=" + msg);
    remoteCallFailed(env, regionNode, exception);
    // NOTE: This call to wakeEvent puts this Procedure back on the scheduler.
    // Thereafter, another Worker can be in here so DO NOT MESS WITH STATE beyond
    // this method. Just get out of this current processing quickly.
    env.getProcedureScheduler().wakeEvent(regionNode.getProcedureEvent());
}

From source file:org.apache.flink.streaming.api.functions.sink.SocketClientSinkTest.java

@Test
public void testSocketSinkNoRetry() throws Exception {
    final ServerSocket server = new ServerSocket(0);
    final int port = server.getLocalPort();

    try {/*from  w w w.  j av  a  2  s .c om*/
        final AtomicReference<Throwable> error = new AtomicReference<Throwable>();

        Thread serverRunner = new Thread("Test server runner") {

            @Override
            public void run() {
                try {
                    Socket sk = server.accept();
                    sk.close();
                } catch (Throwable t) {
                    error.set(t);
                }
            }
        };
        serverRunner.start();

        SocketClientSink<String> simpleSink = new SocketClientSink<>(host, port, simpleSchema, 0, true);
        simpleSink.open(new Configuration());

        // wait socket server to close
        serverRunner.join();
        if (error.get() != null) {
            Throwable t = error.get();
            t.printStackTrace();
            fail("Error in server thread: " + t.getMessage());
        }

        try {
            // socket should be closed, so this should trigger a re-try
            // need two messages here: send a fin to cancel the client state:FIN_WAIT_2 while the server is CLOSE_WAIT
            while (true) { // we have to do this more often as the server side closed is not guaranteed to be noticed immediately
                simpleSink.invoke(TEST_MESSAGE + '\n');
            }
        } catch (IOException e) {
            // check whether throw a exception that reconnect failed.
            assertTrue("Wrong exception", e.getMessage().contains(EXCEPTION_MESSGAE));
        } catch (Exception e) {
            fail("wrong exception: " + e.getClass().getName() + " - " + e.getMessage());
        }

        assertEquals(0, simpleSink.getCurrentNumberOfRetries());
    } finally {
        IOUtils.closeQuietly(server);
    }
}