Search in sources :

Example 66 with IOException

use of java.io.IOException in project bazel by bazelbuild.

the class ErrorInfoTest method runTestFromException.

private void runTestFromException(boolean isDirectlyTransient, boolean isTransitivelyTransient) {
    Exception exception = new IOException("ehhhhh");
    SkyKey causeOfException = SkyKey.create(SkyFunctionName.create("CAUSE"), 1234);
    DummySkyFunctionException dummyException = new DummySkyFunctionException(exception, isDirectlyTransient, /*isCatastrophic=*/
    false);
    ErrorInfo errorInfo = ErrorInfo.fromException(new ReifiedSkyFunctionException(dummyException, causeOfException), isTransitivelyTransient);
    assertThat(errorInfo.getRootCauses()).containsExactly(causeOfException);
    assertThat(errorInfo.getException()).isSameAs(exception);
    assertThat(errorInfo.getRootCauseOfException()).isSameAs(causeOfException);
    assertThat(errorInfo.getCycleInfo()).isEmpty();
    assertThat(errorInfo.isTransient()).isEqualTo(isDirectlyTransient || isTransitivelyTransient);
    assertThat(errorInfo.isCatastrophic()).isFalse();
}
Also used : IOException(java.io.IOException) ReifiedSkyFunctionException(com.google.devtools.build.skyframe.SkyFunctionException.ReifiedSkyFunctionException) IOException(java.io.IOException) ReifiedSkyFunctionException(com.google.devtools.build.skyframe.SkyFunctionException.ReifiedSkyFunctionException)

Example 67 with IOException

use of java.io.IOException in project blade by biezhi.

the class BasicAuthenticator method validateRequest.

/* ------------------------------------------------------------ */
/**
     * @see org.eclipse.jetty.security.Authenticator#validateRequest(ServletRequest, ServletResponse, boolean)
     */
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString());
    try {
        if (!mandatory)
            return new DeferredAuthentication(this);
        if (credentials != null) {
            int space = credentials.indexOf(' ');
            if (space > 0) {
                String method = credentials.substring(0, space);
                if ("basic".equalsIgnoreCase(method)) {
                    credentials = credentials.substring(space + 1);
                    credentials = B64Code.decode(credentials, StandardCharsets.ISO_8859_1);
                    int i = credentials.indexOf(':');
                    if (i > 0) {
                        String username = credentials.substring(0, i);
                        String password = credentials.substring(i + 1);
                        UserIdentity user = login(username, password, request);
                        if (user != null) {
                            return new UserAuthentication(getAuthMethod(), user);
                        }
                    }
                }
            }
        }
        if (DeferredAuthentication.isDeferred(response))
            return Authentication.UNAUTHENTICATED;
        response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "basic realm=\"" + _loginService.getName() + '"');
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return Authentication.SEND_CONTINUE;
    } catch (IOException e) {
        throw new ServerAuthException(e);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) UserIdentity(org.eclipse.jetty.server.UserIdentity) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Constraint(org.eclipse.jetty.util.security.Constraint)

Example 68 with IOException

use of java.io.IOException in project blade by biezhi.

the class FormAuthenticator method validateRequest.

