Example usage for java.io IOException getCause

List of usage examples for java.io IOException getCause

Introduction

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

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:com.weibo.api.motan.proxy.RefererInvocationHandler.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (isLocalMethod(method)) {
        if ("toString".equals(method.getName())) {
            return clustersToString();
        }//from ww  w . j  av  a2s . c om
        if ("equals".equals(method.getName())) {
            return proxyEquals(args[0]);
        }
        throw new MotanServiceException("can not invoke local method:" + method.getName());
    }
    DefaultRequest request = new DefaultRequest();
    request.setRequestId(RequestIdGenerator.getRequestId());
    request.setArguments(args);
    String methodName = method.getName();
    boolean async = false;
    if (methodName.endsWith(MotanConstants.ASYNC_SUFFIX)
            && method.getReturnType().equals(ResponseFuture.class)) {
        methodName = MotanFrameworkUtil.removeAsyncSuffix(methodName);
        async = true;
    }
    RpcContext.getContext().putAttribute(MotanConstants.ASYNC_SUFFIX, async);
    request.setMethodName(methodName);
    request.setParamtersDesc(ReflectUtil.getMethodParamDesc(method));
    request.setInterfaceName(interfaceName);
    RpcContext curContext = RpcContext.getContext();
    Map<String, String> attachments = curContext.getRpcAttachments();
    if (!attachments.isEmpty()) { // set rpccontext attachments to request
        for (Map.Entry<String, String> entry : attachments.entrySet()) {
            request.setAttachment(entry.getKey(), entry.getValue());
        }
    }
    if (StringUtils.isNotBlank(curContext.getClientRequestId())) {// add to attachment if client request id is set
        request.setAttachment(URLParamType.requestIdFromClient.getName(), curContext.getClientRequestId());
    }

    //  referer?protocolA,B,C
    // ?AA?BB?C
    for (Cluster<T> cluster : clusters) {
        String protocolSwitcher = MotanConstants.PROTOCOL_SWITCHER_PREFIX + cluster.getUrl().getProtocol();

        Switcher switcher = switcherService.getSwitcher(protocolSwitcher);

        if (switcher != null && !switcher.isOn()) {
            continue;
        }

        request.setAttachment(URLParamType.version.getName(), cluster.getUrl().getVersion());
        request.setAttachment(URLParamType.clientGroup.getName(), cluster.getUrl().getGroup());
        // clientapplicationmodule
        request.setAttachment(URLParamType.application.getName(), cluster.getUrl().getApplication());
        request.setAttachment(URLParamType.module.getName(), cluster.getUrl().getModule());

        Response response = null;
        boolean throwException = Boolean.parseBoolean(cluster.getUrl()
                .getParameter(URLParamType.throwException.getName(), URLParamType.throwException.getValue()));
        Class returnType = getRealReturnType(async, this.clz, method, methodName);
        try {
            response = cluster.call(request);
            if (async) {
                if (response instanceof ResponseFuture) {
                    ((ResponseFuture) response).setReturnType(returnType);
                    return response;
                } else {
                    ResponseFuture responseFuture = new DefaultResponseFuture(request, 0, cluster.getUrl());
                    if (response.getException() != null) {
                        responseFuture.onFailure(response);
                    } else {
                        responseFuture.onSuccess(response);
                    }
                    responseFuture.setReturnType(returnType);
                    return responseFuture;
                }
            } else {
                Object value = response.getValue();
                if (value != null && value instanceof DeserializableObject) {
                    try {
                        value = ((DeserializableObject) value).deserialize(returnType);
                    } catch (IOException e) {
                        LoggerUtil.error("deserialize response value fail! deserialize type:" + returnType, e);
                        throw new MotanFrameworkException(
                                "deserialize return value fail! deserialize type:" + returnType, e);
                    }
                }
                return value;
            }
        } catch (RuntimeException e) {
            if (ExceptionUtil.isBizException(e)) {
                Throwable t = e.getCause();
                // ?ExceptionError
                if (t != null && t instanceof Exception) {
                    throw t;
                } else {
                    String msg = t == null ? "biz exception cause is null. origin error msg : " + e.getMessage()
                            : ("biz exception cause is throwable error:" + t.getClass() + ", errmsg:"
                                    + t.getMessage());
                    throw new MotanServiceException(msg, MotanErrorMsgConstant.SERVICE_DEFAULT_ERROR);
                }
            } else if (!throwException) {
                LoggerUtil.warn("RefererInvocationHandler invoke false, so return default value: uri="
                        + cluster.getUrl().getUri() + " " + MotanFrameworkUtil.toString(request), e);
                return getDefaultReturnValue(returnType);
            } else {
                LoggerUtil.error("RefererInvocationHandler invoke Error: uri=" + cluster.getUrl().getUri() + " "
                        + MotanFrameworkUtil.toString(request), e);
                throw e;
            }
        }
    }

    throw new MotanServiceException("Referer call Error: cluster not exist, interface=" + clz.getName() + " "
            + MotanFrameworkUtil.toString(request), MotanErrorMsgConstant.SERVICE_UNFOUND);

}

