com.alibaba.fastjson.util.IOUtils Java Examples

The following examples show how to use com.alibaba.fastjson.util.IOUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConfFileRWUtils.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
public static void writeFile(String name, String value) throws IOException {
    String path = ResourceUtil.getResourcePathFromRoot(ZookeeperPath.ZK_LOCAL_WRITE_PATH.getKey());
    checkNotNull(path, "write ecache file curr Path :" + path + " is null! It must be not null");
    path = new File(path).getPath() + File.separator + name;

    ByteArrayInputStream input = null;
    byte[] buffers = new byte[256];
    FileOutputStream output = null;
    try {
        int readIndex;
        input = new ByteArrayInputStream(value.getBytes());
        output = new FileOutputStream(path);
        while ((readIndex = input.read(buffers)) != -1) {
            output.write(buffers, 0, readIndex);
        }
    } finally {
        IOUtils.close(output);
        IOUtils.close(input);
    }
}
 
Example #2
Source File: ConfFileRWUtils.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
public static String readFile(String name) throws IOException {
    StringBuilder mapFileStr = new StringBuilder();
    String path = ZookeeperPath.ZK_LOCAL_WRITE_PATH.getKey() + name;
    InputStream input = ResourceUtil.getResourceAsStreamFromRoot(path);
    checkNotNull(input, "read file curr Path :" + path + " is null! It must be not null");
    byte[] buffers = new byte[256];
    try {
        int readIndex;
        while ((readIndex = input.read(buffers)) != -1) {
            mapFileStr.append(new String(buffers, 0, readIndex));
        }
    } finally {
        IOUtils.close(input);
    }
    return mapFileStr.toString();
}
 
Example #3
Source File: JSONScanner.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public byte[] bytesValue() {
    if (token == JSONToken.HEX) {
        int start = np + 1, len = sp;
        if (len % 2 != 0) {
            throw new JSONException("illegal state. " + len);
        }

        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < bytes.length; ++i) {
            char c0 = text.charAt(start + i * 2);
            char c1 = text.charAt(start + i * 2 + 1);

            int b0 = c0 - (c0 <= 57 ? 48 : 55);
            int b1 = c1 - (c1 <= 57 ? 48 : 55);
            bytes[i] = (byte) ((b0 << 4) | b1);
        }

        return bytes;
    }

    return IOUtils.decodeBase64(text, np + 1, sp);
}
 
Example #4
Source File: FastJsonJsonView.java    From uavstack with Apache License 2.0 6 votes vote down vote up
private String getJsonpParameterValue(HttpServletRequest request) {
    if (this.jsonpParameterNames != null) {
        for (String name : this.jsonpParameterNames) {
            String value = request.getParameter(name);

            if (IOUtils.isValidJsonpQueryParam(value)) {
                return value;
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Ignoring invalid jsonp parameter value: " + value);
            }
        }
    }
    return null;
}
 
Example #5
Source File: JSON.java    From uavstack with Apache License 2.0 6 votes vote down vote up
/**
 * @since 1.2.42
 */
public static byte[] toJSONBytes(Object object, SerializeConfig config, SerializeFilter[] filters, int defaultFeatures, SerializerFeature... features) {
    SerializeWriter out = new SerializeWriter(null, defaultFeatures, features);

    try {
        JSONSerializer serializer = new JSONSerializer(out, config);

        if (filters != null) {
            for (SerializeFilter filter : filters) {
                serializer.addFilter(filter);
            }
        }

        serializer.write(object);
        return out.toBytes(IOUtils.UTF8);
    } finally {
        out.close();
    }
}
 
