Search in sources :

Example 51 with UnsupportedEncodingException

use of java.io.UnsupportedEncodingException in project midpoint by Evolveum.

the class BeanUnmarshaller method unmarshalProtectedByteArray.

private ProtectedByteArrayType unmarshalProtectedByteArray(PrimitiveXNode<String> prim, Class beanClass, ParsingContext pc) throws SchemaException {
    ProtectedByteArrayType protectedType = new ProtectedByteArrayType();
    String stringValue = prim.getParsedValue(DOMUtil.XSD_STRING, String.class);
    if (stringValue == null) {
        return null;
    }
    try {
        protectedType.setClearValue(ArrayUtils.toObject(stringValue.getBytes("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new SystemException("UTF-8 encoding is not supported", e);
    }
    return protectedType;
}
Also used : SystemException(com.evolveum.midpoint.util.exception.SystemException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PolyString(com.evolveum.midpoint.prism.polystring.PolyString)

Example 52 with UnsupportedEncodingException

use of java.io.UnsupportedEncodingException 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 53 with UnsupportedEncodingException

use of java.io.UnsupportedEncodingException in project NoHttp by yanzhenjie.

the class BasicRequest method buildCommonParams.

////////// static module /////////
/**
     * Split joint non form data.
     *
     * @param paramMap      param map.
     * @param encodeCharset charset.
     * @return string parameter combination, each key value on nails with {@code "&"} space.
     */
public static StringBuilder buildCommonParams(MultiValueMap<String, Object> paramMap, String encodeCharset) {
    StringBuilder paramBuilder = new StringBuilder();
    Set<String> keySet = paramMap.keySet();
    for (String key : keySet) {
        List<Object> values = paramMap.getValues(key);
        for (Object value : values) {
            if (value != null && value instanceof CharSequence) {
                paramBuilder.append("&").append(key).append("=");
                try {
                    paramBuilder.append(URLEncoder.encode(value.toString(), encodeCharset));
                } catch (UnsupportedEncodingException e) {
                    Logger.e("Encoding " + encodeCharset + " format is not supported by the system.");
                    paramBuilder.append(value.toString());
                }
            }
        }
    }
    if (paramBuilder.length() > 0)
        paramBuilder.deleteCharAt(0);
    return paramBuilder;
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONObject(org.json.JSONObject)

Example 54 with UnsupportedEncodingException

use of java.io.UnsupportedEncodingException in project OpenAM by OpenRock.

the class SecureFileHandler method setOutputStream.

/**
     * sets the output stream to the specified output stream ..picked up from
     * StreamHandler.
     *
     */
private void setOutputStream(OutputStream out) throws SecurityException, UnsupportedEncodingException {
    if (out == null) {
        if (Debug.warningEnabled()) {
            Debug.warning(logName + ":SecureFileHandler: " + "OutputStream is null");
        }
    }
    output = out;
    headerWritten = false;
    String encoding = getEncoding();
    if (encoding == null) {
        writer = new OutputStreamWriter(output);
    } else {
        try {
            writer = new OutputStreamWriter(output, encoding);
        } catch (UnsupportedEncodingException ex) {
            Debug.error(logName + ":SecureFileHandler: " + "Unsupported Encoding", ex);
            throw new UnsupportedEncodingException(ex.getMessage());
        }
    }
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) OutputStreamWriter(java.io.OutputStreamWriter)

Example 55 with UnsupportedEncodingException

use of java.io.UnsupportedEncodingException in project OpenAM by OpenRock.

the class CreateHostedIDP method execute.

/**
     * Creates hosted identity provider.
     *
     * @param locale Locale of the Request
     * @param params Map of creation parameters.
     */
public String execute(Locale locale, Map params) throws WorkflowException {
    validateParameters(params);
    String metadataFile = getString(params, ParameterKeys.P_META_DATA);
    boolean hasMetaData = (metadataFile != null) && (metadataFile.trim().length() > 0);
    String metadata = null;
    String extendedData = null;
    if (hasMetaData) {
        String extendedDataFile = getString(params, ParameterKeys.P_EXTENDED_DATA);
        metadata = getContent(metadataFile, locale);
        extendedData = getContent(extendedDataFile, locale);
    } else {
        String entityId = getString(params, ParameterKeys.P_ENTITY_ID);
        String metaAlias = generateMetaAliasForIDP(getString(params, ParameterKeys.P_REALM));
        Map map = new HashMap();
        map.put(MetaTemplateParameters.P_IDP, metaAlias);
        map.put(MetaTemplateParameters.P_IDP_E_CERT, getString(params, ParameterKeys.P_IDP_E_CERT));
        map.put(MetaTemplateParameters.P_IDP_S_CERT, getString(params, ParameterKeys.P_IDP_S_CERT));
        try {
            metadata = CreateSAML2HostedProviderTemplate.buildMetaDataTemplate(entityId, map, getRequestURL(params));
            extendedData = CreateSAML2HostedProviderTemplate.createExtendedDataTemplate(entityId, map, getRequestURL(params));
        } catch (SAML2MetaException e) {
            return e.getMessage();
        }
    }
    String[] results = ImportSAML2MetaData.importData(null, metadata, extendedData);
    String realm = results[0];
    String entityId = results[1];
    String cot = getString(params, ParameterKeys.P_COT);
    if ((cot != null) && (cot.length() > 0)) {
        try {
            AddProviderToCOT.addToCOT(realm, cot, entityId);
        } catch (COTException e) {
            throw new WorkflowException(e.getMessage());
        }
    }
    try {
        List attrMapping = getAttributeMapping(params);
        if (!attrMapping.isEmpty()) {
            SAML2MetaManager manager = new SAML2MetaManager();
            EntityConfigElement config = manager.getEntityConfig(realm, entityId);
            IDPSSOConfigElement ssoConfig = manager.getIDPSSOConfig(realm, entityId);
            Map attribConfig = SAML2MetaUtils.getAttributes(ssoConfig);
            List mappedAttributes = (List) attribConfig.get(SAML2Constants.ATTRIBUTE_MAP);
            mappedAttributes.addAll(attrMapping);
            manager.setEntityConfig(realm, config);
        }
    } catch (SAML2MetaException e) {
        throw new WorkflowException(e.getMessage());
    }
    try {
        return getMessage("idp.configured", locale) + "|||realm=" + realm + "&entityId=" + URLEncoder.encode(entityId, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new WorkflowException(e.getMessage());
    }
}
Also used : HashMap(java.util.HashMap) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IDPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.IDPSSOConfigElement) COTException(com.sun.identity.cot.COTException) SAML2MetaManager(com.sun.identity.saml2.meta.SAML2MetaManager) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) EntityConfigElement(com.sun.identity.saml2.jaxb.entityconfig.EntityConfigElement)

Aggregations

UnsupportedEncodingException (java.io.UnsupportedEncodingException)3108 IOException (java.io.IOException)878 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)284 InputStream (java.io.InputStream)275 ArrayList (java.util.ArrayList)268 InputStreamReader (java.io.InputStreamReader)243 File (java.io.File)234 ByteArrayInputStream (java.io.ByteArrayInputStream)209 ByteArrayOutputStream (java.io.ByteArrayOutputStream)201 FileNotFoundException (java.io.FileNotFoundException)198 HashMap (java.util.HashMap)182 MessageDigest (java.security.MessageDigest)180 BufferedReader (java.io.BufferedReader)150 URL (java.net.URL)150 Map (java.util.Map)148 OutputStreamWriter (java.io.OutputStreamWriter)145 FileOutputStream (java.io.FileOutputStream)120 MalformedURLException (java.net.MalformedURLException)110 FileInputStream (java.io.FileInputStream)107 List (java.util.List)105