From source file:org.opendatakit.survey.android.tasks.DownloadFormsTask.java

private String explodeZips(FormDetails fd, File tempMediaPath, int count, int total) {
    String message = "";

    File[] zips = tempMediaPath.listFiles(new FileFilter() {

        @Override// w  ww .ja  v a  2 s . com
        public boolean accept(File pathname) {
            String name = pathname.getName();
            return pathname.isFile() && name.substring(name.lastIndexOf('.') + 1).equals("zip");
        }
    });

    int zipCount = 0;
    for (File zipfile : zips) {
        ZipFile f = null;
        zipCount++;

        try {
            f = new ZipFile(zipfile, ZipFile.OPEN_READ);
            Enumeration<? extends ZipEntry> entries = f.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                File tempFile = new File(tempMediaPath, entry.getName());
                String formattedString = appContext.getString(R.string.form_download_unzipping, fd.formID,
                        zipfile.getName(), Integer.valueOf(zipCount).toString(),
                        Integer.valueOf(zips.length).toString(), entry.getName());
                publishProgress(formattedString, Integer.valueOf(count).toString(),
                        Integer.valueOf(total).toString());
                if (entry.isDirectory()) {
                    tempFile.mkdirs();
                } else {
                    tempFile.getParentFile().mkdirs();
                    int bufferSize = 8192;
                    InputStream in = new BufferedInputStream(f.getInputStream(entry), bufferSize);
                    OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile, false),
                            bufferSize);

                    // this is slow in the debugger....
                    int value;
                    while ((value = in.read()) != -1) {
                        out.write(value);
                    }
                    out.flush();
                    out.close();
                    in.close();
                }
                WebLogger.getLogger(appName).i(t, "Extracted ZipEntry: " + entry.getName());
            }
        } catch (IOException e) {
            WebLogger.getLogger(appName).printStackTrace(e);
            if (e.getCause() != null) {
                message += e.getCause().getMessage();
            } else {
                message += e.getMessage();
            }
        } finally {
            if (f != null) {
                try {
                    f.close();
                } catch (IOException e) {
                    WebLogger.getLogger(appName).printStackTrace(e);
                    WebLogger.getLogger(appName).e(t, "Closing of ZipFile failed: " + e.toString());
                }
            }
        }
    }

    return (message.equals("") ? null : message);
}

From source file:jp.co.opentone.bsol.framework.web.view.util.ViewHelper.java

/**
 * ???IOException?????????true?.//from  ww w. j  a  v  a  2 s  .  co  m
 * @param e ???
 * @return ?????true
 */
public boolean isDownloadCanceled(IOException e) {
    return e instanceof SocketException || (e.getCause() != null && e.getCause() instanceof SocketException);
}

From source file:org.opendatakit.survey.android.tasks.InitializationTask.java