Example #6
Source File: JSONPResponseBodyAdvice.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                              Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                              ServerHttpResponse response) {

    ResponseJSONP responseJsonp = returnType.getMethodAnnotation(ResponseJSONP.class);
    if(responseJsonp == null){
        responseJsonp = returnType.getContainingClass().getAnnotation(ResponseJSONP.class);
    }

    HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
    String callbackMethodName = servletRequest.getParameter(responseJsonp.callback());

    if (!IOUtils.isValidJsonpQueryParam(callbackMethodName)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invalid jsonp parameter value:" + callbackMethodName);
        }
        callbackMethodName = null;
    }

    JSONPObject jsonpObject = new JSONPObject(callbackMethodName);
    jsonpObject.addParameter(body);
    beforeBodyWriteInternal(jsonpObject, selectedContentType, returnType, request, response);
    return jsonpObject;
}
 
Example #7
Source File: JSON.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T parseObject(byte[] input, //
                                int off, //
                                int len, //
                                CharsetDecoder charsetDecoder, //
                                Type clazz, //
                                Feature... features) {
    charsetDecoder.reset();

    int scaleLength = (int) (len * (double) charsetDecoder.maxCharsPerByte());
    char[] chars = allocateChars(scaleLength);

    ByteBuffer byteBuf = ByteBuffer.wrap(input, off, len);
    CharBuffer charByte = CharBuffer.wrap(chars);
    IOUtils.decode(charsetDecoder, byteBuf, charByte);

    int position = charByte.position();

    return (T) parseObject(chars, position, clazz, features);
}
 
Example #8
Source File: SerializeWriter.java    From uavstack with Apache License 2.0 6 votes vote down vote up
private int encodeToUTF8(OutputStream out) throws IOException {

        int bytesLength = (int) (count * (double) 3);
        byte[] bytes = bytesBufLocal.get();

        if (bytes == null) {
            bytes = new byte[1024 * 8];
            bytesBufLocal.set(bytes);
        }

        if (bytes.length < bytesLength) {
            bytes = new byte[bytesLength];
        }

        int position = IOUtils.encodeUTF8(buf, 0, count, bytes);
        out.write(bytes, 0, position);
        return position;
    }
 
Example #9
Source File: SerializeWriter.java    From uavstack with Apache License 2.0 6 votes vote down vote up
private byte[] encodeToUTF8Bytes() {
    int bytesLength = (int) (count * (double) 3);
    byte[] bytes = bytesBufLocal.get();

    if (bytes == null) {
        bytes = new byte[1024 * 8];
        bytesBufLocal.set(bytes);
    }

    if (bytes.length < bytesLength) {
        bytes = new byte[bytesLength];
    }

    int position = IOUtils.encodeUTF8(buf, 0, count, bytes);
    byte[] copy = new byte[position];
    System.arraycopy(bytes, 0, copy, 0, position);
    return copy;
}
 
Example #10
Source File: SerializeWriter.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public void writeInt(int i) {
    if (i == Integer.MIN_VALUE) {
        write("-2147483648");
        return;
    }

    int size = (i < 0) ? IOUtils.stringSize(-i) + 1 : IOUtils.stringSize(i);

    int newcount = count + size;
    if (newcount > buf.length) {
        if (writer == null) {
            expandCapacity(newcount);
        } else {
            char[] chars = new char[size];
            IOUtils.getChars(i, size, chars);
            write(chars, 0, chars.length);
            return;
        }
    }

    IOUtils.getChars(i, newcount, buf);

    count = newcount;
}
 
Example #11
Source File: JSON.java    From uavstack with Apache License 2.0 6 votes vote down vote up
/**
 * @since 1.2.11
 */
@SuppressWarnings("unchecked")
public static <T> T parseObject(byte[] bytes, int offset, int len, Charset charset, Type clazz, Feature... features) {
    if (charset == null) {
        charset = IOUtils.UTF8;
    }
    
    String strVal;
    if (charset == IOUtils.UTF8) {
        char[] chars = allocateChars(bytes.length);
        int chars_len = IOUtils.decodeUTF8(bytes, offset, len, chars);
        if (chars_len < 0) {
            return null;
        }
        strVal = new String(chars, 0, chars_len);
    } else {
        if (len < 0) {
            return null;
        }
        strVal = new String(bytes, offset, len, charset);
    }
    return (T) parseObject(strVal, clazz, features);
}
 
