org.apache.tomcat.util.buf.B2CConverter Java Examples

The following examples show how to use org.apache.tomcat.util.buf.B2CConverter. 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: RequestUtil.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Append request parameters from the specified String to the specified
 * Map.  It is presumed that the specified Map is not accessed from any
 * other thread, so no synchronization is performed.
 * <p>
 * <strong>IMPLEMENTATION NOTE</strong>:  URL decoding is performed
 * individually on the parsed name and value elements, rather than on
 * the entire query string ahead of time, to properly deal with the case
 * where the name or value includes an encoded "=" or "&" character
 * that would otherwise be interpreted as a delimiter.
 *
 * @param map Map that accumulates the resulting parameters
 * @param data Input string containing request parameters
 * @param encoding The encoding to use; encoding must not be null.
 * If an unsupported encoding is specified the parameters will not be
 * parsed and the map will not be modified
 */
public static void parseParameters(Map<String,String[]> map, String data,
        String encoding) {

    if ((data != null) && (data.length() > 0)) {

        // use the specified encoding to extract bytes out of the
        // given string so that the encoding is not lost.
        byte[] bytes = null;
        try {
            bytes = data.getBytes(B2CConverter.getCharset(encoding));
            parseParameters(map, bytes, encoding);
        } catch (UnsupportedEncodingException uee) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("requestUtil.parseParameters.uee",
                        encoding), uee);
            }
        }

    }

}
 
Example #2
Source File: RequestUtil.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Decode and return the specified URL-encoded String.
 *
 * @param str The url-encoded string
 * @param enc The encoding to use; if null, the default encoding is used. If
 * an unsupported encoding is specified null will be returned
 * @param isQuery Is this a query string being processed
 * @exception IllegalArgumentException if a '%' character is not followed
 * by a valid 2-digit hexadecimal number
 */
public static String URLDecode(String str, String enc, boolean isQuery) {
    if (str == null)
        return (null);

    // use the specified encoding to extract bytes out of the
    // given string so that the encoding is not lost. If an
    // encoding is not specified, let it use platform default
    byte[] bytes = null;
    try {
        if (enc == null) {
            bytes = str.getBytes(Charset.defaultCharset());
        } else {
            bytes = str.getBytes(B2CConverter.getCharset(enc));
        }
    } catch (UnsupportedEncodingException uee) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee);
        }
    }

    return URLDecode(bytes, enc, isQuery);

}
 
Example #3
Source File: RequestUtil.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Append request parameters from the specified String to the specified
 * Map.  It is presumed that the specified Map is not accessed from any
 * other thread, so no synchronization is performed.
 * <p>
 * <strong>IMPLEMENTATION NOTE</strong>:  URL decoding is performed
 * individually on the parsed name and value elements, rather than on
 * the entire query string ahead of time, to properly deal with the case
 * where the name or value includes an encoded "=" or "&" character
 * that would otherwise be interpreted as a delimiter.
 *
 * @param map Map that accumulates the resulting parameters
 * @param data Input string containing request parameters
 * @param encoding The encoding to use; encoding must not be null.
 * If an unsupported encoding is specified the parameters will not be
 * parsed and the map will not be modified
 */
public static void parseParameters(Map<String,String[]> map, String data,
        String encoding) {

    if ((data != null) && (data.length() > 0)) {

        // use the specified encoding to extract bytes out of the
        // given string so that the encoding is not lost.
        byte[] bytes = null;
        try {
            bytes = data.getBytes(B2CConverter.getCharset(encoding));
            parseParameters(map, bytes, encoding);
        } catch (UnsupportedEncodingException uee) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("requestUtil.parseParameters.uee",
                        encoding), uee);
            }
        }

    }

}
 