private final void extractFromRawZip(int resourceId, boolean overwrite, ArrayList<String> result) {
    String message = null;//ww  w  . jav  a2s  .co m
    AssetFileDescriptor fd = null;
    try {
        fd = appContext.getResources().openRawResourceFd(resourceId);
        final long size = fd.getLength(); // apparently over-counts by 2x?
        InputStream rawInputStream = null;
        try {
            rawInputStream = fd.createInputStream();
            ZipInputStream zipInputStream = null;
            ZipEntry entry = null;
            try {

                // count the number of files in the zip
                zipInputStream = new ZipInputStream(rawInputStream);
                int totalFiles = 0;
                while ((entry = zipInputStream.getNextEntry()) != null) {
                    message = null;
                    if (isCancelled()) {
                        message = "cancelled";
                        result.add(entry.getName() + " " + message);
                        break;
                    }
                    ++totalFiles;
                }
                zipInputStream.close();

                // and re-open the stream, reading it this time...
                fd = appContext.getResources().openRawResourceFd(resourceId);
                rawInputStream = fd.createInputStream();
                zipInputStream = new ZipInputStream(rawInputStream);

                long bytesProcessed = 0L;
                long lastBytesProcessedThousands = 0L;
                int nFiles = 0;
                while ((entry = zipInputStream.getNextEntry()) != null) {
                    message = null;
                    if (isCancelled()) {
                        message = "cancelled";
                        result.add(entry.getName() + " " + message);
                        break;
                    }
                    ++nFiles;
                    File tempFile = new File(ODKFileUtils.getAppFolder(appName), entry.getName());
                    String formattedString = appContext.getString(R.string.expansion_unzipping_without_detail,
                            entry.getName(), nFiles, totalFiles);
                    String detail;
                    if (entry.isDirectory()) {
                        detail = appContext.getString(R.string.expansion_create_dir_detail);
                        publishProgress(formattedString, detail);
                        tempFile.mkdirs();
                    } else if (overwrite || !tempFile.exists()) {
                        int bufferSize = 8192;
                        OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile, false),
                                bufferSize);
                        byte buffer[] = new byte[bufferSize];
                        int bread;
                        while ((bread = zipInputStream.read(buffer)) != -1) {
                            bytesProcessed += bread;
                            long curThousands = (bytesProcessed / 1000L);
                            if (curThousands != lastBytesProcessedThousands) {
                                detail = appContext.getString(R.string.expansion_unzipping_detail,
                                        bytesProcessed, size);
                                publishProgress(formattedString, detail);
                                lastBytesProcessedThousands = curThousands;
                            }
                            out.write(buffer, 0, bread);
                        }
                        out.flush();
                        out.close();

                        detail = appContext.getString(R.string.expansion_unzipping_detail, bytesProcessed,
                                size);
                        publishProgress(formattedString, detail);
                    }
                    WebLogger.getLogger(appName).i(t, "Extracted ZipEntry: " + entry.getName());
                }

                String completionString = appContext.getString(R.string.expansion_unzipping_complete,
                        totalFiles);
                publishProgress(completionString, null);
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
                mPendingSuccess = false;
                if (e.getCause() != null) {
                    message = e.getCause().getMessage();
                } else {
                    message = e.getMessage();
                }
                if (entry != null) {
                    result.add(entry.getName() + " " + message);
                } else {
                    result.add("Error accessing zipfile resource " + message);
                }
            } finally {
                if (zipInputStream != null) {
                    try {
                        zipInputStream.close();
                    } catch (IOException e) {
                        WebLogger.getLogger(appName).printStackTrace(e);
                        WebLogger.getLogger(appName).e(t, "Closing of ZipFile failed: " + e.toString());
                    }
                }
            }
        } catch (Exception e) {
            WebLogger.getLogger(appName).printStackTrace(e);
            mPendingSuccess = false;
            if (e.getCause() != null) {
                message = e.getCause().getMessage();
            } else {
                message = e.getMessage();
            }
            result.add("Error accessing zipfile resource " + message);
        } finally {
            if (rawInputStream != null) {
                try {
                    rawInputStream.close();
                } catch (IOException e) {
                    WebLogger.getLogger(appName).printStackTrace(e);
                }
            }
        }
    } finally {
        if (fd != null) {
            try {
                fd.close();
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
            }
        } else {
            result.add("Error accessing zipfile resource.");
        }
    }
}

From source file:com.flipzu.flipzu.FlipInterface.java

public JSONArray getStatus(String username) {
    String url = WSServer + "/ajax/get_status/" + username;

    JSONArray response = null;/*from   www.  ja  v a 2 s  .  c o  m*/
    try {
        response = sendJson(url, null);
    } catch (IOException e) {
        debug.logE(TAG, "getStatus ERROR", e.getCause());
    }

    return response;
}

From source file:com.flipzu.flipzu.FlipInterface.java

public void playAircast(String bcastId) {
    debug.logV(TAG, "playAircast called for " + bcastId);
    String url = WSServer + "/ajax/play_aircast/" + bcastId;

    try {//  w  w  w  . ja  va2  s . c  o  m
        sendRequest(url, null);
    } catch (IOException e) {
        debug.logE(TAG, "playAircast ERROR", e.getCause());
    }
}

From source file:com.flipzu.flipzu.FlipInterface.java

public boolean deleteAircast(Integer bcast_id, String access_token) {
    debug.logV(TAG, "deleteAircast called for " + bcast_id.toString());
    debug.logV(TAG, "deleteAircast called for token" + access_token);
    String url = WSServer + "/api/delete_aircast_id/" + bcast_id.toString();

    String data = "&access_token=" + access_token;

    try {//w ww.  j ava2  s .co m
        sendRequest(url, data);
    } catch (IOException e) {
        debug.logE(TAG, "deleteAircast ERROR", e.getCause());
        return false;
    }

    return true;
}

From source file:bammerbom.ultimatecore.bukkit.UltimateUpdater.java

/**
 * Make a connection to the BukkitDev API and request the newest file's
 * details.//from  w w  w  . jav a  2s.c  om
 *
 * @return true if successful.
 */