/* ------------------------------------------------------------ */
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    Request base_request = Request.getBaseRequest(request);
    Response base_response = base_request.getResponse();
    String uri = request.getRequestURI();
    if (uri == null)
        uri = URIUtil.SLASH;
    mandatory |= isJSecurityCheck(uri);
    if (!mandatory)
        return new DeferredAuthentication(this);
    if (isLoginOrErrorPage(URIUtil.addPaths(request.getServletPath(), request.getPathInfo())) && !DeferredAuthentication.isDeferred(response))
        return new DeferredAuthentication(this);
    HttpSession session = request.getSession(true);
    try {
        // Handle a request for authentication.
        if (isJSecurityCheck(uri)) {
            final String username = request.getParameter(__J_USERNAME);
            final String password = request.getParameter(__J_PASSWORD);
            UserIdentity user = login(username, password, request);
            LOG.debug("jsecuritycheck {} {}", username, user);
            session = request.getSession(true);
            if (user != null) {
                // Redirect to original request
                String nuri;
                FormAuthentication form_auth;
                synchronized (session) {
                    nuri = (String) session.getAttribute(__J_URI);
                    if (nuri == null || nuri.length() == 0) {
                        nuri = request.getContextPath();
                        if (nuri.length() == 0)
                            nuri = URIUtil.SLASH;
                    }
                    form_auth = new FormAuthentication(getAuthMethod(), user);
                }
                LOG.debug("authenticated {}->{}", form_auth, nuri);
                response.setContentLength(0);
                int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
                base_response.sendRedirect(redirectCode, response.encodeRedirectURL(nuri));
                return form_auth;
            }
            // not authenticated
            if (LOG.isDebugEnabled())
                LOG.debug("Form authentication FAILED for " + StringUtil.printable(username));
            if (_formErrorPage == null) {
                LOG.debug("auth failed {}->403", username);
                if (response != null)
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } else if (_dispatch) {
                LOG.debug("auth failed {}=={}", username, _formErrorPage);
                RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage);
                response.setHeader(HttpHeader.CACHE_CONTROL.asString(), HttpHeaderValue.NO_CACHE.asString());
                response.setDateHeader(HttpHeader.EXPIRES.asString(), 1);
                dispatcher.forward(new FormRequest(request), new FormResponse(response));
            } else {
                LOG.debug("auth failed {}->{}", username, _formErrorPage);
                int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
                base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formErrorPage)));
            }
            return Authentication.SEND_FAILURE;
        }
        // Look for cached authentication
        Authentication authentication = (Authentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
        if (authentication != null) {
            // Has authentication been revoked?
            if (authentication instanceof User && _loginService != null && !_loginService.validate(((User) authentication).getUserIdentity())) {
                LOG.debug("auth revoked {}", authentication);
                session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
            } else {
                synchronized (session) {
                    String j_uri = (String) session.getAttribute(__J_URI);
                    if (j_uri != null) {
                        //check if the request is for the same url as the original and restore
                        //params if it was a post
                        LOG.debug("auth retry {}->{}", authentication, j_uri);
                        StringBuffer buf = request.getRequestURL();
                        if (request.getQueryString() != null)
                            buf.append("?").append(request.getQueryString());
                        if (j_uri.equals(buf.toString())) {
                            MultiMap<String> j_post = (MultiMap<String>) session.getAttribute(__J_POST);
                            if (j_post != null) {
                                LOG.debug("auth rePOST {}->{}", authentication, j_uri);
                                base_request.setContentParameters(j_post);
                            }
                            session.removeAttribute(__J_URI);
                            session.removeAttribute(__J_METHOD);
                            session.removeAttribute(__J_POST);
                        }
                    }
                }
                LOG.debug("auth {}", authentication);
                return authentication;
            }
        }
        // if we can't send challenge
        if (DeferredAuthentication.isDeferred(response)) {
            LOG.debug("auth deferred {}", session.getId());
            return Authentication.UNAUTHENTICATED;
        }
        // remember the current URI
        synchronized (session) {
            // But only if it is not set already, or we save every uri that leads to a login form redirect
            if (session.getAttribute(__J_URI) == null || _alwaysSaveUri) {
                StringBuffer buf = request.getRequestURL();
                if (request.getQueryString() != null)
                    buf.append("?").append(request.getQueryString());
                session.setAttribute(__J_URI, buf.toString());
                session.setAttribute(__J_METHOD, request.getMethod());
                if (MimeTypes.Type.FORM_ENCODED.is(req.getContentType()) && HttpMethod.POST.is(request.getMethod())) {
                    MultiMap<String> formParameters = new MultiMap<>();
                    base_request.extractFormParameters(formParameters);
                    session.setAttribute(__J_POST, formParameters);
                }
            }
        }
        // send the the challenge
        if (_dispatch) {
            LOG.debug("challenge {}=={}", session.getId(), _formLoginPage);
            RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage);
            response.setHeader(HttpHeader.CACHE_CONTROL.asString(), HttpHeaderValue.NO_CACHE.asString());
            response.setDateHeader(HttpHeader.EXPIRES.asString(), 1);
            dispatcher.forward(new FormRequest(request), new FormResponse(response));
        } else {
            LOG.debug("challenge {}->{}", session.getId(), _formLoginPage);
            int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
            base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formLoginPage)));
        }
        return Authentication.SEND_CONTINUE;
    } catch (IOException | ServletException e) {
        throw new ServerAuthException(e);
    }
}
Also used : User(org.eclipse.jetty.server.Authentication.User) HttpSession(javax.servlet.http.HttpSession) UserIdentity(org.eclipse.jetty.server.UserIdentity) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) Constraint(org.eclipse.jetty.util.security.Constraint) RequestDispatcher(javax.servlet.RequestDispatcher) HttpServletRequest(javax.servlet.http.HttpServletRequest) Response(org.eclipse.jetty.server.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) ServletException(javax.servlet.ServletException) MultiMap(org.eclipse.jetty.util.MultiMap) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Authentication(org.eclipse.jetty.server.Authentication)

