Search in sources :

Example 91 with CharsetDecoder

use of java.nio.charset.CharsetDecoder in project robovm by robovm.

the class CharsetDecoderTest method testCharsetDecoder.

/*
     * test constructor
     */
public void testCharsetDecoder() {
    // default value
    decoder = new MockCharsetDecoder(cs, (float) AVER_BYTES, MAX_BYTES);
    // normal case
    CharsetDecoder ec = new MockCharsetDecoder(cs, 1, MAX_BYTES);
    assertSame(ec.charset(), cs);
    assertEquals(1.0, ec.averageCharsPerByte(), 0.0);
    assertTrue(ec.maxCharsPerByte() == MAX_BYTES);
    /*
         * ------------------------ Exceptional cases -------------------------
         */
    // Normal case: null charset
    ec = new MockCharsetDecoder(null, 1, MAX_BYTES);
    assertNull(ec.charset());
    assertEquals(1.0, ec.averageCharsPerByte(), 0.0);
    assertTrue(ec.maxCharsPerByte() == MAX_BYTES);
    ec = new MockCharsetDecoder(new CharsetEncoderTest.MockCharset("mock", new String[0]), 1, MAX_BYTES);
    // Illegal Argument: zero length
    try {
        ec = new MockCharsetDecoder(cs, 0, MAX_BYTES);
        fail("should throw IllegalArgumentException");
    } catch (IllegalArgumentException e) {
    }
    try {
        ec = new MockCharsetDecoder(cs, 1, 0);
        fail("should throw IllegalArgumentException");
    } catch (IllegalArgumentException e) {
    }
    // Illegal Argument: negative length
    try {
        ec = new MockCharsetDecoder(cs, -1, MAX_BYTES);
        fail("should throw IllegalArgumentException");
    } catch (IllegalArgumentException e) {
    }
    try {
        ec = new MockCharsetDecoder(cs, 1, -1);
        fail("should throw IllegalArgumentException");
    } catch (IllegalArgumentException e) {
    }
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder)

Example 92 with CharsetDecoder

use of java.nio.charset.CharsetDecoder in project robovm by robovm.

the class CharsetDecoderTest method test_ByteArray_decode_with_offset_using_facade_method.

// http://code.google.com/p/android/issues/detail?id=4237
public void test_ByteArray_decode_with_offset_using_facade_method() throws Exception {
    CharsetDecoder decoder = Charset.forName("UTF-16").newDecoder();
    byte[] arr = encode("UTF-16", "Android");
    arr = prependByteToByteArray(arr, new Integer(1).byteValue());
    int offset = 1;
    CharBuffer outBuffer = decoder.decode(ByteBuffer.wrap(arr, offset, arr.length - offset));
    assertEquals("Android", outBuffer.toString().trim());
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) CharBuffer(java.nio.CharBuffer)

Example 93 with CharsetDecoder

use of java.nio.charset.CharsetDecoder in project robovm by robovm.

the class CharsetDecoderTest method test_ByteArray_decode_with_offset.

// http://code.google.com/p/android/issues/detail?id=4237
public void test_ByteArray_decode_with_offset() throws Exception {
    CharsetDecoder decoder = Charset.forName("UTF-16").newDecoder();
    byte[] arr = encode("UTF-16", "Android");
    arr = prependByteToByteArray(arr, new Integer(1).byteValue());
    int offset = 1;
    ByteBuffer inBuffer = ByteBuffer.wrap(arr, offset, arr.length - offset).slice();
    CharBuffer outBuffer = CharBuffer.allocate(arr.length - offset);
    decoder.reset();
    CoderResult coderResult = decoder.decode(inBuffer, outBuffer, true);
    assertFalse(coderResult.toString(), coderResult.isError());
    decoder.flush(outBuffer);
    outBuffer.flip();
    assertEquals("Android", outBuffer.toString().trim());
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) CharBuffer(java.nio.CharBuffer) ByteBuffer(java.nio.ByteBuffer) CoderResult(java.nio.charset.CoderResult)

