Search in sources :

Example 66 with MalformedURLException

use of java.net.MalformedURLException in project XobotOS by xamarin.

the class VMClassLoader method getResources.

/*
     * Get an enumeration with all matching resources.
     */
static List<URL> getResources(String name) {
    ArrayList<URL> list = new ArrayList<URL>();
    int numEntries = getBootClassPathSize();
    for (int i = 0; i < numEntries; i++) {
        String urlStr = getBootClassPathResource(name, i);
        if (urlStr != null) {
            try {
                list.add(new URL(urlStr));
            } catch (MalformedURLException mue) {
                mue.printStackTrace();
            // unexpected; keep going
            }
        }
    }
    return list;
}
Also used : MalformedURLException(java.net.MalformedURLException) ArrayList(java.util.ArrayList) URL(java.net.URL)

Example 67 with MalformedURLException

use of java.net.MalformedURLException in project NoHttp by yanzhenjie.

the class Downloader method download.

public void download(int what, DownloadRequest downloadRequest, DownloadListener downloadListener) {
    validateParam(downloadRequest, downloadListener);
    Connection connection = null;
    RandomAccessFile randomAccessFile = null;
    String savePathDir = downloadRequest.getFileDir();
    String fileName = downloadRequest.getFileName();
    try {
        if (TextUtils.isEmpty(savePathDir))
            savePathDir = NoHttp.getContext().getFilesDir().getAbsolutePath();
        validateDevice(savePathDir);
        if (// auto named.
        TextUtils.isEmpty(fileName))
            fileName = Long.toString(System.currentTimeMillis());
        File tempFile = new File(savePathDir, fileName + ".nohttp");
        // 断点开始处。
        long rangeSize = handleRange(tempFile, downloadRequest);
        // 连接服务器。
        connection = mHttpConnection.getConnection(downloadRequest);
        Exception exception = connection.exception();
        if (exception != null)
            throw exception;
        Logger.i("----------Response Start----------");
        Headers responseHeaders = connection.responseHeaders();
        int responseCode = responseHeaders.getResponseCode();
        // getList filename from server.
        if (downloadRequest.autoNameByHead()) {
            String contentDisposition = responseHeaders.getContentDisposition();
            if (!TextUtils.isEmpty(contentDisposition)) {
                fileName = HeaderUtil.parseHeadValue(contentDisposition, "filename", null);
                if (!TextUtils.isEmpty(fileName)) {
                    try {
                        fileName = URLDecoder.decode(fileName, downloadRequest.getParamsEncoding());
                    } catch (UnsupportedEncodingException e) {
                    // Do nothing.
                    }
                    if (fileName.startsWith("\"") && fileName.endsWith("\"")) {
                        fileName = fileName.substring(1, fileName.length() - 1);
                    }
                }
            }
            // From url.
            if (TextUtils.isEmpty(fileName)) {
                String tempUrl = downloadRequest.url();
                String[] slash = tempUrl.split("/");
                fileName = slash[slash.length - 1];
                int paramIndex = fileName.indexOf("?");
                if (paramIndex > 0) {
                    fileName = fileName.substring(0, paramIndex);
                }
            }
        }
        InputStream serverStream = connection.serverStream();
        if (responseCode >= 400) {
            ServerError error = new ServerError("Download failed, the server response code is " + responseCode + ": " + downloadRequest.url());
            error.setErrorBody(IOUtils.toString(serverStream));
            throw error;
        } else {
            long contentLength;
            // 文件总大小
            if (responseCode == 206) {
                // Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小]。
                // Sample:Accept-Range:bytes 1024-2047/2048。
                String range = responseHeaders.getContentRange();
                try {
                    // 截取'/'之后的总大小。
                    contentLength = Long.parseLong(range.substring(range.indexOf('/') + 1));
                } catch (Throwable e) {
                    throw new ServerError("ResponseCode is 206, but content-Range error in Server HTTP header " + "information: " + range + ".");
                }
            } else if (responseCode == 304) {
                int httpContentLength = responseHeaders.getContentLength();
                downloadListener.onStart(what, true, httpContentLength, responseHeaders, httpContentLength);
                downloadListener.onProgress(what, 100, httpContentLength, 0);
                Logger.d("-------Download finish-------");
                downloadListener.onFinish(what, savePathDir + File.separator + fileName);
                return;
            } else {
                // such as: 200.
                // 服务器不支持Range。
                rangeSize = 0L;
                // 直接下载。
                contentLength = responseHeaders.getContentLength();
            }
            // 验证文件已经存在。
            File lastFile = new File(savePathDir, fileName);
            if (lastFile.exists()) {
                if (downloadRequest.isDeleteOld())
                    IOUtils.delFileOrFolder(lastFile);
                else {
                    downloadListener.onStart(what, true, lastFile.length(), responseHeaders, lastFile.length());
                    downloadListener.onProgress(what, 100, lastFile.length(), 0);
                    Logger.d("-------Download finish-------");
                    downloadListener.onFinish(what, lastFile.getAbsolutePath());
                    return;
                }
            }
            if (IOUtils.getDirSize(savePathDir) < contentLength)
                throw new StorageSpaceNotEnoughError("The folder is not enough space to save the downloaded file:" + " " + savePathDir + ".");
            // 需要重新下载,生成临时文件。
            if (responseCode != 206 && !IOUtils.createNewFile(tempFile))
                throw new StorageReadWriteError("SD isn't available, please check SD card and permission: " + "WRITE_EXTERNAL_STORAGE, and you must pay attention to Android6.0 RunTime " + "Permissions: https://github.com/yanzhenjie/AndPermission.");
            if (downloadRequest.isCanceled()) {
                Log.w("NoHttpDownloader", "Download request is canceled.");
                downloadListener.onCancel(what);
                return;
            }
            // 通知开始下载了。
            Logger.d("-------Download start-------");
            downloadListener.onStart(what, rangeSize > 0, rangeSize, responseHeaders, contentLength);
            randomAccessFile = new RandomAccessFile(tempFile, "rws");
            randomAccessFile.seek(rangeSize);
            byte[] buffer = new byte[8096];
            int len;
            // 旧的进度记录,防止重复通知。
            int oldProgress = 0;
            // 追加目前已经下载的进度。
            long count = rangeSize;
            long startTime = System.currentTimeMillis();
            long speedCount = 0;
            long oldSpeed = 0;
            while (((len = serverStream.read(buffer)) != -1)) {
                if (downloadRequest.isCanceled()) {
                    Log.i("NoHttpDownloader", "Download request is canceled.");
                    downloadListener.onCancel(what);
                    break;
                } else {
                    randomAccessFile.write(buffer, 0, len);
                    count += len;
                    speedCount += len;
                    long time = System.currentTimeMillis() - startTime;
                    long speed = speedCount * 1000 / time;
                    boolean speedChanged = oldSpeed != speed && time >= 300;
                    Logger.i("speedCount: " + speedCount + "; time: " + time + "; speed: " + speed + "; changed: " + "" + speedChanged);
                    if (contentLength != 0) {
                        int progress = (int) (count * 100 / contentLength);
                        if (progress != oldProgress && speedChanged) {
                            downloadListener.onProgress(what, progress, count, speed);
                            speedCount = 0;
                            oldSpeed = speed;
                            startTime = System.currentTimeMillis();
                        } else if (speedChanged) {
                            downloadListener.onProgress(what, oldProgress, count, speed);
                            speedCount = 0;
                            oldSpeed = speed;
                            startTime = System.currentTimeMillis();
                        } else if (progress != oldProgress) {
                            downloadListener.onProgress(what, progress, count, oldSpeed);
                        }
                        oldProgress = progress;
                    } else if (speedChanged) {
                        downloadListener.onProgress(what, 0, count, speed);
                        speedCount = 0;
                        oldSpeed = speed;
                        startTime = System.currentTimeMillis();
                    } else {
                        downloadListener.onProgress(what, 0, count, oldSpeed);
                    }
                }
            }
            if (!downloadRequest.isCanceled()) {
                //noinspection ResultOfMethodCallIgnored
                tempFile.renameTo(lastFile);
                Logger.d("-------Download finish-------");
                downloadListener.onFinish(what, lastFile.getAbsolutePath());
            }
        }
    } catch (MalformedURLException e) {
        Logger.e(e);
        downloadListener.onDownloadError(what, new URLError(e.getMessage()));
    } catch (UnknownHostException e) {
        Logger.e(e);
        downloadListener.onDownloadError(what, new UnKnownHostError(e.getMessage()));
    } catch (SocketTimeoutException e) {
        Logger.e(e);
        downloadListener.onDownloadError(what, new TimeoutError(e.getMessage()));
    } catch (IOException e) {
        Exception newException = e;
        if (!IOUtils.canWrite(savePathDir))
            newException = new StorageReadWriteError("This folder cannot be written to the file: " + savePathDir + ".");
        else if (IOUtils.getDirSize(savePathDir) < 1024)
            newException = new StorageSpaceNotEnoughError("The folder is not enough space to save the downloaded " + "file: " + savePathDir + ".");
        Logger.e(newException);
        downloadListener.onDownloadError(what, newException);
    } catch (Exception e) {
        // NetworkError | ServerError | StorageCantWriteError | StorageSpaceNotEnoughError
        if (!NetUtil.isNetworkAvailable())
            e = new NetworkError("The network is not available.");
        Logger.e(e);
        downloadListener.onDownloadError(what, e);
    } finally {
        Logger.i("----------Response End----------");
        IOUtils.closeQuietly(randomAccessFile);
        IOUtils.closeQuietly(connection);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Headers(com.yanzhenjie.nohttp.Headers) URLError(com.yanzhenjie.nohttp.error.URLError) UnknownHostException(java.net.UnknownHostException) InputStream(java.io.InputStream) ServerError(com.yanzhenjie.nohttp.error.ServerError) StorageReadWriteError(com.yanzhenjie.nohttp.error.StorageReadWriteError) Connection(com.yanzhenjie.nohttp.Connection) HttpConnection(com.yanzhenjie.nohttp.HttpConnection) UnsupportedEncodingException(java.io.UnsupportedEncodingException) StorageSpaceNotEnoughError(com.yanzhenjie.nohttp.error.StorageSpaceNotEnoughError) NetworkError(com.yanzhenjie.nohttp.error.NetworkError) TimeoutError(com.yanzhenjie.nohttp.error.TimeoutError) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SocketTimeoutException(java.net.SocketTimeoutException) RandomAccessFile(java.io.RandomAccessFile) UnKnownHostError(com.yanzhenjie.nohttp.error.UnKnownHostError) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 68 with MalformedURLException

use of java.net.MalformedURLException in project NoHttp by yanzhenjie.

the class HttpConnection method getConnection.

/**
     * Send the request, send only head, parameters, such as file information.
     *
     * @param request {@link IBasicRequest}.
     * @return {@link Connection}.
     */
public Connection getConnection(IBasicRequest request) {
    Logger.d("--------------Request start--------------");
    Headers responseHeaders = new HttpHeaders();
    InputStream inputStream = null;
    Exception exception = null;
    Network network = null;
    String url = request.url();
    try {
        if (!NetUtil.isNetworkAvailable())
            throw new NetworkError("The network is not available, please check the network. The requested url is:" + " " + url);
        // MalformedURLException, IOException, ProtocolException, UnknownHostException, SocketTimeoutException
        network = createConnectionAndWriteData(request);
        Logger.d("-------Response start-------");
        int responseCode = network.getResponseCode();
        responseHeaders = parseResponseHeaders(new URI(request.url()), responseCode, network.getResponseHeaders());
        // handle body
        if (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307) {
            Connection redirectConnection = handleRedirect(request, responseHeaders);
            responseHeaders = redirectConnection.responseHeaders();
            inputStream = redirectConnection.serverStream();
            exception = redirectConnection.exception();
        } else if (hasResponseBody(request.getRequestMethod(), responseCode)) {
            inputStream = network.getServerStream(responseCode, responseHeaders);
        }
        Logger.d("-------Response end-------");
    } catch (MalformedURLException e) {
        exception = new URLError("The url is malformed: " + url + ".");
    } catch (UnknownHostException e) {
        exception = new UnKnownHostError("Hostname can not be resolved: " + url + ".");
    } catch (SocketTimeoutException e) {
        exception = new TimeoutError("Request time out: " + url + ".");
    } catch (Exception e) {
        exception = e;
    } finally {
        if (exception != null)
            Logger.e(exception);
    }
    Logger.d("--------------Request finish--------------");
    return new Connection(network, responseHeaders, inputStream, exception);
}
Also used : MalformedURLException(java.net.MalformedURLException) UnknownHostException(java.net.UnknownHostException) InputStream(java.io.InputStream) HttpURLConnection(java.net.HttpURLConnection) NetworkError(com.yanzhenjie.nohttp.error.NetworkError) TimeoutError(com.yanzhenjie.nohttp.error.TimeoutError) URLError(com.yanzhenjie.nohttp.error.URLError) URI(java.net.URI) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) SocketTimeoutException(java.net.SocketTimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) UnKnownHostError(com.yanzhenjie.nohttp.error.UnKnownHostError)

Example 69 with MalformedURLException

use of java.net.MalformedURLException in project OpenAM by OpenRock.

the class SiteConfiguration method setSiteSecondaryURLs.

/**
     * Sets the secondary URLs of a site.
     *
     * @param ssoToken Single Sign-On Token which is used to access to the
     *        service management datastore.
     * @param siteName Name of the site.
     * @param secondaryURLs secondary URLs of a site.
     * @throws SMSException if errors access in the service management
     *         datastore.
     * @throws SSOException if the <code>ssoToken</code> is not valid.
     */
public static void setSiteSecondaryURLs(SSOToken ssoToken, String siteName, Collection secondaryURLs) throws SMSException, SSOException, ConfigurationException {
    for (Iterator i = secondaryURLs.iterator(); i.hasNext(); ) {
        String url = (String) i.next();
        try {
            FQDNUrl test = new FQDNUrl(url);
            if ((!test.isFullyQualified()) || (test.getPort().length() == 0) || (test.getURI().length() == 0)) {
                String[] param = { url };
                throw new ConfigurationException("invalid.site.secondary.url", param);
            }
        } catch (MalformedURLException ex) {
            String[] param = { url };
            throw new ConfigurationException("invalid.site.secondary.url", param);
        }
    }
    ServiceConfig rootNode = getRootSiteConfig(ssoToken);
    ServiceConfig sc = rootNode.getSubConfig(siteName);
    ServiceConfig accessPoint = sc.getSubConfig(SUBCONFIG_ACCESS_URL);
    Set secondary = accessPoint.getSubConfigNames("*");
    Set toAdd = new HashSet(secondaryURLs.size());
    toAdd.addAll(secondaryURLs);
    Set toRemove = new HashSet(secondary.size());
    if ((secondary != null) && !secondary.isEmpty()) {
        toRemove.addAll(secondary);
        toRemove.removeAll(secondaryURLs);
        toAdd.removeAll(secondary);
    }
    Set allURLs = getAllSiteURLs(ssoToken);
    for (Iterator i = toAdd.iterator(); i.hasNext(); ) {
        String url = (String) i.next();
        if (allURLs.contains(url)) {
            String[] param = { url };
            throw new ConfigurationException("duplicated.site.url", param);
        }
    }
    for (Iterator i = toRemove.iterator(); i.hasNext(); ) {
        String url = (String) i.next();
        accessPoint.removeSubConfig(url);
    }
    for (Iterator i = toAdd.iterator(); i.hasNext(); ) {
        String url = (String) i.next();
        Map values = new HashMap(2);
        Set set = new HashSet(2);
        set.add(getNextId(ssoToken));
        values.put(ATTR_SEC_ID, set);
        accessPoint.addSubConfig(url, SUBCONFIG_SEC_URLS, 0, values);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) FQDNUrl(com.sun.identity.shared.FQDNUrl) ServiceConfig(com.sun.identity.sm.ServiceConfig) HashMap(java.util.HashMap) Iterator(java.util.Iterator) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 70 with MalformedURLException

use of java.net.MalformedURLException in project OpenAM by OpenRock.

the class AssertionIDRequestUtil method sendAssertionIDRequestURI.

/**
     * Sends the Assertion ID to specifiied Assertion ID Request Service and
     * returns <code>Assertion</code> coming from the Assertion ID Request
     * Service.
     *
     * @param assertionID the asssertionID</code> object
     * @param samlAuthorityEntityID entity ID of SAML authority
     * @param role SAML authority role, for example,
     * <code>SAML2Constants.ATTR_AUTH_ROLE</code>, 
     * <code>SAML2Constants.AUTHN_AUTH_ROLE</code> or
     * <code>SAML2Constants.IDP_ROLE</code>
     * @param realm the realm of hosted entity
     *
     * @return the <code>Assertion</code> object
     * @exception SAML2Exception if the operation is not successful
     *
     * @supported.api
     */
public static Assertion sendAssertionIDRequestURI(String assertionID, String samlAuthorityEntityID, String role, String realm) throws SAML2Exception {
    StringBuffer locationSB = new StringBuffer();
    getRoleDescriptorAndLocation(samlAuthorityEntityID, role, realm, SAML2Constants.URI, locationSB);
    if (locationSB.indexOf("?") == -1) {
        locationSB.append("?");
    } else {
        locationSB.append("&");
    }
    locationSB.append("ID=").append(assertionID);
    String location = fillInBasicAuthInfo(locationSB.toString(), realm, samlAuthorityEntityID, role);
    URL url = null;
    try {
        url = new URL(location);
    } catch (MalformedURLException me) {
        throw new SAML2Exception(me.getMessage());
    }
    try {
        HttpURLConnection conn = HttpURLConnectionManager.getConnection(url);
        conn.setInstanceFollowRedirects(false);
        conn.setUseCaches(false);
        conn.setDoOutput(false);
        conn.connect();
        int respCode = conn.getResponseCode();
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("AssertionIDRequestUtil.sendAssertionIDRequestURI: " + "Response code = " + respCode + ", Response message = " + conn.getResponseMessage());
        }
        if (respCode != HttpURLConnection.HTTP_OK) {
            return null;
        }
        String contentType = conn.getContentType();
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("AssertionIDRequestUtil.sendAssertionIDRequestURI: " + "Content type = " + contentType);
        }
        if ((contentType == null) || (contentType.indexOf(MIME_TYPE_ASSERTION) == -1)) {
            return null;
        }
        int contentLength = conn.getContentLength();
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("AssertionIDRequestUtil.sendAssertionIDRequestURI: " + "Content length = " + contentLength);
        }
        BufferedInputStream bin = new BufferedInputStream(conn.getInputStream());
        StringBuffer contentSB = new StringBuffer();
        byte[] content = new byte[2048];
        if (contentLength != -1) {
            int read = 0, totalRead = 0;
            int left;
            while (totalRead < contentLength) {
                left = contentLength - totalRead;
                read = bin.read(content, 0, left < content.length ? left : content.length);
                if (read == -1) {
                    // We need to close connection !!
                    break;
                } else {
                    if (read > 0) {
                        totalRead += read;
                        contentSB.append(new String(content, 0, read));
                    }
                }
            }
        } else {
            int numbytes;
            int totalRead = 0;
            while (true) {
                numbytes = bin.read(content);
                if (numbytes == -1) {
                    break;
                }
                totalRead += numbytes;
                contentSB.append(new String(content, 0, numbytes));
            }
        }
        return AssertionFactory.getInstance().createAssertion(contentSB.toString());
    } catch (IOException ioex) {
        SAML2Utils.debug.error("AssertionIDRequest.sendAssertionIDRequestURI:", ioex);
        throw new SAML2Exception(ioex.getMessage());
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) BufferedInputStream(java.io.BufferedInputStream) IOException(java.io.IOException) URL(java.net.URL)

Aggregations

MalformedURLException (java.net.MalformedURLException)3838 URL (java.net.URL)2885 IOException (java.io.IOException)1194 File (java.io.File)910 ArrayList (java.util.ArrayList)372 InputStream (java.io.InputStream)367 HttpURLConnection (java.net.HttpURLConnection)295 URISyntaxException (java.net.URISyntaxException)270 URI (java.net.URI)239 InputStreamReader (java.io.InputStreamReader)226 BufferedReader (java.io.BufferedReader)208 HashMap (java.util.HashMap)200 URLClassLoader (java.net.URLClassLoader)168 Map (java.util.Map)166 URLConnection (java.net.URLConnection)148 FileNotFoundException (java.io.FileNotFoundException)137 Matcher (java.util.regex.Matcher)132 Test (org.junit.Test)129 UnsupportedEncodingException (java.io.UnsupportedEncodingException)119 Pattern (java.util.regex.Pattern)113