Java Code Examples for io.undertow.server.handlers.form.FormData#FormValue

The following examples show how to use io.undertow.server.handlers.form.FormData#FormValue . 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: HttpServletRequestImpl.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public Enumeration<String> getParameterNames() {
    if (queryParameters == null) {
        queryParameters = exchange.getQueryParameters();
    }
    final Set<String> parameterNames = new HashSet<>(queryParameters.keySet());
    if (exchange.getRequestMethod().equals(HttpMethodNames.POST)) {
        final FormData parsedFormData = parseFormData();
        if (parsedFormData != null) {
            Iterator<String> it = parsedFormData.iterator();
            while (it.hasNext()) {
                String name = it.next();
                for (FormData.FormValue param : parsedFormData.get(name)) {
                    if (!param.isFileItem()) {
                        parameterNames.add(name);
                        break;
                    }
                }
            }
        }
    }
    return new IteratorEnumeration<>(parameterNames.iterator());
}
 
Example 2
Source File: HttpServletRequestImpl.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public String getParameter(final String name) {
    if (queryParameters == null) {
        queryParameters = exchange.getQueryParameters();
    }
    Deque<String> params = queryParameters.get(name);
    if (params == null) {
        final FormData parsedFormData = parseFormData();
        if (parsedFormData != null) {
            FormData.FormValue res = parsedFormData.getFirst(name);
            if (res == null || res.isFileItem()) {
                return null;
            } else {
                return res.getValue();
            }
        }
        return null;
    }
    return params.getFirst();
}
 
Example 3
Source File: RequestParser.java    From core-ng-project with Apache License 2.0 6 votes vote down vote up
private void parseForm(RequestImpl request, HttpServerExchange exchange) throws IOException {
    FormData formData = exchange.getAttachment(FormDataParser.FORM_DATA);
    if (formData == null) return;

    for (String name : formData) {
        FormData.FormValue value = formData.getFirst(name);
        if (value.isFileItem()) {
            String fileName = value.getFileName();
            if (!Strings.isBlank(fileName)) {    // browser passes blank file name if not choose file in form
                FormData.FileItem item = value.getFileItem();
                logger.debug("[request:file] {}={}, size={}", name, fileName, item.getFileSize());
                request.files.put(name, new MultipartFile(item.getFile(), fileName, value.getHeaders().getFirst(Headers.CONTENT_TYPE)));
            }
        } else {
            logger.debug("[request:form] {}={}", name, new FieldLogParam(name, value.getValue()));
            request.formParams.put(name, value.getValue());
        }
    }
}
 
Example 4
Source File: HttpServletRequestImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String getParameter(final String name) {
    if(queryParameters == null) {
        queryParameters = exchange.getQueryParameters();
    }
    Deque<String> params = queryParameters.get(name);
    if (params == null) {
        final FormData parsedFormData = parseFormData();
        if (parsedFormData != null) {
            FormData.FormValue res = parsedFormData.getFirst(name);
            if (res == null || res.isFile()) {
                return null;
            } else {
                return res.getValue();
            }
        }
        return null;
    }
    return params.getFirst();
}
 
Example 5
Source File: HttpServletRequestImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Enumeration<String> getParameterNames() {
    if (queryParameters == null) {
        queryParameters = exchange.getQueryParameters();
    }
    final Set<String> parameterNames = new HashSet<>(queryParameters.keySet());
    if (exchange.getRequestMethod().equals(Methods.POST)) {
        final FormData parsedFormData = parseFormData();
        if (parsedFormData != null) {
            Iterator<String> it = parsedFormData.iterator();
            while (it.hasNext()) {
                String name = it.next();
                for(FormData.FormValue param : parsedFormData.get(name)) {
                    if(!param.isFile()) {
                        parameterNames.add(name);
                        break;
                    }
                }
            }
        }
    }
    return new IteratorEnumeration<>(parameterNames.iterator());
}
 
Example 6
Source File: DomainApiGenericOperationHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private InputStream convertToStream(FormData.FormValue op) throws IOException {
    if (op.isFile()) {
        return Files.newInputStream(op.getPath());
    } else {
        return new ByteArrayInputStream(op.getValue().getBytes(StandardCharsets.UTF_8));
    }
}
 
Example 7
Source File: BasicHttpHandler.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
protected String getOrThrow(FormData data, String key) {
    FormData.FormValue value = data.getFirst(key);
    if (Objects.isNull(value)) {
        throw new IllegalArgumentException("Form key " + key + " is missing");
    }

    String object = value.getValue();
    if (Objects.isNull(object)) {
        throw new IllegalArgumentException("Form key " + key + " does not have a value");
    }

    return object;
}
 
