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:me.schiz.jmeter.protocol.smtp.sampler.SMTPSampler.java

private SampleResult sampleDisconnect(SampleResult sr) {
    SocketClient soclient = SessionStorage.getInstance().getClient(getSOClient());
    SMTPClient client = null;// ww  w  .  j a  v a2 s . c o  m
    if (soclient instanceof SMTPClient)
        client = (SMTPClient) soclient;

    String request = "DISCONNECT \n";
    request += "Client : " + getClient() + "\n";
    sr.setRequestHeaders(request);
    if (client == null) {
        clientNotFound(sr);
    } else {
        synchronized (client) {
            sr.sampleStart();
            try {
                client.disconnect();
                sr.setResponseCode(String.valueOf(client.getReplyCode()));
                setSuccessfulByResponseCode(sr, client.getReplyCode());
                SessionStorage.getInstance().removeClient(getSOClient());

            } catch (IOException e) {
                sr.setSuccessful(false);
                sr.setResponseData(e.toString().getBytes());
                sr.setResponseCode(e.getClass().getName());
                log.error("client `" + client + "` ", e);
                removeClient();
            }
            sr.sampleEnd();
        }
    }
    return sr;
}

From source file:me.schiz.jmeter.protocol.smtp.sampler.SMTPSampler.java

private SampleResult sampleReset(SampleResult sr) {
    SocketClient soclient = SessionStorage.getInstance().getClient(getSOClient());
    SMTPClient client = null;//from   ww  w  .  j  ava 2 s  .  co m
    if (soclient instanceof SMTPClient)
        client = (SMTPClient) soclient;

    String request = "COMMAND\n";
    request += "Client : " + getClient() + "\n";
    sr.setRequestHeaders(request);
    if (client == null) {
        sr.setResponseCode("404");
        sr.setResponseData(("Client `" + getClient() + "` not found").getBytes());
        sr.setSuccessful(false);
        return sr;
    } else {
        synchronized (client) {
            sr.sampleStart();
            try {
                sr.setSuccessful(client.reset());
                sr.setResponseCode(String.valueOf(client.getReplyCode()));
                sr.setResponseData(client.getReplyString().getBytes());
                setSuccessfulByResponseCode(sr, client.getReplyCode());
            } catch (IOException e) {
                sr.setSuccessful(false);
                sr.setResponseData(e.toString().getBytes());
                sr.setResponseCode(e.getClass().getName());
                log.error("client `" + client + "` ", e);
                removeClient();
            }
            sr.sampleEnd();
        }
    }
    return sr;
}

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

/**
 *
 * @param aAppId/*from  ww w . ja va  2  s  .  c o  m*/
 * @param aAppSecret
 * @param aAccessToken
 * @param aTimeout
 * @return
 */