Example 94 with CharsetDecoder

use of java.nio.charset.CharsetDecoder in project alfresco-remote-api by Alfresco.

the class AuthenticationFilter method doFilter.

// Various services required by NTLM authenticator
/**
 * Run the authentication filter
 *
 * @param context ServletContext
 * @param req ServletRequest
 * @param resp ServletResponse
 * @param chain FilterChain
 * @exception ServletException
 * @exception IOException
 */
@Override
public void doFilter(ServletContext context, ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
    if (logger.isDebugEnabled())
        logger.debug("Entering AuthenticationFilter.");
    // Assume it's an HTTP request
    HttpServletRequest httpReq = (HttpServletRequest) req;
    HttpServletResponse httpResp = (HttpServletResponse) resp;
    // Get the user details object from the session
    SessionUser user = getSessionUser(context, httpReq, httpResp, false);
    if (user == null) {
        if (logger.isDebugEnabled())
            logger.debug("There is no user in the session.");
        // Get the authorization header
        String authHdr = httpReq.getHeader("Authorization");
        if (authHdr != null && authHdr.length() > 5 && authHdr.substring(0, 5).equalsIgnoreCase("BASIC")) {
            if (logger.isDebugEnabled())
                logger.debug("Basic authentication details present in the header.");
            byte[] encodedString = Base64.decodeBase64(authHdr.substring(5).getBytes());
            // ALF-13621: Due to browser inconsistencies we have to try a fallback path of encodings
            Set<String> attemptedAuths = new HashSet<String>(ENCODINGS.length * 2);
            for (String encoding : ENCODINGS) {
                CharsetDecoder decoder = Charset.forName(encoding).newDecoder().onMalformedInput(CodingErrorAction.REPORT);
                try {
                    // Attempt to decode using this charset
                    String basicAuth = decoder.decode(ByteBuffer.wrap(encodedString)).toString();
                    // It decoded OK but we may already have tried this string.
                    if (!attemptedAuths.add(basicAuth)) {
                        // Already tried - no need to try again
                        continue;
                    }
                    String username = null;
                    String password = null;
                    // Split the username and password
                    int pos = basicAuth.indexOf(":");
                    if (pos != -1) {
                        username = basicAuth.substring(0, pos);
                        password = basicAuth.substring(pos + 1);
                    } else {
                        username = basicAuth;
                        password = "";
                    }
                    // Go to the repo and authenticate
                    Authorization auth = new Authorization(username, password);
                    if (auth.isTicket()) {
                        authenticationService.validate(auth.getTicket());
                    } else {
                        authenticationService.authenticate(username, password.toCharArray());
                        if (authenticationListener != null) {
                            authenticationListener.userAuthenticated(new BasicAuthCredentials(username, password));
                        }
                    }
                    user = createUserEnvironment(httpReq.getSession(), authenticationService.getCurrentUserName(), authenticationService.getCurrentTicket(), false);
                    // Success so break out
                    break;
                } catch (CharacterCodingException e) {
                    if (logger.isDebugEnabled())
                        logger.debug("Didn't decode using " + decoder.getClass().getName(), e);
                } catch (AuthenticationException ex) {
                    if (logger.isDebugEnabled())
                        logger.debug("Authentication error ", ex);
                } catch (NoSuchPersonException e) {
                    if (logger.isDebugEnabled())
                        logger.debug("There is no such person error ", e);
                }
            }
        } else {
            // Check if the request includes an authentication ticket
            String ticket = req.getParameter(ARG_TICKET);
            if (ticket != null && ticket.length() > 0) {
                // PowerPoint bug fix
                if (ticket.endsWith(PPT_EXTN)) {
                    ticket = ticket.substring(0, ticket.length() - PPT_EXTN.length());
                }
                if (logger.isDebugEnabled())
                    logger.debug("Logon via ticket from " + req.getRemoteHost() + " (" + req.getRemoteAddr() + ":" + req.getRemotePort() + ")" + " ticket=" + ticket);
                // Validate the ticket
                authenticationService.validate(ticket);
                if (authenticationListener != null) {
                    authenticationListener.userAuthenticated(new TicketCredentials(ticket));
                }
                // Need to create the User instance if not already available
                String currentUsername = authenticationService.getCurrentUserName();
                user = createUserEnvironment(httpReq.getSession(), currentUsername, ticket, false);
            }
        }
        if (user == null) {
            if (logger.isDebugEnabled())
                logger.debug("No user/ticket, force the client to prompt for logon details.");
            httpResp.setHeader("WWW-Authenticate", "BASIC realm=\"Alfresco DAV Server\"");
            httpResp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpResp.flushBuffer();
            return;
        }
    } else {
        if (authenticationListener != null) {
            authenticationListener.userAuthenticated(new TicketCredentials(user.getTicket()));
        }
    }
    // Chain other filters
    chain.doFilter(req, resp);
}
Also used : TicketCredentials(org.alfresco.repo.web.auth.TicketCredentials) CharsetDecoder(java.nio.charset.CharsetDecoder) BasicAuthCredentials(org.alfresco.repo.web.auth.BasicAuthCredentials) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) NoSuchPersonException(org.alfresco.service.cmr.security.NoSuchPersonException) HttpServletResponse(javax.servlet.http.HttpServletResponse) CharacterCodingException(java.nio.charset.CharacterCodingException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Authorization(org.alfresco.repo.security.authentication.Authorization) SessionUser(org.alfresco.repo.SessionUser) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 95 with CharsetDecoder

use of java.nio.charset.CharsetDecoder in project felix by apache.

the class UriUtils method decodePath.

/**
 * Decodes a given URL-encoded path using a given character encoding.
 *
 * @param path the URL-encoded path, can be <code>null</code>;
 * @param encoding the character encoding to use, cannot be <code>null</code>.
 * @return the decoded path, can be <code>null</code> only if the given path was <code>null</code>.
 */
private static String decodePath(String path, String encoding) {
    // Special cases...
    if (path == null) {
        return null;
    }
    CharsetDecoder decoder = Charset.forName(encoding).newDecoder();
    decoder.onMalformedInput(CodingErrorAction.REPORT);
    decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
    int len = path.length();
    ByteBuffer buf = ByteBuffer.allocate(len);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < len; i++) {
        char ch = path.charAt(i);
        if (ch == '%' && (i + 2 < len)) {
            // URL-encoded char...
            buf.put((byte) ((16 * hexVal(path, ++i)) + hexVal(path, ++i)));
        } else {
            if (buf.position() > 0) {
                // flush encoded chars first...
                sb.append(decode(buf, decoder));
                buf.clear();
            }
            sb.append(ch);
        }
    }
    // flush trailing encoded characters...
    if (buf.position() > 0) {
        sb.append(decode(buf, decoder));
        buf.clear();
    }
    return sb.toString();
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) ByteBuffer(java.nio.ByteBuffer)

Aggregations

CharsetDecoder (java.nio.charset.CharsetDecoder)381 CharBuffer (java.nio.CharBuffer)187 ByteBuffer (java.nio.ByteBuffer)167 Charset (java.nio.charset.Charset)99 CharacterCodingException (java.nio.charset.CharacterCodingException)95 CoderResult (java.nio.charset.CoderResult)82 IOException (java.io.IOException)45 InputStreamReader (java.io.InputStreamReader)43 BufferedReader (java.io.BufferedReader)26 Reader (java.io.Reader)25 CharsetEncoder (java.nio.charset.CharsetEncoder)23 FileInputStream (java.io.FileInputStream)18 Test (org.junit.Test)18 FileChannel (java.nio.channels.FileChannel)13 ArrayDecoder (sun.nio.cs.ArrayDecoder)12 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)11 InputStream (java.io.InputStream)10 Buffer (java.nio.Buffer)10 File (java.io.File)9 MalformedInputException (java.nio.charset.MalformedInputException)9