Example 8
Source File: MCMPHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
void add(final HttpString name, final FormData.FormValue value) {
    Deque<String> values = this.values.get(name);
    if (values == null) {
        this.values.put(name, values = new ArrayDeque<>(1));
    }
    String stringVal = value.getValue();
    checkStringForSuspiciousCharacters(stringVal);
    values.add(stringVal);
}
 
Example 9
Source File: RequestDumpingHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void dumpRequestBody(HttpServerExchange exchange, StringBuilder sb) {
    try {
        FormData formData = exchange.getAttachment(FormDataParser.FORM_DATA);
        if (formData != null) {
            sb.append("body=\n");

            for (String formField : formData) {
                Deque<FormData.FormValue> formValues = formData.get(formField);

                sb.append(formField)
                        .append("=");
                for (FormData.FormValue formValue : formValues) {
                    sb.append(formValue.isFile() ? "[file-content]" : formValue.getValue());
                    sb.append("\n");

                    if (formValue.getHeaders() != null) {
                        sb.append("headers=\n");
                        for (HeaderValues header : formValue.getHeaders()) {
                            sb.append("\t")
                                    .append(header.getHeaderName()).append("=").append(header.getFirst()).append("\n");

                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
Source File: PartImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public PartImpl(final String name, final FormData.FormValue formValue, MultipartConfigElement config,
                ServletContextImpl servletContext, HttpServletRequestImpl servletRequest) {
    this.name = name;
    this.formValue = formValue;
    this.config = config;
    this.servletContext = servletContext;
    this.servletRequest = servletRequest;

}
 
Example 11
Source File: HttpServletRequestImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String[] getParameterValues(final String name) {
    if (queryParameters == null) {
        queryParameters = exchange.getQueryParameters();
    }
    final List<String> ret = new ArrayList<>();
    Deque<String> params = queryParameters.get(name);
    if (params != null) {
        for (String param : params) {
            ret.add(param);
        }
    }
    if (exchange.getRequestMethod().equals(Methods.POST)) {
        final FormData parsedFormData = parseFormData();
        if (parsedFormData != null) {
            Deque<FormData.FormValue> res = parsedFormData.get(name);
            if (res != null) {
                for (FormData.FormValue value : res) {
                    if(!value.isFile()) {
                        ret.add(value.getValue());
                    }
                }
            }
        }
    }
    if (ret.isEmpty()) {
        return null;
    }
    return ret.toArray(new String[ret.size()]);
}
 
Example 12
Source File: ServerRequest.java    From proteus with Apache License 2.0 5 votes vote down vote up
public Deque<FormData.FormValue> files(final String name)
{
    if (this.form != null) {
        return form.get(name);
    }

    return null;
}
 
Example 13
Source File: ServerRequest.java    From proteus with Apache License 2.0 5 votes vote down vote up
private void extractFormParameters(final FormData formData)
{
    if (formData != null) {
        for (String key : formData) {
            final Deque<FormData.FormValue> formValues = formData.get(key);
            final Deque<String> values = formValues.stream()
                    .filter(fv -> !fv.isFileItem())
                    .map(FormData.FormValue::getValue)
                    .collect(java.util.stream.Collectors.toCollection(FastConcurrentDirectDeque::new));

            exchange.getQueryParameters().put(key, values);
        }
    }
}
 
Example 14
Source File: PartImpl.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public PartImpl(final String name, final FormData.FormValue formValue, MultipartConfigElement config,
                ServletContextImpl servletContext, HttpServletRequestImpl servletRequest) {
    this.name = name;
    this.formValue = formValue;
    this.config = config;
    this.servletContext = servletContext;
    this.servletRequest = servletRequest;

}
 
Example 15
Source File: HttpServletRequestImpl.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public String[] getParameterValues(final String name) {
    if (queryParameters == null) {
        queryParameters = exchange.getQueryParameters();
    }
    final List<String> ret = new ArrayList<>();
    Deque<String> params = queryParameters.get(name);
    if (params != null) {
        for (String param : params) {
            ret.add(param);
        }
    }
    if (exchange.getRequestMethod().equals(HttpMethodNames.POST)) {
        final FormData parsedFormData = parseFormData();
        if (parsedFormData != null) {
            Deque<FormData.FormValue> res = parsedFormData.get(name);
            if (res != null) {
                for (FormData.FormValue value : res) {
                    if (!value.isFileItem()) {
                        ret.add(value.getValue());
                    }
                }
            }
        }
    }
    if (ret.isEmpty()) {
        return null;
    }
    return ret.toArray(new String[ret.size()]);
}
 
Example 16
Source File: FormAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public AuthenticationMechanismOutcome runFormAuth(final HttpServerExchange exchange, final SecurityContext securityContext) {
    final FormDataParser parser = formParserFactory.createParser(exchange);
    if (parser == null) {
        UndertowLogger.SECURITY_LOGGER.debug("Could not authenticate as no form parser is present");
        // TODO - May need a better error signaling mechanism here to prevent repeated attempts.
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }

    try {
        final FormData data = parser.parseBlocking();
        final FormData.FormValue jUsername = data.getFirst("j_username");
        final FormData.FormValue jPassword = data.getFirst("j_password");
        if (jUsername == null || jPassword == null) {
            UndertowLogger.SECURITY_LOGGER.debugf("Could not authenticate as username or password was not present in the posted result for %s", exchange);
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
        final String userName = jUsername.getValue();
        final String password = jPassword.getValue();
        AuthenticationMechanismOutcome outcome = null;
        PasswordCredential credential = new PasswordCredential(password.toCharArray());
        try {
            IdentityManager identityManager = getIdentityManager(securityContext);
            Account account = identityManager.verify(userName, credential);
            if (account != null) {
                securityContext.authenticationComplete(account, name, true);
                UndertowLogger.SECURITY_LOGGER.debugf("Authenticated user %s using for auth for %s", account.getPrincipal().getName(), exchange);
                outcome = AuthenticationMechanismOutcome.AUTHENTICATED;
            } else {
                securityContext.authenticationFailed(MESSAGES.authenticationFailed(userName), name);
            }
        } finally {
            if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) {
                handleRedirectBack(exchange);
                exchange.endExchange();
            }
            return outcome != null ? outcome : AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 17
Source File: MCMPHandler.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
void add(final HttpString name, Deque<FormData.FormValue> values) {
    checkStringForSuspiciousCharacters(name.toString());
    for (final FormData.FormValue value : values) {
        add(name, value);
    }
}
 
Example 18
Source File: FormAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
public AuthenticationMechanismOutcome runFormAuth(final HttpServerExchange exchange, final SecurityContext securityContext) {
    final FormDataParser parser = formParserFactory.createParser(exchange);
    if (parser == null) {
        UndertowLogger.SECURITY_LOGGER.debug("Could not authenticate as no form parser is present");
        // TODO - May need a better error signaling mechanism here to prevent repeated attempts.
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }

    try {
        final FormData data = parser.parseBlocking();
        if (data == null) {
            UndertowLogger.SECURITY_LOGGER.debug("Could not authenticate as no form parser is present");
            // TODO - May need a better error signaling mechanism here to prevent repeated attempts.
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }

        final FormData.FormValue jUsername = data.getFirst("j_username");
        final FormData.FormValue jPassword = data.getFirst("j_password");
        if (jUsername == null || jPassword == null) {
            UndertowLogger.SECURITY_LOGGER.debugf("Could not authenticate as username or password was not present in the posted result for %s", exchange);
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
        final String userName = jUsername.getValue();
        final String password = jPassword.getValue();
        AuthenticationMechanismOutcome outcome = null;
        PasswordCredential credential = new PasswordCredential(password.toCharArray());
        try {
            IdentityManager identityManager = getIdentityManager(securityContext);
            Account account = identityManager.verify(userName, credential);
            if (account != null) {
                securityContext.authenticationComplete(account, name, true);
                UndertowLogger.SECURITY_LOGGER.debugf("Authenticated user %s using for auth for %s", account.getPrincipal().getName(), exchange);
                outcome = AuthenticationMechanismOutcome.AUTHENTICATED;
            } else {
                securityContext.authenticationFailed(MESSAGES.authenticationFailed(userName), name);
            }
        } finally {
            if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) {
                handleRedirectBack(exchange);
                exchange.endExchange();
            }
            return outcome != null ? outcome : AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 19
Source File: LightFormAuthenticationMechanism.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
public AuthenticationMechanismOutcome runFormAuth(final HttpServerExchange exchange, final SecurityContext securityContext) {
        final FormDataParser parser = formParserFactory.createParser(exchange);
        if (parser == null) {
            UndertowLogger.SECURITY_LOGGER.debug("Could not authenticate as no form parser is present");
            // TODO - May need a better error signaling mechanism here to prevent repeated attempts.
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }

        try {
            final FormData data = parser.parseBlocking();
            final FormData.FormValue jUsername = data.getFirst("j_username");
            final FormData.FormValue jPassword = data.getFirst("j_password");
            final FormData.FormValue jClientId = data.getFirst("client_id");
            final FormData.FormValue jUserType = data.getFirst("user_type");
            if (jUsername == null || jPassword == null) {
                UndertowLogger.SECURITY_LOGGER.debugf("Could not authenticate as username or password was not present in the posted result for %s", exchange);
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
            final String userName = jUsername.getValue();
            final String password = jPassword.getValue();
            final String userType = jUserType.getValue();
            final String clientId = jClientId.getValue();

            // get clientAuthClass and userType
            String clientAuthClass = null;
            IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
            Client client = clients.get(clientId);
            if(client != null) {
                clientAuthClass = client.getAuthenticateClass();
            }

            AuthenticationMechanismOutcome outcome = null;
            LightPasswordCredential credential = new LightPasswordCredential(password.toCharArray(), clientAuthClass, userType, exchange);
            try {
                IdentityManager identityManager = getIdentityManager(securityContext);
                Account account = identityManager.verify(userName, credential);
                if (account != null) {
                    securityContext.authenticationComplete(account, name, true);
                    UndertowLogger.SECURITY_LOGGER.debugf("Authenticated user %s using for auth for %s", account.getPrincipal().getName(), exchange);
                    outcome = AuthenticationMechanismOutcome.AUTHENTICATED;
                } else {
                    securityContext.authenticationFailed(MESSAGES.authenticationFailed(userName), name);
                }
            } finally {
//                if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) {
//                    handleRedirectBack(exchange);
//                    exchange.endExchange();
//                }
                return outcome != null ? outcome : AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 
Example 20
Source File: Oauth2CodePostHandler.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");

    // get the form from the exchange
    final FormData data = exchange.getAttachment(FormDataParser.FORM_DATA);

    final FormData.FormValue jClientId = data.getFirst("client_id");
    final FormData.FormValue jRedirectUri = data.getFirst("redirect_uri");
    final FormData.FormValue jState = data.getFirst("state");
    final FormData.FormValue jRemember = data.getFirst("remember");
    final String clientId = jClientId.getValue();
    final String remember = jRemember == null ? null : jRemember.getValue();  // should be 'Y' or 'N' if not null.
    String redirectUri = jRedirectUri == null ? null : jRedirectUri.getValue();
    final String state = jState == null ? null : jState.getValue();
    if(logger.isDebugEnabled()) {
        logger.debug("client_id = " + clientId + " state = " + state + " redirectUri = " + redirectUri + " remember = " + remember);
    }
    // check if the client_id is valid
    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    Client client = clients.get(clientId);
    if(client == null) {
        if(logger.isDebugEnabled()) logger.debug("client is not found for clientId = " + clientId);
        setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId);
        processAudit(exchange);
    } else {
        final SecurityContext context = exchange.getSecurityContext();
        String userId = context.getAuthenticatedAccount().getPrincipal().getName();
        if(logger.isDebugEnabled()) logger.debug("userId = " + userId);
        if("error".equals(userId)) {
            exchange.setStatusCode(StatusCodes.BAD_REQUEST);
            exchange.getResponseSender().send(context.getAuthenticatedAccount().getRoles().iterator().next());
            processAudit(exchange);
        } else {
            Set<String> roles = context.getAuthenticatedAccount().getRoles();
            Map<String, String> codeMap = new HashMap<>();
            codeMap.put("userId", userId);
            if(roles != null && !roles.isEmpty()) {
                codeMap.put("roles", String.join(" ", roles));
            }
            // generate auth code
            String code = Util.getUUID();
            if(redirectUri == null) {
                redirectUri = client.getRedirectUri();
            } else {
                codeMap.put("redirectUri", redirectUri);
            }
            if(remember != null) codeMap.put("remember", remember); // pass the remember checkbox value to the token service
            CacheStartupHookProvider.hz.getMap("codes").set(code, codeMap);

            redirectUri = redirectUri + "?code=" + code;
            if(state != null) {
                redirectUri = redirectUri + "&state=" + state;
            }
            if(logger.isDebugEnabled()) logger.debug("redirectUri = " + redirectUri);
            // now redirect here.
            exchange.setStatusCode(StatusCodes.FOUND);
            exchange.getResponseHeaders().put(Headers.LOCATION, redirectUri);
            exchange.endExchange();
            processAudit(exchange);
        }
    }
}