Example #4
Source File: TestInputBuffer.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private void doUtf8BodyTest(String description, int[] input,
        String expected) throws Exception {

    byte[] bytes = new byte[input.length];
    for (int i = 0; i < input.length; i++) {
        bytes[i] = (byte) input[i];
    }

    ByteChunk bc = new ByteChunk();
    int rc = postUrl(bytes, "http://localhost:" + getPort() + "/test", bc,
            null);

    if (expected == null) {
        Assert.assertEquals(description, HttpServletResponse.SC_OK, rc);
        Assert.assertEquals(description, "FAILED", bc.toString());
    } else if (expected.length() == 0) {
        Assert.assertNull(description, bc.toString());
    } else {
        bc.setCharset(B2CConverter.UTF_8);
        Assert.assertEquals(description, expected, bc.toString());
    }
}
 
Example #5
Source File: WebSocketServlet.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private String getWebSocketAccept(String key) throws ServletException {

        MessageDigest sha1Helper = sha1Helpers.poll();
        if (sha1Helper == null) {
            try {
                sha1Helper = MessageDigest.getInstance("SHA1");
            } catch (NoSuchAlgorithmException e) {
                throw new ServletException(e);
            }
        }

        sha1Helper.reset();
        sha1Helper.update(key.getBytes(B2CConverter.ISO_8859_1));
        String result = Base64.encode(sha1Helper.digest(WS_ACCEPT));

        sha1Helpers.add(sha1Helper);

        return result;
    }
 
Example #6
Source File: Response.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Overrides the character encoding used in the body of the response. This
 * method must be called prior to writing output using getWriter().
 *
 * @param characterEncoding The name of character encoding.
 */
public void setCharacterEncoding(String characterEncoding) {
    if (isCommitted()) {
        return;
    }
    if (characterEncoding == null) {
        return;
    }

    try {
        this.charset = B2CConverter.getCharset(characterEncoding);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException(e);
    }
    this.characterEncoding = characterEncoding;
}
 
Example #7
Source File: WsOutbound.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private void doWriteText(CharBuffer buffer, boolean finalFragment)
        throws IOException {
    CharsetEncoder encoder = B2CConverter.UTF_8.newEncoder();
    do {
        CoderResult cr = encoder.encode(buffer, bb, true);
        if (cr.isError()) {
            cr.throwException();
        }
        bb.flip();
        if (buffer.hasRemaining()) {
            doWriteBytes(bb, false);
        } else {
            doWriteBytes(bb, finalFragment);
        }
    } while (buffer.hasRemaining());

    // Reset - bb will be cleared in doWriteBytes()
    cb.clear();
}
 
Example #8
Source File: TestInputBuffer.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private void doUtf8BodyTest(String description, int[] input,
        String expected) throws Exception {

    byte[] bytes = new byte[input.length];
    for (int i = 0; i < input.length; i++) {
        bytes[i] = (byte) input[i];
    }

    ByteChunk bc = new ByteChunk();
    int rc = postUrl(bytes, "http://localhost:" + getPort() + "/test", bc,
            null);

    if (expected == null) {
        Assert.assertEquals(description, HttpServletResponse.SC_OK, rc);
        Assert.assertEquals(description, "FAILED", bc.toString());
    } else if (expected.length() == 0) {
        Assert.assertNull(description, bc.toString());
    } else {
        bc.setCharset(B2CConverter.UTF_8);
        Assert.assertEquals(description, expected, bc.toString());
    }
}
 
Example #9
Source File: RequestUtil.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Decode and return the specified URL-encoded String.
 *
 * @param str The url-encoded string
 * @param enc The encoding to use; if null, the default encoding is used. If
 * an unsupported encoding is specified null will be returned
 * @param isQuery Is this a query string being processed
 * @exception IllegalArgumentException if a '%' character is not followed
 * by a valid 2-digit hexadecimal number
 */
public static String URLDecode(String str, String enc, boolean isQuery) {
    if (str == null)
        return (null);

    // use the specified encoding to extract bytes out of the
    // given string so that the encoding is not lost. If an
    // encoding is not specified, let it use platform default
    byte[] bytes = null;
    try {
        if (enc == null) {
            bytes = str.getBytes(Charset.defaultCharset());
        } else {
            bytes = str.getBytes(B2CConverter.getCharset(enc));
        }
    } catch (UnsupportedEncodingException uee) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee);
        }
    }

    return URLDecode(bytes, enc, isQuery);

}
 