public String getUser(String aAppId, String aAppSecret, String aAccessToken, long aTimeout) {
    if (mLog.isDebugEnabled()) {
        mLog.debug("Requesting user for access-token: '" + aAccessToken + "', app-id: '" + aAppId
                + "', app-secret: '******'" + ", timeout: " + aTimeout + "ms...");
    }
    if (null == aAppSecret) {
        return "{\"code\":-1, \"msg\":\"No client secret passed\"}";
    }
    if (null == aAccessToken) {
        return "{\"code\":-1, \"msg\":\"No access token passed\"}";
    }
    if (aTimeout < 0) {
        return "{\"code\":-1, \"msg\":\"Invalid negative timeout passed\"}";
    }
    String lPostBody;
    mUsername = null;
    mFullname = null;
    mEmail = null;
    String lJSONString = null;
    try {
        lPostBody = "access_token=" + aAccessToken;

        Map lHeaders = new HashMap<String, String>();
        lHeaders.put("Content-Type", "application/x-www-form-urlencoded");

        lJSONString = HTTPSupport.request(mOAuthHost + OAUTH_GETUSER_URL, "POST", lHeaders, lPostBody,
                aTimeout);
        // to simulate a null or empty response or an invalid (e.g. non-JSON) response
        // lJSONString = lJSONString.replaceAll("\"aschulze\"", "null");
        // lJSONString = lJSONString.replaceAll("\"aschulze\"", "\"\"");
        // lJSONString = "<xml>" + lJSONString + "</xml>";
        // lJSONString = "<xml>" + lJSONString + "</xml>";
        // lJSONString = "{\"error\":\"invalid_request\", \"error_description\":\"Validation error\"}";
        // lJSONString = "{\"any other nonsense\":\"non sense\", \"bla bla\":\"radi radi radi\"}";
        Map<String, Object> lJSON = parseJSON(lJSONString);
        if (null != lJSON) {
            String lError = (String) lJSON.get("error");
            if (null != lError) {
                mReturnCode = -1;
                String lErrDescr = (String) lJSON.get("error_description");
                mReturnMsg = lError + " on validating access token: '"
                        + (null != lErrDescr ? lErrDescr : "[No error description from OAuth]") + "'.";
                mLog.error("Username could not be obtained, response: '"
                        + mReturnMsg.replace("\n", "\\n").replace("\r", "\\r") + "'.");
                return "{\"code\":-1, \"msg\":\"" + mReturnMsg + "\"}";
            } else {
                mUsername = (String) lJSON.get("login_name");
                mFullname = (String) lJSON.get("full_user_name");
                mEmail = (String) lJSON.get("email");
                if (null == mUsername || mUsername.isEmpty()) {
                    mReturnCode = -1;
                    mReturnMsg = "OAuth did not deliver a username in field 'login_name' ("
                            + (null == mUsername ? "null" : "empty") + "), response: '" + lJSONString + "'.";
                    mLog.error(mReturnMsg);
                    return "{\"code\":-1, \"msg\":\"" + mReturnMsg + "\"}";
                }
            }
        }
        if (mLog.isDebugEnabled()) {
            mLog.debug(
                    "User obtained, response: '" + lJSONString.replace("\n", "\\n").replace("\r", "\\r") + "'");
        }
        return lJSONString;
    } catch (IOException lEx) {
        mReturnCode = -1;
        mReturnMsg = lEx.getClass().getSimpleName()
                + " validating access token to obtain user name from OAuth host: " + lEx.getMessage();
        lJSONString = "{\"code\":-1, \"msg\":\"" + lEx.getClass().getSimpleName() + "\", \"response\":\""
                + (lJSONString != null ? lJSONString.replace("\"", "\\\"") : "[null]") + "\"}";
        mLog.error("User could not be obtained, response '"
                + lJSONString.replace("\n", "\\n").replace("\r", "\\r") + "'.");
        return lJSONString;
    }
}

From source file:me.schiz.jmeter.protocol.pop3.sampler.POP3Sampler.java

private SampleResult sampleCommand(SampleResult sr) {
    SocketClient soclient = SessionStorage.getInstance().getClient(getSOClient());
    POP3Client client = null;//from w w w  . ja  va  2s .  c  o m
    int responseCode;
    if (soclient instanceof POP3Client)
        client = (POP3Client) soclient;

    String request = "COMMAND\n";
    request += "Client : " + getClient() + "\n";
    request += "Command : " + getCommand() + "\n";
    sr.setRequestHeaders(request);
    if (client == null) {
        clientNotFound(sr);
    } else {
        synchronized (client) {
            sr.sampleStart();
            try {
                String command, args = null;
                int index = getCommand().indexOf(' ');
                if (index != -1) {
                    command = getCommand().substring(0, index);
                    if (index + 1 < getCommand().length())
                        args = getCommand().substring(index + 1, getCommand().length() - 1);
                } else
                    command = getCommand();

                responseCode = (args != null ? client.sendCommand(command, args) : client.sendCommand(command));
                if (getAdditionalReply())
                    client.getAdditionalReply();
                setSuccessfulByResponseCode(sr, responseCode);
                setResponse(sr, client.getReplyStrings());
            } catch (IOException e) {
                sr.setSuccessful(false);
                sr.setResponseData(e.toString().getBytes());
                sr.setResponseCode(e.getClass().getName());
                log.error("client `" + client + "` ", e);
                removeClient();
            }
            sr.sampleEnd();
        }
    }
    return sr;
}

