Search in sources :

Example 26 with UnsupportedEncodingException

use of java.io.UnsupportedEncodingException in project openhab1-addons by openhab.

the class ZWaveNodeNamingCommandClass method getString.

/**
     * Get a string from the serial message
     *
     * @param serialMessage
     * @param offset
     * @return String
     */
protected String getString(SerialMessage serialMessage, int offset) {
    int charPresentation = serialMessage.getMessagePayloadByte(offset + 1);
    // First 5 bits are reserved so 0 them
    charPresentation = 0x07 & charPresentation;
    switch(charPresentation) {
        case ENCODING_ASCII:
            logger.debug("NODE {} : Node Name is encoded with standard ASCII codes", this.getNode().getNodeId());
            break;
        case ENCODING_EXTENDED_ASCII:
            logger.debug("NODE {} : Node Name is encoded with standard and OEM Extended ASCII codes", this.getNode().getNodeId());
            break;
        case ENCODING_UTF16:
            logger.debug("NODE {} : Node Name is encoded with Unicode UTF-16", this.getNode().getNodeId());
            break;
        default:
            logger.error("NODE {} : Node Name encoding is unsupported. Encoding code {}", this.getNode().getNodeId(), charPresentation);
            return null;
    }
    int numBytes = serialMessage.getMessagePayload().length - (offset + 2);
    if (numBytes < 0) {
        logger.error("NODE {} : Node Name report error in message length ({})", this.getNode().getNodeId(), serialMessage.getMessagePayload().length);
        return null;
    }
    if (numBytes == 0) {
        return new String();
    }
    // Maximum length is 16 bytes
    if (numBytes > MAX_STRING_LENGTH) {
        logger.warn("NODE {} : Node Name is too big; maximum is {} characters {}", this.getNode().getNodeId(), MAX_STRING_LENGTH, numBytes);
        numBytes = MAX_STRING_LENGTH;
    }
    if (charPresentation != ENCODING_ASCII) {
        logger.debug("NODE {}: Switching to using ASCII encoding", getNode().getNodeId());
        charPresentation = ENCODING_ASCII;
    }
    ByteArrayOutputStream str = new ByteArrayOutputStream();
    // Check for null terminations - ignore anything after the first null
    for (int c = 0; c < numBytes; c++) {
        if (serialMessage.getMessagePayloadByte(c + offset + 2) > 32 && serialMessage.getMessagePayloadByte(c + offset + 2) < 127) {
            str.write((byte) (serialMessage.getMessagePayloadByte(c + offset + 2)));
        }
    }
    try {
        return new String(str.toByteArray(), "ASCII");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
/*
         * byte[] strBuffer = Arrays.copyOfRange(serialMessage.getMessagePayload(), offset + 2, offset + 2 + numBytes);
         *
         * String response = null;
         * try {
         * switch (charPresentation) {
         * case ENCODING_ASCII:
         * // Using standard ASCII codes. (values 128-255 are ignored)
         * break;
         * case ENCODING_EXTENDED_ASCII:
         * // Using standard and OEM Extended ASCII
         * response = new String(strBuffer, "ASCII");
         * break;
         *
         * case ENCODING_UTF16:
         * // Unicode UTF-16
         * String sTemp = new String(strBuffer, "UTF-16");
         * response = new String(sTemp.getBytes("UTF-8"), "UTF-8");
         * break;
         * }
         * } catch (UnsupportedEncodingException uee) {
         * System.out.println("Exception: " + uee);
         * }
         * if (response == null) {
         * return null;
         * }
         *
         * return response.replaceAll("\\p{C}", "?");
         */
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ZWaveEndpoint(org.openhab.binding.zwave.internal.protocol.ZWaveEndpoint)

Example 27 with UnsupportedEncodingException

use of java.io.UnsupportedEncodingException in project weiciyuan by qii.

the class JavaHttpUtility method doUploadFile.

public boolean doUploadFile(String urlStr, Map<String, String> param, String path, String imageParamName, final FileUploaderHttpHelper.ProgressListener listener) throws WeiboException {
    String BOUNDARYSTR = getBoundry();
    File targetFile = new File(path);
    byte[] barry = null;
    int contentLength = 0;
    String sendStr = "";
    try {
        barry = ("--" + BOUNDARYSTR + "--\r\n").getBytes("UTF-8");
        sendStr = getBoundaryMessage(BOUNDARYSTR, param, imageParamName, new File(path).getName(), "image/png");
        contentLength = sendStr.getBytes("UTF-8").length + (int) targetFile.length() + 2 * barry.length;
    } catch (UnsupportedEncodingException e) {
    }
    int totalSent = 0;
    String lenstr = Integer.toString(contentLength);
    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;
    FileInputStream fis = null;
    GlobalContext globalContext = GlobalContext.getInstance();
    String errorStr = globalContext.getString(R.string.timeout);
    globalContext = null;
    try {
        URL url = null;
        url = new URL(urlStr);
        Proxy proxy = getProxy();
        if (proxy != null) {
            urlConnection = (HttpURLConnection) url.openConnection(proxy);
        } else {
            urlConnection = (HttpURLConnection) url.openConnection();
        }
        urlConnection.setConnectTimeout(UPLOAD_CONNECT_TIMEOUT);
        urlConnection.setReadTimeout(UPLOAD_READ_TIMEOUT);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("POST");
        urlConnection.setUseCaches(false);
        urlConnection.setRequestProperty("Connection", "Keep-Alive");
        urlConnection.setRequestProperty("Charset", "UTF-8");
        urlConnection.setRequestProperty("Content-type", "multipart/form-data;boundary=" + BOUNDARYSTR);
        urlConnection.setRequestProperty("Content-Length", lenstr);
        ((HttpURLConnection) urlConnection).setFixedLengthStreamingMode(contentLength);
        urlConnection.connect();
        out = new BufferedOutputStream(urlConnection.getOutputStream());
        out.write(sendStr.getBytes("UTF-8"));
        totalSent += sendStr.getBytes("UTF-8").length;
        fis = new FileInputStream(targetFile);
        int bytesRead;
        int bytesAvailable;
        int bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024;
        bytesAvailable = fis.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        bytesRead = fis.read(buffer, 0, bufferSize);
        long transferred = 0;
        final Thread thread = Thread.currentThread();
        while (bytesRead > 0) {
            if (thread.isInterrupted()) {
                targetFile.delete();
                throw new InterruptedIOException();
            }
            out.write(buffer, 0, bufferSize);
            bytesAvailable = fis.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fis.read(buffer, 0, bufferSize);
            transferred += bytesRead;
            if (transferred % 50 == 0) {
                out.flush();
            }
            if (listener != null) {
                listener.transferred(transferred);
            }
        }
        out.write(barry);
        totalSent += barry.length;
        out.write(barry);
        totalSent += barry.length;
        out.flush();
        out.close();
        if (listener != null) {
            listener.waitServerResponse();
        }
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            String error = handleError(urlConnection);
            throw new WeiboException(error);
        }
        targetFile.delete();
    } catch (IOException e) {
        e.printStackTrace();
        throw new WeiboException(errorStr, e);
    } finally {
        Utility.closeSilently(fis);
        Utility.closeSilently(out);
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return true;
}
Also used : GlobalContext(org.qii.weiciyuan.support.utils.GlobalContext) InterruptedIOException(java.io.InterruptedIOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) URL(java.net.URL) Proxy(java.net.Proxy) HttpURLConnection(java.net.HttpURLConnection) WeiboException(org.qii.weiciyuan.support.error.WeiboException) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Example 28 with UnsupportedEncodingException

use of java.io.UnsupportedEncodingException in project otter by alibaba.

the class SecurityUtils method getMD5Str.

/**
     * MD5 加密
     */
public static String getMD5Str(String str) {
    MessageDigest messageDigest = null;
    try {
        messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.reset();
        messageDigest.update(str.getBytes("UTF-8"));
    } catch (NoSuchAlgorithmException e) {
        System.out.println("NoSuchAlgorithmException caught!");
        System.exit(-1);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    byte[] byteArray = messageDigest.digest();
    StringBuffer md5StrBuff = new StringBuffer();
    for (int i = 0; i < byteArray.length; i++) {
        if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
            md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
        else
            md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
    }
    return md5StrBuff.toString();
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

Example 29 with UnsupportedEncodingException

use of java.io.UnsupportedEncodingException in project hazelcast by hazelcast.

the class IncrementCommandProcessor method handle.

@Override
public void handle(IncrementCommand incrementCommand) {
    String key;
    try {
        key = URLDecoder.decode(incrementCommand.getKey(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new HazelcastException(e);
    }
    String mapName = DEFAULT_MAP_NAME;
    int index = key.indexOf(':');
    if (index != -1) {
        mapName = MAP_NAME_PRECEDER + key.substring(0, index);
        key = key.substring(index + 1);
    }
    try {
        textCommandService.lock(mapName, key);
    } catch (Exception e) {
        incrementCommand.setResponse(NOT_FOUND);
        if (incrementCommand.shouldReply()) {
            textCommandService.sendResponse(incrementCommand);
        }
        return;
    }
    incrementUnderLock(incrementCommand, key, mapName);
    textCommandService.unlock(mapName, key);
    if (incrementCommand.shouldReply()) {
        textCommandService.sendResponse(incrementCommand);
    }
}
Also used : HazelcastException(com.hazelcast.core.HazelcastException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HazelcastException(com.hazelcast.core.HazelcastException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 30 with UnsupportedEncodingException

use of java.io.UnsupportedEncodingException in project hazelcast by hazelcast.

the class HttpPostCommandProcessor method handleChangeClusterVersion.

private void handleChangeClusterVersion(HttpPostCommand command) throws UnsupportedEncodingException {
    byte[] data = command.getData();
    String[] strList = bytesToString(data).split("&");
    String groupName = URLDecoder.decode(strList[0], "UTF-8");
    String groupPass = URLDecoder.decode(strList[1], "UTF-8");
    String versionParam = URLDecoder.decode(strList[2], "UTF-8");
    String res;
    try {
        Node node = textCommandService.getNode();
        ClusterService clusterService = node.getClusterService();
        GroupConfig groupConfig = node.getConfig().getGroupConfig();
        if (!(groupConfig.getName().equals(groupName) && groupConfig.getPassword().equals(groupPass))) {
            res = response(ResponseType.FORBIDDEN);
        } else {
            Version version;
            try {
                version = Version.of(versionParam);
                clusterService.changeClusterVersion(version);
                res = response(ResponseType.SUCCESS, "version", clusterService.getClusterVersion().toString());
            } catch (Exception ex) {
                res = response(ResponseType.FAIL, "version", clusterService.getClusterVersion().toString());
            }
        }
    } catch (Throwable throwable) {
        logger.warning("Error occurred while changing cluster version", throwable);
        res = exceptionResponse(throwable);
    }
    command.setResponse(HttpCommand.CONTENT_TYPE_JSON, stringToBytes(res));
}
Also used : ClusterService(com.hazelcast.internal.cluster.ClusterService) GroupConfig(com.hazelcast.config.GroupConfig) Version(com.hazelcast.version.Version) Node(com.hazelcast.instance.Node) StringUtil.bytesToString(com.hazelcast.util.StringUtil.bytesToString) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

UnsupportedEncodingException (java.io.UnsupportedEncodingException)1401 IOException (java.io.IOException)385 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)150 ArrayList (java.util.ArrayList)129 File (java.io.File)120 InputStream (java.io.InputStream)117 ByteArrayInputStream (java.io.ByteArrayInputStream)107 ByteArrayOutputStream (java.io.ByteArrayOutputStream)101 InputStreamReader (java.io.InputStreamReader)91 MessageDigest (java.security.MessageDigest)87 OutputStreamWriter (java.io.OutputStreamWriter)83 FileNotFoundException (java.io.FileNotFoundException)79 BufferedReader (java.io.BufferedReader)73 URL (java.net.URL)73 HashMap (java.util.HashMap)66 Map (java.util.Map)63 FileOutputStream (java.io.FileOutputStream)56 List (java.util.List)46 JSONException (org.json.JSONException)45 FileInputStream (java.io.FileInputStream)41