Search in sources :

Example 1 with FormData

use of io.undertow.server.handlers.form.FormData in project camel by apache.

the class DefaultUndertowHttpBinding method toCamelMessage.

@Override
public Message toCamelMessage(HttpServerExchange httpExchange, Exchange exchange) throws Exception {
    Message result = new DefaultMessage();
    populateCamelHeaders(httpExchange, result.getHeaders(), exchange);
    // Map form data which is parsed by undertow form parsers
    FormData formData = httpExchange.getAttachment(FormDataParser.FORM_DATA);
    if (formData != null) {
        Map<String, Object> body = new HashMap<>();
        formData.forEach(key -> {
            formData.get(key).forEach(value -> {
                if (value.isFile()) {
                    DefaultAttachment attachment = new DefaultAttachment(new FilePartDataSource(value));
                    result.addAttachmentObject(key, attachment);
                    body.put(key, attachment.getDataHandler());
                } else if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToExternalHeaders(key, value.getValue(), exchange)) {
                    UndertowHelper.appendHeader(result.getHeaders(), key, value.getValue());
                    UndertowHelper.appendHeader(body, key, value.getValue());
                }
            });
        });
        result.setBody(body);
    } else {
        //body is extracted as byte[] then auto TypeConverter kicks in
        if (Methods.POST.equals(httpExchange.getRequestMethod()) || Methods.PUT.equals(httpExchange.getRequestMethod())) {
            result.setBody(readFromChannel(httpExchange.getRequestChannel()));
        } else {
            result.setBody(null);
        }
    }
    return result;
}
Also used : DefaultMessage(org.apache.camel.impl.DefaultMessage) FormData(io.undertow.server.handlers.form.FormData) Message(org.apache.camel.Message) DefaultMessage(org.apache.camel.impl.DefaultMessage) HashMap(java.util.HashMap) HttpString(io.undertow.util.HttpString) DefaultAttachment(org.apache.camel.impl.DefaultAttachment)

Example 2 with FormData

use of io.undertow.server.handlers.form.FormData in project core-ng-project by neowu.

the class RequestParser method parseForm.

private void parseForm(RequestImpl request, HttpServerExchange exchange) {
    FormData formData = exchange.getAttachment(FormDataParser.FORM_DATA);
    if (formData == null)
        return;
    for (String name : formData) {
        FormData.FormValue value = formData.getFirst(name);
        if (value.isFile()) {
            if (!Strings.isEmpty(value.getFileName())) {
                // browser passes empty file name if not choose file in form
                logger.debug("[request:file] {}={}, size={}", name, value.getFileName(), Files.size(value.getPath()));
                request.files.put(name, new MultipartFile(value.getPath(), value.getFileName(), value.getHeaders().getFirst(Headers.CONTENT_TYPE)));
            }
        } else {
            logger.debug("[request:form] {}={}", name, new FieldParam(name, value.getValue()));
            request.formParams.put(name, value.getValue());
        }
    }
}
Also used : FormData(io.undertow.server.handlers.form.FormData) MultipartFile(core.framework.web.MultipartFile) FieldParam(core.framework.impl.log.filter.FieldParam) HttpString(io.undertow.util.HttpString)

Example 3 with FormData

use of io.undertow.server.handlers.form.FormData in project light-codegen by networknt.

the class ValidateUploadFileHandler method handle.

/**
 * Retrieve the file from the request and validate the json contents against a schema.
 * Will return the contents of the file as well.
 *
 * @param o The multipart as parsed from com.networknt.rpc.router.MultipartHandler
 *
 * @return The contents of the file if valid, null otherwise. TODO to provide error messages.
 */
@Override
public ByteBuffer handle(HttpServerExchange exchange, Object o) {
    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    logger.entry(o);
    if (o instanceof FormData) {
        File file = this.getFileFromForm((FormData) o);
        try {
            // TODO validate against schema... where do I find the schema?
            String fileContents = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
            return NioUtils.toByteBuffer(fileContents);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}
Also used : FormData(io.undertow.server.handlers.form.FormData) HttpString(io.undertow.util.HttpString) HttpString(io.undertow.util.HttpString)

Example 4 with FormData

use of io.undertow.server.handlers.form.FormData in project undertow by undertow-io.

the class FormAuthenticationMechanism method runFormAuth.

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;
    }
    Throwable original = null;
    AuthenticationMechanismOutcome retValue = null;
    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);
            }
        } catch (Throwable t) {
            original = t;
        } finally {
            try {
                if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) {
                    handleRedirectBack(exchange);
                    exchange.endExchange();
                }
                retValue = outcome != null ? outcome : AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            } catch (Throwable t) {
                if (original != null) {
                    original.addSuppressed(t);
                } else {
                    original = t;
                }
            }
        }
    } catch (IOException e) {
        original = new UncheckedIOException(e);
    }
    if (original != null) {
        if (original instanceof RuntimeException) {
            throw (RuntimeException) original;
        }
        if (original instanceof Error) {
            throw (Error) original;
        }
    }
    return retValue;
}
Also used : FormData(io.undertow.server.handlers.form.FormData) Account(io.undertow.security.idm.Account) IdentityManager(io.undertow.security.idm.IdentityManager) PasswordCredential(io.undertow.security.idm.PasswordCredential) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) FormDataParser(io.undertow.server.handlers.form.FormDataParser)

Example 5 with FormData

use of io.undertow.server.handlers.form.FormData in project undertow by undertow-io.

the class RequestDumpingHandler method dumpRequestBody.

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.isFileItem() ? "[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);
    }
}
Also used : FormData(io.undertow.server.handlers.form.FormData) HeaderValues(io.undertow.util.HeaderValues)

Aggregations

FormData (io.undertow.server.handlers.form.FormData)11 HttpString (io.undertow.util.HttpString)8 ArrayList (java.util.ArrayList)3 FormDataParser (io.undertow.server.handlers.form.FormDataParser)2 HeaderValues (io.undertow.util.HeaderValues)2 HashMap (java.util.HashMap)2 FieldParam (core.framework.impl.log.filter.FieldParam)1 MultipartFile (core.framework.web.MultipartFile)1 Account (io.undertow.security.idm.Account)1 IdentityManager (io.undertow.security.idm.IdentityManager)1 PasswordCredential (io.undertow.security.idm.PasswordCredential)1 ServletRequestContext (io.undertow.servlet.handlers.ServletRequestContext)1 IteratorEnumeration (io.undertow.servlet.util.IteratorEnumeration)1 HeaderMap (io.undertow.util.HeaderMap)1 IOException (java.io.IOException)1 UncheckedIOException (java.io.UncheckedIOException)1 Deque (java.util.Deque)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1 Part (javax.servlet.http.Part)1