Example #10
Source File: TestRestCsrfPreventionFilter2.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private void testInvalidPostWithRequestParams() throws Exception {
    String validBody = Constants.CSRF_REST_NONCE_HEADER_NAME + "=" + validNonce;
    String invalidbody1 = Constants.CSRF_REST_NONCE_HEADER_NAME + "=" + INVALID_NONCE_1;
    String invalidbody2 = Constants.CSRF_REST_NONCE_HEADER_NAME + "="
            + Constants.CSRF_REST_NONCE_HEADER_FETCH_VALUE;
    doTest(METHOD_POST, REMOVE_ALL_CUSTOMERS, CREDENTIALS,
            validBody.getBytes(B2CConverter.ISO_8859_1), USE_COOKIES,
            HttpServletResponse.SC_FORBIDDEN, null, null, true,
            Constants.CSRF_REST_NONCE_HEADER_REQUIRED_VALUE);
    doTest(METHOD_POST, REMOVE_CUSTOMER, CREDENTIALS,
            invalidbody1.getBytes(B2CConverter.ISO_8859_1), USE_COOKIES,
            HttpServletResponse.SC_FORBIDDEN, null, null, true,
            Constants.CSRF_REST_NONCE_HEADER_REQUIRED_VALUE);
    doTest(METHOD_POST, REMOVE_CUSTOMER, CREDENTIALS,
            invalidbody2.getBytes(B2CConverter.ISO_8859_1), USE_COOKIES,
            HttpServletResponse.SC_FORBIDDEN, null, null, true,
            Constants.CSRF_REST_NONCE_HEADER_REQUIRED_VALUE);
}
 
Example #11
Source File: OutputBuffer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private static Charset getCharset(final String encoding) throws IOException {
    if (Globals.IS_SECURITY_ENABLED) {
        try {
            return AccessController.doPrivileged(new PrivilegedExceptionAction<Charset>() {
                @Override
                public Charset run() throws IOException {
                    return B2CConverter.getCharset(encoding);
                }
            });
        } catch (PrivilegedActionException ex) {
            Exception e = ex.getException();
            if (e instanceof IOException) {
                throw (IOException) e;
            } else {
                throw new IOException(ex);
            }
        }
    } else {
        return B2CConverter.getCharset(encoding);
    }
}
 
Example #12
Source File: WebSocketServlet.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private String getWebSocketAccept(String key) throws ServletException {

        MessageDigest sha1Helper = sha1Helpers.poll();
        if (sha1Helper == null) {
            try {
                sha1Helper = MessageDigest.getInstance("SHA1");
            } catch (NoSuchAlgorithmException e) {
                throw new ServletException(e);
            }
        }

        sha1Helper.reset();
        sha1Helper.update(key.getBytes(B2CConverter.ISO_8859_1));
        String result = Base64.encode(sha1Helper.digest(WS_ACCEPT));

        sha1Helpers.add(sha1Helper);

        return result;
    }
 
Example #13
Source File: WsOutbound.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private void doWriteText(CharBuffer buffer, boolean finalFragment)
        throws IOException {
    CharsetEncoder encoder = B2CConverter.UTF_8.newEncoder();
    do {
        CoderResult cr = encoder.encode(buffer, bb, true);
        if (cr.isError()) {
            cr.throwException();
        }
        bb.flip();
        if (buffer.hasRemaining()) {
            doWriteBytes(bb, false);
        } else {
            doWriteBytes(bb, finalFragment);
        }
    } while (buffer.hasRemaining());

    // Reset - bb will be cleared in doWriteBytes()
    cb.clear();
}
 
Example #14
Source File: InputBuffer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private static B2CConverter createConverter(final Charset charset) throws IOException {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        try {
            return AccessController.doPrivileged(new PrivilegedExceptionAction<B2CConverter>() {

                @Override
                public B2CConverter run() throws IOException {
                    return new B2CConverter(charset);
                }
            });
        } catch (PrivilegedActionException ex) {
            Exception e = ex.getException();
            if (e instanceof IOException) {
                throw (IOException) e;
            } else {
                throw new IOException(e);
            }
        }
    } else {
        return new B2CConverter(charset);
    }

}
 