private boolean read() {
    try {
        final URLConnection conn = this.url.openConnection();
        conn.setConnectTimeout(5000);

        conn.addRequestProperty("User-Agent", UltimateUpdater.USER_AGENT);

        conn.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.isEmpty()) {
            r.log("No updates found.");
            this.result = UpdateResult.FAIL_BADID;
            return false;
        }

        UltimateUpdater.versionName = (String) ((Map) array.get(array.size() - 1))
                .get(UltimateUpdater.TITLE_VALUE);
        this.versionLink = (String) ((Map) array.get(array.size() - 1)).get(UltimateUpdater.LINK_VALUE);
        this.versionType = (String) ((Map) array.get(array.size() - 1)).get(UltimateUpdater.TYPE_VALUE);
        this.versionGameVersion = (String) ((Map) array.get(array.size() - 1))
                .get(UltimateUpdater.VERSION_VALUE);

        return true;
    } catch (final IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            r.log("Invalid API key.");
            this.result = UpdateResult.FAIL_APIKEY;
        } else {
            r.log("Could not connect to bukkit.org, update check failed. "
                    + (e.getCause() != null ? "(" + e.getCause() + ")" : ""));
            this.result = UpdateResult.FAIL_DBO;
        }
        return false;
    }
}

From source file:org.elasticsearch.client.RestHighLevelClientTests.java

public void testWrapResponseListenerOnSuccess() {
    {/*from   w ww  . jav a 2  s .c o  m*/
        TrackingActionListener trackingActionListener = new TrackingActionListener();
        ResponseListener responseListener = restHighLevelClient.wrapResponseListener(
                response -> response.getStatusLine().getStatusCode(), trackingActionListener,
                Collections.emptySet());
        RestStatus restStatus = randomFrom(RestStatus.values());
        HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
        responseListener.onSuccess(new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse));
        assertNull(trackingActionListener.exception.get());
        assertEquals(restStatus.getStatus(), trackingActionListener.statusCode.get());
    }
    {
        TrackingActionListener trackingActionListener = new TrackingActionListener();
        ResponseListener responseListener = restHighLevelClient.wrapResponseListener(response -> {
            throw new IllegalStateException();
        }, trackingActionListener, Collections.emptySet());
        RestStatus restStatus = randomFrom(RestStatus.values());
        HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
        responseListener.onSuccess(new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse));
        assertThat(trackingActionListener.exception.get(), instanceOf(IOException.class));
        IOException ioe = (IOException) trackingActionListener.exception.get();
        assertEquals(
                "Unable to parse response body for Response{requestLine=GET / http/1.1, host=http://localhost:9200, "
                        + "response=http/1.1 " + restStatus.getStatus() + " " + restStatus.name() + "}",
                ioe.getMessage());
        assertThat(ioe.getCause(), instanceOf(IllegalStateException.class));
    }
}

From source file:org.opendatakit.common.android.task.InitializationTask.java

private final void doActionOnRawZip(int resourceId, boolean overwrite, ArrayList<String> result,
        ZipAction action) {//from w w  w  .  j  a v a  2s .c o  m
    String message = null;
    InputStream rawInputStream = null;
    try {
        rawInputStream = appContext.getResources().openRawResource(resourceId);
        ZipInputStream zipInputStream = null;
        ZipEntry entry = null;
        try {
            int countFiles = 0;

            zipInputStream = new ZipInputStream(rawInputStream);
            while ((entry = zipInputStream.getNextEntry()) != null) {
                message = null;
                if (isCancelled()) {
                    message = "cancelled";
                    result.add(entry.getName() + " " + message);
                    break;
                }
                ++countFiles;
                action.doWorker(entry, zipInputStream, countFiles, 0);
            }
            zipInputStream.close();

            action.done(countFiles);
        } catch (IOException e) {
            WebLogger.getLogger(appName).printStackTrace(e);
            mPendingSuccess = false;
            if (e.getCause() != null) {
                message = e.getCause().getMessage();
            } else {
                message = e.getMessage();
            }
            if (entry != null) {
                result.add(entry.getName() + " " + message);
            } else {
                result.add("Error accessing zipfile resource " + message);
            }
        } finally {
            if (zipInputStream != null) {
                try {
                    zipInputStream.close();
                } catch (IOException e) {
                    WebLogger.getLogger(appName).printStackTrace(e);
                    WebLogger.getLogger(appName).e(t, "Closing of ZipFile failed: " + e.toString());
                }
            }
        }
    } catch (Exception e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        mPendingSuccess = false;
        if (e.getCause() != null) {
            message = e.getCause().getMessage();
        } else {
            message = e.getMessage();
        }
        result.add("Error accessing zipfile resource " + message);
    } finally {
        if (rawInputStream != null) {
            try {
                rawInputStream.close();
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
            }
        }
    }
}