From source file:com.clustercontrol.notify.util.SendSyslog.java

private void sendMsgWithRetry(InetAddress ipAddress, int port, int syslogPriority, String headerTimestamp,
        String hostname, String message) throws IOException {

    String protocol = HinemosPropertyUtil.getHinemosPropertyStr(PROP_PROTOCOL, "udp");

    String sendMessage = "<" + syslogPriority + ">" + headerTimestamp + " " + hostname + " " + message;

    // 1024?????1024??????????
    if (sendMessage.getBytes().length > LIMIT_SIZE) {
        byte[] buf = sendMessage.getBytes();
        sendMessage = new String(buf, 0, LIMIT_SIZE);
    }/*from w w  w  .j a v  a 2s.  co m*/

    m_log.debug("sendMsgWithRetry. (ipAddresss=" + ipAddress + ", port=" + port + ", sendMessage=" + sendMessage
            + ")");

    int retryCount = HinemosPropertyUtil.getHinemosPropertyNum(PROP_RETRY_COUNT, Long.valueOf(1)).intValue();
    int retryInterval = HinemosPropertyUtil.getHinemosPropertyNum(PROP_RETRY_INTERVAL, Long.valueOf(10000))
            .intValue();
    IOException lastException = null;
    int retrytime;
    for (retrytime = 0; retrytime < retryCount; retrytime++) {
        try {
            if ("udp".equals(protocol)) {
                sendUdpMsg(ipAddress, port, sendMessage);
            } else {
                sendTcpMsg(ipAddress, port, sendMessage);
            }

            break;
        } catch (IOException e) {
            m_log.warn("sendMsgWithRetry() : " + e.getClass().getSimpleName() + ", retried time="
                    + (retrytime + 1) + ", protocol=" + protocol + ", message=" + e.getMessage());

            lastException = e;

            try {
                Thread.sleep(retryInterval);
            } catch (InterruptedException e1) {
            }
        }
    }

    if (retrytime == retryCount && lastException != null) {
        throw lastException;
    }
}

From source file:me.schiz.jmeter.protocol.smtp.sampler.SMTPSampler.java

private SampleResult sampleCommand(SampleResult sr) {
    SocketClient soclient = SessionStorage.getInstance().getClient(getSOClient());
    SMTPClient client = null;//w w w  .  j a  v a2s . co  m
    int responseCode = 0;
    if (soclient instanceof SMTPClient)
        client = (SMTPClient) soclient;

    String request = "COMMAND\n";
    request += "Client : " + getClient() + "\n";
    request += "Command : " + getCommand() + "\n";
    sr.setRequestHeaders(request);
    if (client == null) {
        sr.setResponseCode("404");
        sr.setResponseData(("Client `" + getClient() + "` not found").getBytes());
        sr.setSuccessful(false);
        return sr;
    } else {
        synchronized (client) {
            sr.sampleStart();
            try {
                responseCode = client.sendCommand(getCommand());
                sr.setResponseCode(String.valueOf(responseCode));
                sr.setSuccessful(SMTPReply.isPositiveIntermediate(responseCode));
                String response = client.getReplyString();
                setSuccessfulByResponseCode(sr, client.getReplyCode());

                if (SessionStorage.getInstance()
                        .getClientType(getSOClient()) == SessionStorage.proto_type.STARTTLS) {
                    String command;
                    if (getCommand().indexOf(' ') != -1)
                        command = getCommand().substring(0, getCommand().indexOf(' '));
                    else
                        command = getCommand();
                    if ((command.equalsIgnoreCase("lhlo") || command.equalsIgnoreCase("ehlo")
                            || command.equalsIgnoreCase("helo")) && getUseSTARTTLS()
                            && client instanceof SMTPSClient) {
                        SMTPSClient sclient = (SMTPSClient) client;
                        if (sclient.execTLS() == false) {
                            sr.setSuccessful(false);
                            sr.setResponseCode("403");
                            ;
                            response += sclient.getReplyString();
                            log.error("client `" + client + "` STARTTLS failed");
                            removeClient();
                        } else {
                            response += "\nSTARTTLS OK";
                        }
                    }
                }
                sr.setResponseData(response.getBytes());
            } catch (IOException e) {
                sr.setSuccessful(false);
                sr.setResponseData(e.toString().getBytes());
                sr.setResponseCode(e.getClass().getName());
                log.error("client `" + client + "` ", e);
                removeClient();
            }
            sr.sampleEnd();
        }
    }
    return sr;
}