Example #15
Source File: RequestUtil.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Decode and return the specified URL-encoded byte array.
 *
 * @param bytes The url-encoded byte array
 * @param enc The encoding to use; if null, the default encoding is used. If
 * an unsupported encoding is specified null will be returned
 * @param isQuery Is this a query string being processed
 * @exception IllegalArgumentException if a '%' character is not followed
 * by a valid 2-digit hexadecimal number
 */
public static String URLDecode(byte[] bytes, String enc, boolean isQuery) {

    if (bytes == null)
        return null;

    int len = bytes.length;
    int ix = 0;
    int ox = 0;
    while (ix < len) {
        byte b = bytes[ix++];     // Get byte to test
        if (b == '+' && isQuery) {
            b = (byte)' ';
        } else if (b == '%') {
            if (ix + 2 > len) {
                throw new IllegalArgumentException(
                        sm.getString("requestUtil.urlDecode.missingDigit"));
            }
            b = (byte) ((convertHexDigit(bytes[ix++]) << 4)
                        + convertHexDigit(bytes[ix++]));
        }
        bytes[ox++] = b;
    }
    if (enc != null) {
        try {
            return new String(bytes, 0, ox, B2CConverter.getCharset(enc));
        } catch (UnsupportedEncodingException uee) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee);
            }
            return null;
        }
    }
    return new String(bytes, 0, ox);

}
 
Example #16
Source File: AccessLogValve.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Open the new log file for the date specified by <code>dateStamp</code>.
 */
protected synchronized void open() {
    // Open the current log file
    // If no rotate - no need for dateStamp in fileName
    File pathname = getLogFile(rotatable && !renameOnRotate);

    Charset charset = null;
    if (encoding != null) {
        try {
            charset = B2CConverter.getCharset(encoding);
        } catch (UnsupportedEncodingException ex) {
            log.error(sm.getString(
                    "accessLogValve.unsupportedEncoding", encoding), ex);
        }
    }
    if (charset == null) {
        charset = Charset.defaultCharset();
    }

    try {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(pathname, true), charset), 128000),
                false);

        currentLogFile = pathname;
    } catch (IOException e) {
        writer = null;
        currentLogFile = null;
        log.error(sm.getString("accessLogValve.openFail", pathname), e);
    }
}
 
Example #17
Source File: RealmBase.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
protected Charset getDigestCharset() throws UnsupportedEncodingException {
    if (digestEncoding == null) {
        return Charset.defaultCharset();
    } else {
        return B2CConverter.getCharset(getDigestEncoding());
    }
}
 
Example #18
Source File: AccessLogValve.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Open the new log file for the date specified by <code>dateStamp</code>.
 */
protected synchronized void open() {
    // Open the current log file
    // If no rotate - no need for dateStamp in fileName
    File pathname = getLogFile(rotatable && !renameOnRotate);

    Charset charset = null;
    if (encoding != null) {
        try {
            charset = B2CConverter.getCharset(encoding);
        } catch (UnsupportedEncodingException ex) {
            log.error(sm.getString(
                    "accessLogValve.unsupportedEncoding", encoding), ex);
        }
    }
    if (charset == null) {
        charset = Charset.defaultCharset();
    }

    try {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(pathname, true), charset), 128000),
                false);

        currentLogFile = pathname;
    } catch (IOException e) {
        writer = null;
        currentLogFile = null;
        log.error(sm.getString("accessLogValve.openFail", pathname), e);
    }
}
 
Example #19
Source File: RequestUtil.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Decode and return the specified URL-encoded byte array.
 *
 * @param bytes The url-encoded byte array
 * @param enc The encoding to use; if null, the default encoding is used. If
 * an unsupported encoding is specified null will be returned
 * @param isQuery Is this a query string being processed
 * @exception IllegalArgumentException if a '%' character is not followed
 * by a valid 2-digit hexadecimal number
 */