Example 69 with IOException

use of java.io.IOException in project blade by biezhi.

the class SelectorManager method chooseSelector.

private ManagedSelector chooseSelector(SelectableChannel channel) {
    // Ideally we would like to have all connections from the same client end
    // up on the same selector (to try to avoid smearing the data from a single
    // client over all cores), but because of proxies, the remote address may not
    // really be the client - so we have to hedge our bets to ensure that all
    // channels don't end up on the one selector for a proxy.
    ManagedSelector candidate1 = null;
    if (channel != null) {
        try {
            if (channel instanceof SocketChannel) {
                SocketAddress remote = ((SocketChannel) channel).getRemoteAddress();
                if (remote instanceof InetSocketAddress) {
                    byte[] addr = ((InetSocketAddress) remote).getAddress().getAddress();
                    if (addr != null) {
                        int s = addr[addr.length - 1] & 0xFF;
                        candidate1 = _selectors[s % getSelectorCount()];
                    }
                }
            }
        } catch (IOException x) {
            LOG.ignore(x);
        }
    }
    // The ++ increment here is not atomic, but it does not matter,
    // so long as the value changes sometimes, then connections will
    // be distributed over the available selectors.
    long s = _selectorIndex++;
    int index = (int) (s % getSelectorCount());
    ManagedSelector candidate2 = _selectors[index];
    if (candidate1 == null || candidate1.size() >= candidate2.size() * 2)
        return candidate2;
    return candidate1;
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 70 with IOException

use of java.io.IOException in project kata-tcg by bkimminich.

the class ConsoleInputStrategy method nextMove.

@Override
public Move nextMove(int availableMana, int currentHealth, List<Card> availableCards) {
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in, Charset.defaultCharset()));
        Integer card = -1;
        Action action = Action.DAMAGE;
        while (card < 0 || card > 8 || card > availableMana || !availableCards.contains(new Card(card))) {
            try {
                String input = br.readLine();
                if (input.endsWith("h")) {
                    action = Action.HEALING;
                    input = input.replace("h", "");
                }
                card = Integer.decode(input);
            } catch (NumberFormatException e) {
                logger.warning("Invalid input: " + e.getMessage());
            }
        }
        return new Move(Optional.of(new Card(card)), action);
    } catch (IOException e) {
        logger.severe("Could not read console input: " + e.getMessage());
        e.printStackTrace();
    }
    return new Move(Optional.empty(), null);
}
Also used : Action(de.kimminich.kata.tcg.Action) InputStreamReader(java.io.InputStreamReader) Move(de.kimminich.kata.tcg.Move) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) Card(de.kimminich.kata.tcg.Card)

Aggregations

IOException (java.io.IOException)46678 File (java.io.File)8666 InputStream (java.io.InputStream)4827 ArrayList (java.util.ArrayList)4154 Test (org.junit.Test)3912 FileInputStream (java.io.FileInputStream)3019 FileOutputStream (java.io.FileOutputStream)2620 HashMap (java.util.HashMap)2492 FileNotFoundException (java.io.FileNotFoundException)2376 BufferedReader (java.io.BufferedReader)2351 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1970 InputStreamReader (java.io.InputStreamReader)1957 URL (java.net.URL)1923 ByteArrayInputStream (java.io.ByteArrayInputStream)1775 OutputStream (java.io.OutputStream)1543 Path (org.apache.hadoop.fs.Path)1460 Map (java.util.Map)1384 List (java.util.List)1255 Properties (java.util.Properties)1125 ServletException (javax.servlet.ServletException)996