Example #12
Source File: JSONReaderScanner.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public byte[] bytesValue() {
    if (token == JSONToken.HEX) {
        throw new JSONException("TODO");
    }

    return IOUtils.decodeBase64(buf, np + 1, sp);
}
 
Example #13
Source File: JSON.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
  * @since 1.2.11 
  */
 public static final int writeJSONString(OutputStream os, // 
                                         Object object, // 
                                         int defaultFeatures, //
                                         SerializerFeature... features) throws IOException {
    return writeJSONString(os,  //
                           IOUtils.UTF8, //
                           object, //
                           SerializeConfig.globalInstance, //
                           null, //
                           null, // 
                           defaultFeatures, //
                           features);
}
 
Example #14
Source File: JSON.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
 * @since 1.2.11
 */
@SuppressWarnings("unchecked")
public static <T> T parseObject(InputStream is, //
                                Charset charset, //
                                Type type, //
                                Feature... features) throws IOException {
    if (charset == null) {
        charset = IOUtils.UTF8;
    }
    
    byte[] bytes = allocateBytes(1024 * 64);
    int offset = 0;
    for (;;) {
        int readCount = is.read(bytes, offset, bytes.length - offset);
        if (readCount == -1) {
            break;
        }
        offset += readCount;
        if (offset == bytes.length) {
            byte[] newBytes = new byte[bytes.length * 3 / 2];
            System.arraycopy(bytes, 0, newBytes, 0, bytes.length);
            bytes = newBytes;
        }
    }
    
    return (T) parseObject(bytes, 0, offset, charset, type, features);
}
 
Example #15
Source File: JSON.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
 * @since 1.2.11
 */
@SuppressWarnings("unchecked")
public static <T> T parseObject(InputStream is, //
                                Type type, //
                                Feature... features) throws IOException {
    return (T) parseObject(is, IOUtils.UTF8, type, features);
}
 
Example #16
Source File: JSON.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public static Object parse(byte[] input, Feature... features) {
    char[] chars = allocateChars(input.length);
    int len = IOUtils.decodeUTF8(input, 0, input.length, chars);
    if (len < 0) {
        return null;
    }
    return parse(new String(chars, 0, len), features);
}
 
Example #17
Source File: SerializeWriter.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public void writeFieldValue(char seperator, String name, long value) {
    if (value == Long.MIN_VALUE || !quoteFieldNames) {
        write(seperator);
        writeFieldName(name);
        writeLong(value);
        return;
    }

    int intSize = (value < 0) ? IOUtils.stringSize(-value) + 1 : IOUtils.stringSize(value);

    int nameLen = name.length();
    int newcount = count + nameLen + 4 + intSize;
    if (newcount > buf.length) {
        if (writer != null) {
            write(seperator);
            writeFieldName(name);
            writeLong(value);
            return;
        }
        expandCapacity(newcount);
    }

    int start = count;
    count = newcount;

    buf[start] = seperator;

    int nameEnd = start + nameLen + 1;

    buf[start + 1] = keySeperator;

    name.getChars(0, nameLen, buf, start + 2);

    buf[nameEnd + 1] = keySeperator;
    buf[nameEnd + 2] = ':';

    IOUtils.getChars(value, count, buf);
}
 
Example #18
Source File: SerializeWriter.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public void writeFieldValue(char seperator, String name, int value) {
    if (value == Integer.MIN_VALUE || !quoteFieldNames) {
        write(seperator);
        writeFieldName(name);
        writeInt(value);
        return;
    }

    int intSize = (value < 0) ? IOUtils.stringSize(-value) + 1 : IOUtils.stringSize(value);

    int nameLen = name.length();
    int newcount = count + nameLen + 4 + intSize;
    if (newcount > buf.length) {
        if (writer != null) {
            write(seperator);
            writeFieldName(name);
            writeInt(value);
            return;
        }
        expandCapacity(newcount);
    }

    int start = count;
    count = newcount;

    buf[start] = seperator;

    int nameEnd = start + nameLen + 1;

    buf[start + 1] = keySeperator;

    name.getChars(0, nameLen, buf, start + 2);

    buf[nameEnd + 1] = keySeperator;
    buf[nameEnd + 2] = ':';

    IOUtils.getChars(value, count, buf);
}
 