public static String URLDecode(byte[] bytes, String enc, boolean isQuery) {

    if (bytes == null)
        return null;

    int len = bytes.length;
    int ix = 0;
    int ox = 0;
    while (ix < len) {
        byte b = bytes[ix++];     // Get byte to test
        if (b == '+' && isQuery) {
            b = (byte)' ';
        } else if (b == '%') {
            if (ix + 2 > len) {
                throw new IllegalArgumentException(
                        sm.getString("requestUtil.urlDecode.missingDigit"));
            }
            b = (byte) ((convertHexDigit(bytes[ix++]) << 4)
                        + convertHexDigit(bytes[ix++]));
        }
        bytes[ox++] = b;
    }
    if (enc != null) {
        try {
            return new String(bytes, 0, ox, B2CConverter.getCharset(enc));
        } catch (UnsupportedEncodingException uee) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("requestUtil.urlDecode.uee", enc), uee);
            }
            return null;
        }
    }
    return new String(bytes, 0, ox);

}
 
Example #20
Source File: URLEncoder.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * URL encodes the provided path using the given encoding.
 *
 * @param path      The path to encode
 * @param encoding  The encoding to use to convert the path to bytes
 *
 * @return The encoded path
 *
 * @deprecated This will be removed in Tomcat 9.0.x
 */
@Deprecated
public String encode(String path, String encoding) {
    Charset charset;
    try {
        charset = B2CConverter.getCharset(encoding);
    } catch (UnsupportedEncodingException e) {
        charset = Charset.defaultCharset();
    }
    return encode(path, charset);
}
 
Example #21
Source File: Parameters.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private Charset getCharset(String encoding) {
    if (encoding == null) {
        return DEFAULT_CHARSET;
    }
    try {
        return B2CConverter.getCharset(encoding);
    } catch (UnsupportedEncodingException e) {
        return DEFAULT_CHARSET;
    }
}
 
Example #22
Source File: RealmBase.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
protected Charset getDigestCharset() throws UnsupportedEncodingException {
    if (digestEncoding == null) {
        return Charset.defaultCharset();
    } else {
        return B2CConverter.getCharset(getDigestEncoding());
    }
}
 
Example #23
Source File: Request.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Overrides the name of the character encoding used in the body of
 * this request.  This method must be called prior to reading request
 * parameters or reading input using <code>getReader()</code>.
 *
 * @param enc The character encoding to be used
 *
 * @exception UnsupportedEncodingException if the specified encoding
 *  is not supported
 *
 * @since Servlet 2.3
 */
@Override
public void setCharacterEncoding(String enc)
    throws UnsupportedEncodingException {

    if (usingReader) {
        return;
    }

    // Confirm that the encoding name is valid
    B2CConverter.getCharset(enc);

    // Save the validated encoding
    coyoteRequest.setCharacterEncoding(enc);
}
 
Example #24
Source File: DigestAuthenticator.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
public Principal authenticate(Realm realm) {
    // Second MD5 digest used to calculate the digest :
    // MD5(Method + ":" + uri)
    String a2 = method + ":" + uri;

    byte[] buffer = ConcurrentMessageDigest.digestMD5(
            a2.getBytes(B2CConverter.ISO_8859_1));
    String md5a2 = MD5Encoder.encode(buffer);

    return realm.authenticate(userName, response, nonce, nc, cnonce,
            qop, realmName, md5a2);
}
 
Example #25
Source File: TestSSOnonLoginAndBasicAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private BasicCredentials(String aMethod,
        String aUsername, String aPassword) {
    method = aMethod;
    username = aUsername;
    password = aPassword;
    String userCredentials = username + ":" + password;
    byte[] credentialsBytes =
            userCredentials.getBytes(B2CConverter.ISO_8859_1);
    String base64auth = Base64.encodeBase64String(credentialsBytes);
    credentials= method + " " + base64auth;
}
 
Example #26
Source File: TestNonLoginAndBasicAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private BasicCredentials(String aMethod,
        String aUsername, String aPassword) {
    method = aMethod;
    username = aUsername;
    password = aPassword;
    String userCredentials = username + ":" + password;
    byte[] credentialsBytes =
            userCredentials.getBytes(B2CConverter.ISO_8859_1);
    String base64auth = Base64.encodeBase64String(credentialsBytes);
    credentials= method + " " + base64auth;
}
 