From source file:org.runbuddy.libtomahawk.resolver.ScriptAccount.java

private JsonObject jsHttpRequest(ScriptInterfaceRequestOptions options) {
    Response response = null;//  ww w  . j a va  2 s.  co  m
    try {
        String url = null;
        Map<String, String> headers = null;
        String method = null;
        String username = null;
        String password = null;
        String data = null;
        boolean isTestingConfig = false;
        if (options != null) {
            url = options.url;
            headers = options.headers;
            method = options.method;
            username = options.username;
            password = options.password;
            data = options.data;
            isTestingConfig = options.isTestingConfig;
        }
        java.net.CookieManager cookieManager = getCookieManager(isTestingConfig);
        response = NetworkUtils.httpRequest(method, url, headers, username, password, data, true,
                cookieManager);
        // We have to encode the %-chars because the Android WebView automatically decodes
        // percentage-escaped chars ... for whatever reason. Seems likely that this is a bug.
        String responseText = response.body().string().replace("%", "%25");
        JsonObject responseHeaders = new JsonObject();
        for (String headerName : response.headers().names()) {
            String concatenatedValues = "";
            for (int i = 0; i < response.headers(headerName).size(); i++) {
                if (i > 0) {
                    concatenatedValues += "\n";
                }
                concatenatedValues += response.headers(headerName).get(i);
            }
            String escapedKey = headerName.toLowerCase().replace("%", "%25");
            String escapedValue = concatenatedValues.replace("%", "%25");
            responseHeaders.addProperty(escapedKey, escapedValue);
        }
        int status = response.code();
        String statusText = response.message().replace("%", "%25");

        JsonObject result = new JsonObject();
        result.addProperty("responseText", responseText);
        result.add("responseHeaders", responseHeaders);
        result.addProperty("status", status);
        result.addProperty("statusText", statusText);
        return result;
    } catch (IOException e) {
        Log.e(TAG, "jsHttpRequest: " + e.getClass() + ": " + e.getLocalizedMessage());
        return null;
    } finally {
        if (response != null) {
            try {
                response.body().close();
            } catch (IOException e) {
                Log.e(TAG, "jsHttpRequest: " + e.getClass() + ": " + e.getLocalizedMessage());
            }
        }
    }
}

From source file:com.rallydev.integration.build.rest.RallyRestService.java

protected String getSubscriptionInfo() {
    logMessage("getSubscriptionInfo: attempting to retrieve subscription object ...");
    String reqUrl = getUrl() + "/subscription";
    GetMethod get = new GetMethod(reqUrl);
    try {/*from   w ww .  jav a  2s  .  c  om*/
        String response = doGet(new HttpClient(), get);
        logMessage("getSubscriptionInfo: response from doGet was " + response);
        return response;
    } catch (IOException ex) {
        logMessage("getSubscriptionInfo: IOException " + ex.getClass() + ". Message is " + ex.getMessage());
        return null;
    }
}

From source file:de.tudarmstadt.lt.lm.app.GenerateNgramIndex.java