Example #19
Source File: SerializeWriter.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public byte[] toBytes(Charset charset) {
    if (this.writer != null) {
        throw new UnsupportedOperationException("writer not null");
    }
    
    if (charset == IOUtils.UTF8) {
        return encodeToUTF8Bytes();
    } else {
        return new String(buf, 0, count).getBytes(charset);
    }
}
 
Example #20
Source File: SerializeWriter.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public int writeToEx(OutputStream out, Charset charset) throws IOException {
    if (this.writer != null) {
        throw new UnsupportedOperationException("writer not null");
    }
    
    if (charset == IOUtils.UTF8) {
        return encodeToUTF8(out);
    } else {
        byte[] bytes = new String(buf, 0, count).getBytes(charset);
        out.write(bytes);
        return bytes.length;
    }
}
 
Example #21
Source File: GenericFastJsonRedisSerializer.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public Object deserialize(byte[] bytes) throws SerializationException {
    if (bytes == null || bytes.length == 0) {
        return null;
    }
    try {
        return JSON.parseObject(new String(bytes, IOUtils.UTF8), Object.class, defaultRedisConfig);
    } catch (Exception ex) {
        throw new SerializationException("Could not deserialize: " + ex.getMessage(), ex);
    }
}
 
Example #22
Source File: JSONReaderScanner.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public void close() {
    super.close();

    if (buf.length <= 1024 * 64) {
        BUF_LOCAL.set(buf);
    }
    this.buf = null;

    IOUtils.close(reader);
}
 
Example #23
Source File: JSON.java    From uavstack with Apache License 2.0 4 votes vote down vote up
public static Object parse(byte[] input, int off, int len, CharsetDecoder charsetDecoder, int features) {
    charsetDecoder.reset();

    int scaleLength = (int) (len * (double) charsetDecoder.maxCharsPerByte());
    char[] chars = allocateChars(scaleLength);

    ByteBuffer byteBuf = ByteBuffer.wrap(input, off, len);
    CharBuffer charBuf = CharBuffer.wrap(chars);
    IOUtils.decode(charsetDecoder, byteBuf, charBuf);

    int position = charBuf.position();

    DefaultJSONParser parser = new DefaultJSONParser(chars, position, ParserConfig.getGlobalInstance(), features);
    Object value = parser.parse();

    parser.handleResovleTask(value);

    parser.close();

    return value;
}
 
Example #24
Source File: JSON.java    From uavstack with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T parseObject(byte[] bytes, Type clazz, Feature... features) {
    return (T) parseObject(bytes, 0, bytes.length, IOUtils.UTF8, clazz, features);
}
 
Example #25
Source File: SerializeWriter.java    From uavstack with Apache License 2.0 4 votes vote down vote up
public void writeLong(long i) {
    boolean needQuotationMark = isEnabled(SerializerFeature.BrowserCompatible) //
                                && (!isEnabled(SerializerFeature.WriteClassName)) //
                                && (i > 9007199254740991L || i < -9007199254740991L);

    if (i == Long.MIN_VALUE) {
        if (needQuotationMark) write("\"-9223372036854775808\"");
        else write("-9223372036854775808");
        return;
    }

    int size = (i < 0) ? IOUtils.stringSize(-i) + 1 : IOUtils.stringSize(i);

    int newcount = count + size;
    if (needQuotationMark) newcount += 2;
    if (newcount > buf.length) {
        if (writer == null) {
            expandCapacity(newcount);
        } else {
            char[] chars = new char[size];
            IOUtils.getChars(i, size, chars);
            if (needQuotationMark) {
                write('"');
                write(chars, 0, chars.length);
                write('"');
            } else {
                write(chars, 0, chars.length);
            }
            return;
        }
    }

    if (needQuotationMark) {
        buf[count] = '"';
        IOUtils.getChars(i, newcount - 1, buf);
        buf[newcount - 1] = '"';
    } else {
        IOUtils.getChars(i, newcount, buf);
    }

    count = newcount;
}
 
