Search in sources :

Example 91 with CharacterCodingException

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

the class AuthenticationFilter method doFilterInternal.

protected void doFilterInternal(ServletContext context, ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
    if (logger.isTraceEnabled()) {
        logger.trace("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);
                    if (logger.isTraceEnabled()) {
                        logger.trace("Successfully created user environment, login using basic auth or ROLE_TICKET for user: " + AuthenticationUtil.maskUsername(user.getUserName()));
                    }
                    // 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.isTraceEnabled()) {
                    logger.trace("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 (logger.isTraceEnabled()) {
                    logger.trace("Successfully created user environment, login using TICKET for user: " + AuthenticationUtil.maskUsername(user.getUserName()));
                }
            }
        }
        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()));
        }
        if (logger.isTraceEnabled()) {
            logger.trace("User already set to: " + AuthenticationUtil.maskUsername(user.getUserName()));
        }
    }
    // 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 92 with CharacterCodingException

use of java.nio.charset.CharacterCodingException in project aion by aionnetwork.

the class Slices method decodeString.

public static String decodeString(ByteBuffer src, Charset charset) {
    CharsetDecoder decoder = getDecoder(charset);
    CharBuffer dst = CharBuffer.allocate((int) ((double) src.remaining() * decoder.maxCharsPerByte()));
    try {
        CoderResult cr = decoder.decode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = decoder.flush(dst);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
    return dst.flip().toString();
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) CharBuffer(java.nio.CharBuffer) CharacterCodingException(java.nio.charset.CharacterCodingException) CoderResult(java.nio.charset.CoderResult)

Example 93 with CharacterCodingException

use of java.nio.charset.CharacterCodingException in project qpid-broker-j by apache.

the class TypedBytesContentReader method readLengthPrefixedUTF.

public String readLengthPrefixedUTF() throws TypedBytesFormatException {
    try {
        short length = readShortImpl();
        if (length == 0) {
            return "";
        } else {
            _charsetDecoder.reset();
            ByteBuffer encodedString = _data.slice();
            encodedString.limit(length);
            _data.position(_data.position() + length);
            CharBuffer string = _charsetDecoder.decode(encodedString);
            return string.toString();
        }
    } catch (CharacterCodingException e) {
        TypedBytesFormatException jmse = new TypedBytesFormatException("Error decoding byte stream as a UTF8 string: " + e);
        jmse.initCause(e);
        throw jmse;
    }
}
Also used : CharBuffer(java.nio.CharBuffer) CharacterCodingException(java.nio.charset.CharacterCodingException) ByteBuffer(java.nio.ByteBuffer)

Example 94 with CharacterCodingException

use of java.nio.charset.CharacterCodingException in project erlide_eclipse by erlang.

the class IndexedErlangValue method getBinaryValueString.

private static String getBinaryValueString(final OtpErlangBinary b) {
    final StringBuilder sb = new StringBuilder("<<");
    if (b.size() > 0) {
        final byte[] bytes = b.binaryValue();
        CharBuffer cb = null;
        if (IndexedErlangValue.looksLikeAscii(bytes)) {
            final Charset[] css = { Charsets.UTF_8, Charsets.ISO_8859_1 };
            final Charset[] tryCharsets = css;
            for (final Charset cset : tryCharsets) {
                final CharsetDecoder cd = cset.newDecoder();
                cd.onMalformedInput(CodingErrorAction.REPORT);
                cd.onUnmappableCharacter(CodingErrorAction.REPORT);
                try {
                    cb = cd.decode(ByteBuffer.wrap(bytes));
                    break;
                } catch (final CharacterCodingException e) {
                }
            }
        }
        if (cb != null && cb.length() > 0) {
            sb.append('"').append(cb).append('"');
        } else {
            for (int i = 0, n = bytes.length; i < n; ++i) {
                int j = bytes[i];
                if (j < 0) {
                    j += 256;
                }
                sb.append(j);
                if (i < n - 1) {
                    sb.append(',');
                }
            }
        }
    }
    sb.append(">>");
    return sb.toString();
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) CharBuffer(java.nio.CharBuffer) Charset(java.nio.charset.Charset) CharacterCodingException(java.nio.charset.CharacterCodingException)

Example 95 with CharacterCodingException

use of java.nio.charset.CharacterCodingException in project erlide_eclipse by erlang.

the class Util method decode.

public static String decode(final byte[] binaryValue, final Charset charset) {
    final CharsetDecoder decoder = charset.newDecoder();
    try {
        final ByteBuffer bbuf = ByteBuffer.wrap(binaryValue);
        final CharBuffer cbuf = decoder.decode(bbuf);
        return cbuf.toString();
    } catch (final CharacterCodingException e) {
        return null;
    }
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) CharBuffer(java.nio.CharBuffer) CharacterCodingException(java.nio.charset.CharacterCodingException) ByteBuffer(java.nio.ByteBuffer)

Aggregations

CharacterCodingException (java.nio.charset.CharacterCodingException)197 ByteBuffer (java.nio.ByteBuffer)115 CharBuffer (java.nio.CharBuffer)48 CharsetDecoder (java.nio.charset.CharsetDecoder)44 IOException (java.io.IOException)34 CharsetEncoder (java.nio.charset.CharsetEncoder)31 CoderResult (java.nio.charset.CoderResult)30 Charset (java.nio.charset.Charset)27 InputStream (java.io.InputStream)9 Date (java.util.Date)9 UnmappableCharacterException (java.nio.charset.UnmappableCharacterException)8 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)8 ByteArrayInputStream (java.io.ByteArrayInputStream)6 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)6 Path (java.nio.file.Path)6 ParseException (java.text.ParseException)6 Test (org.junit.Test)6 CoreException (org.eclipse.core.runtime.CoreException)5 HumanReadableException (com.facebook.buck.util.HumanReadableException)4 OutputStream (java.io.OutputStream)4