@Override
public void run() {
    if (!_index_dir.exists())
        _index_dir.mkdir();/*from   w  ww  . j  a v a2 s. co m*/
    _ngram_file = new File(_index_dir, "ngram.raw.txt.gz");
    if (_overwrite && _ngram_file.exists())
        _ngram_file.delete();

    if (!_ngram_file.exists()) {
        new Ngrams() {
            {

                _provider_type = _provider_type_;
                _prvdr = _provider;
                _file = _file_;
                _out = _ngram_file.getAbsolutePath();
                _order_from = _order_from_;
                _order_to = _order_to_;
                _accross_sentences = _accross_sentences_;

            }
        }.run();
    }

    try {
        generate_index();
    } catch (IOException e) {
        LOG.error("Could not generate Ngram index on file '{}'. {}: {}", _file_, e.getClass().getName(),
                e.getMessage());
    }

}

From source file:org.dasein.cloud.google.network.FirewallSupport.java

@Override
public @Nonnull String authorize(@Nonnull String firewallId, @Nonnull Direction direction,
        @Nonnull Permission permission, @Nonnull RuleTarget sourceEndpoint, @Nonnull Protocol protocol,
        @Nonnull RuleTarget destinationEndpoint, int beginPort, int endPort, int precedence)
        throws CloudException, InternalException {
    APITrace.begin(provider, "Firewall.authorize");
    try {//  w  w  w . j  a  v a2  s.  c o m
        if (Permission.DENY.equals(permission)) {
            throw new OperationNotSupportedException("GCE does not support DENY rules");
        }
        if (direction.equals(Direction.EGRESS)) {
            throw new OperationNotSupportedException("GCE does not support EGRESS rules");
        }
        Compute gce = provider.getGoogleCompute();
        com.google.api.services.compute.model.Firewall googleFirewall = new com.google.api.services.compute.model.Firewall();

        Random r = new Random();
        char c = (char) (r.nextInt(26) + 'a');
        googleFirewall.setName(c + UUID.randomUUID().toString());
        googleFirewall.setDescription(
                sourceEndpoint.getCidr() + ":" + protocol.name() + ":" + beginPort + "-" + endPort);

        VLAN vlan = provider.getNetworkServices().getVlanSupport().getVlan(firewallId.split("fw-")[1]);
        googleFirewall.setNetwork(vlan.getTag("contentLink"));

        String portString = "";
        if (beginPort == endPort)
            portString = beginPort + "";
        else {
            portString = beginPort + "-" + endPort;
        }
        ArrayList<Allowed> allowedRules = new ArrayList<Allowed>();
        Allowed allowed = new Allowed();
        allowed.setIPProtocol(protocol.name());
        allowed.setPorts(Collections.singletonList(portString));
        allowedRules.add(allowed);
        googleFirewall.setAllowed(allowedRules);

        if (sourceEndpoint.getRuleTargetType().equals(RuleTargetType.VLAN)
                || sourceEndpoint.getRuleTargetType().equals(RuleTargetType.GLOBAL)) {
            throw new OperationNotSupportedException(
                    "GCE does not support VLAN or GLOBAL as valid source types");
        }
        if (sourceEndpoint.getRuleTargetType().equals(RuleTargetType.VM)) {
            googleFirewall
                    .setSourceTags(Collections.singletonList(sourceEndpoint.getProviderVirtualMachineId()));
        } else if (sourceEndpoint.getRuleTargetType().equals(RuleTargetType.CIDR)) {
            googleFirewall.setSourceRanges(Collections.singletonList(sourceEndpoint.getCidr()));
        }

        if (destinationEndpoint.getRuleTargetType().equals(RuleTargetType.VM)) {
            googleFirewall.setTargetTags(
                    Collections.singletonList(destinationEndpoint.getProviderVirtualMachineId()));
        } else if (!destinationEndpoint.getRuleTargetType().equals(RuleTargetType.VLAN)) {
            throw new OperationNotSupportedException(
                    "GCE only supports either specific VMs or the whole network as a valid destination type");
        }

        try {
            Operation job = gce.firewalls().insert(provider.getContext().getAccountNumber(), googleFirewall)
                    .execute();
            GoogleMethod method = new GoogleMethod(provider);
            return method.getOperationTarget(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION,
                    "", "", false);
        } 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 creating a new rule on " + firewallId + ": " + ex.getMessage());
        }
    } finally {
        APITrace.end();
    }
}