Example #26
Source File: SerializeWriter.java    From uavstack with Apache License 2.0 4 votes vote down vote up
public byte[] toBytes(String charsetName) {
    return toBytes(charsetName == null || "UTF-8".equals(charsetName) //
        ? IOUtils.UTF8 //
        : Charset.forName(charsetName));
}
 
Example #27
Source File: JSONLexerBase.java    From uavstack with Apache License 2.0 4 votes vote down vote up
public final String scanSymbolUnQuoted(final SymbolTable symbolTable) {
    if (token == JSONToken.ERROR && pos == 0 && bp == 1) {
        bp = 0; // adjust
    }
    final boolean[] firstIdentifierFlags = IOUtils.firstIdentifierFlags;
    final char first = ch;

    final boolean firstFlag = ch >= firstIdentifierFlags.length || firstIdentifierFlags[first];
    if (!firstFlag) {
        throw new JSONException("illegal identifier : " + ch //
                + info());
    }

    final boolean[] identifierFlags = IOUtils.identifierFlags;

    int hash = first;

    np = bp;
    sp = 1;
    char chLocal;
    for (;;) {
        chLocal = next();

        if (chLocal < identifierFlags.length) {
            if (!identifierFlags[chLocal]) {
                break;
            }
        }

        hash = 31 * hash + chLocal;

        sp++;
        continue;
    }

    this.ch = charAt(bp);
    token = JSONToken.IDENTIFIER;

    final int NULL_HASH = 3392903;
    if (sp == 4 && hash == NULL_HASH && charAt(np) == 'n' && charAt(np + 1) == 'u' && charAt(np + 2) == 'l'
            && charAt(np + 3) == 'l') {
        return null;
    }

    // return text.substring(np, np + sp).intern();

    if (symbolTable == null) {
        return subString(np, sp);
    }

    return this.addSymbol(np, sp, hash, symbolTable);
    // return symbolTable.addSymbol(buf, np, sp, hash);
}
 
Example #28
Source File: HttpUtils.java    From sds with Apache License 2.0 4 votes vote down vote up
public static String post(String urlPath, Map<String, Object> params) throws Exception {

        URL url = new URL(urlPath);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(1000);
        connection.setReadTimeout(1000);
        connection.setUseCaches(false);
        connection.addRequestProperty("encoding", CHARSET_NAME);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod(HTTP_METHOD);

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        OutputStream os = connection.getOutputStream();
        OutputStreamWriter osr = new OutputStreamWriter(os, CHARSET_NAME);
        BufferedWriter bw = new BufferedWriter(osr);

        /**
         * 构建请求参数
         */
        StringBuilder paramStr = new StringBuilder();
        for (Entry<String, Object> entry : params.entrySet()) {
            if (entry.getValue() == null) {
                continue;
            }

            paramStr.append(entry.getKey())
                    .append("=")
                    .append(URLEncoder.encode(entry.getValue().toString(), CHARSET_NAME))
                    .append("&");
        }

        String paramValue = paramStr.toString();
        if (paramValue.endsWith("&")) {
            paramStr.deleteCharAt(paramValue.length() - 1);
        }

        bw.write(paramStr.toString());
        bw.flush();

        InputStream is = connection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, CHARSET_NAME);
        BufferedReader br = new BufferedReader(isr);

        String line;
        StringBuilder response = new StringBuilder();
        while ((line = br.readLine()) != null) {
            response.append(line);
        }
        IOUtils.close(bw);
        IOUtils.close(osr);
        IOUtils.close(os);
        IOUtils.close(br);
        IOUtils.close(isr);
        IOUtils.close(is);

        return response.toString();
    }