Example #27
Source File: TestRestCsrfPreventionFilter2.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private void testValidPostWithRequestParams() throws Exception {
    String validBody = Constants.CSRF_REST_NONCE_HEADER_NAME + "=" + validNonce;
    String invalidbody = Constants.CSRF_REST_NONCE_HEADER_NAME + "=" + INVALID_NONCE_1;
    doTest(METHOD_POST, REMOVE_CUSTOMER, CREDENTIALS,
            validBody.getBytes(B2CConverter.ISO_8859_1), USE_COOKIES,
            HttpServletResponse.SC_OK, CUSTOMER_REMOVED_RESPONSE, null, false, null);
    doTest(METHOD_POST, ADD_CUSTOMER, CREDENTIALS,
            validBody.getBytes(B2CConverter.ISO_8859_1), USE_COOKIES,
            HttpServletResponse.SC_OK, CUSTOMER_ADDED_RESPONSE, null, false, null);
    doTest(METHOD_POST, REMOVE_CUSTOMER, CREDENTIALS,
            invalidbody.getBytes(B2CConverter.ISO_8859_1), USE_COOKIES,
            HttpServletResponse.SC_OK, CUSTOMER_REMOVED_RESPONSE, validNonce, false, null);
}
 
Example #28
Source File: DigestAuthenticator.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a unique token. The token is generated according to the
 * following pattern. NOnceToken = Base64 ( MD5 ( client-IP ":"
 * time-stamp ":" private-key ) ).
 *
 * @param request HTTP Servlet request
 */
protected String generateNonce(Request request) {

    long currentTime = System.currentTimeMillis();

    synchronized (lastTimestampLock) {
        if (currentTime > lastTimestamp) {
            lastTimestamp = currentTime;
        } else {
            currentTime = ++lastTimestamp;
        }
    }

    String ipTimeKey =
        request.getRemoteAddr() + ":" + currentTime + ":" + getKey();

    byte[] buffer = ConcurrentMessageDigest.digestMD5(
            ipTimeKey.getBytes(B2CConverter.ISO_8859_1));
    String nonce = currentTime + ":" + MD5Encoder.encode(buffer);

    NonceInfo info = new NonceInfo(currentTime, getNonceCountWindowSize());
    synchronized (nonces) {
        nonces.put(nonce, info);
    }

    return nonce;
}
 
Example #29
Source File: TesterParametersPerformance.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private long doCreateString(String input, int size,
        boolean defensiveCopyWorkAround) {
    int loops = 10000;
    byte[] inputBytes = input.getBytes();
    byte[] bytes = new byte[size];
    int inputLength = inputBytes.length;

    System.arraycopy(inputBytes, 0, bytes, 0, inputLength);

    String[] result = new String[loops];
    Charset charset = null;
    try {
        charset = B2CConverter.getCharset("ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    long start = System.nanoTime();
    for (int i = 0; i < loops; i++) {
        if (defensiveCopyWorkAround) {
            byte[] tmp = new byte[inputLength];
            System.arraycopy(bytes, 0, tmp, 0, inputLength);
            result[i] = new String(tmp, 0, inputLength, charset);
        } else {
            result[i] = new String(bytes, 0, inputLength, charset);
        }
    }

    return System.nanoTime() - start;
}
 
Example #30
Source File: Request.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Overrides the name of the character encoding used in the body of
 * this request.  This method must be called prior to reading request
 * parameters or reading input using <code>getReader()</code>.
 *
 * @param enc The character encoding to be used
 *
 * @exception UnsupportedEncodingException if the specified encoding
 *  is not supported
 *
 * @since Servlet 2.3
 */
@Override
public void setCharacterEncoding(String enc)
    throws UnsupportedEncodingException {

    if (usingReader) {
        return;
    }

    // Confirm that the encoding name is valid
    B2CConverter.getCharset(enc);

    // Save the validated encoding
    coyoteRequest.setCharacterEncoding(enc);
}