Search in sources :

Example 1 with None

use of org.apache.tapestry5.validator.None in project tapestry-5 by apache.

the class ResourceStreamerImpl method streamResource.

public boolean streamResource(Resource resource, StreamableResource streamable, String providedChecksum, Set<Options> options) throws IOException {
    assert streamable != null;
    assert providedChecksum != null;
    assert options != null;
    String actualChecksum = streamable.getChecksum();
    if (providedChecksum.length() > 0 && !providedChecksum.equals(actualChecksum)) {
        // TAP5-2185: Trying to find the wrongly-checksummed resource in the classpath and context,
        // so we can create an Asset with the correct checksum and redirect to it.
        Asset asset = null;
        if (resource != null) {
            asset = findAssetInsideWebapp(resource);
        }
        if (asset != null) {
            response.sendRedirect(asset.toClientURL());
            return true;
        }
        return false;
    }
    // ETag should be surrounded with quotes.
    String token = QUOTE + actualChecksum + QUOTE;
    // Even when sending a 304, we want the ETag associated with the request.
    // In most cases (except JavaScript modules), the checksum is also embedded into the URL.
    // However, E-Tags are also useful for enabling caching inside intermediate servers, CDNs, etc.
    response.setHeader("ETag", token);
    // If the client can send the correct ETag token, then its cache already contains the correct
    // content.
    String providedToken = request.getHeader("If-None-Match");
    if (token.equals(providedToken)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return true;
    }
    long lastModified = streamable.getLastModified();
    long ifModifiedSince;
    try {
        ifModifiedSince = request.getDateHeader(IF_MODIFIED_SINCE_HEADER);
    } catch (IllegalArgumentException ex) {
        // Simulate the header being missing if it is poorly formatted.
        ifModifiedSince = -1;
    }
    if (ifModifiedSince > 0 && ifModifiedSince >= lastModified) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return true;
    }
    // Prevent the upstream code from compressing when we don't want to.
    response.disableCompression();
    response.setDateHeader("Last-Modified", lastModified);
    if (productionMode && !options.contains(Options.OMIT_EXPIRATION)) {
        // Starting in 5.4, this is a lot less necessary; any change to a Resource will result
        // in a new asset URL with the changed checksum incorporated into the URL.
        response.setDateHeader("Expires", lastModified + InternalConstants.TEN_YEARS);
    }
    // mostly result in quick SC_NOT_MODIFIED responses.
    if (options.contains(Options.OMIT_EXPIRATION)) {
        response.setHeader("Cache-Control", omitExpirationCacheControlHeader);
    }
    if (streamable.getCompression() == CompressionStatus.COMPRESSED) {
        response.setHeader(TapestryHttpInternalConstants.CONTENT_ENCODING_HEADER, TapestryHttpInternalConstants.GZIP_CONTENT_ENCODING);
    }
    ResponseCustomizer responseCustomizer = streamable.getResponseCustomizer();
    if (responseCustomizer != null) {
        responseCustomizer.customizeResponse(streamable, response);
    }
    if (!request.getMethod().equals("HEAD")) {
        response.setContentLength(streamable.getSize());
        OutputStream os = response.getOutputStream(streamable.getContentType().toString());
        streamable.streamTo(os);
        os.close();
    }
    return true;
}
Also used : OutputStream(java.io.OutputStream) Asset(org.apache.tapestry5.Asset)

Example 2 with None

use of org.apache.tapestry5.validator.None in project tapestry-5 by apache.

the class InternalComponentResourcesImplTest method post_render_cleanup_removes_all_variables.

@Test
public void post_render_cleanup_removes_all_variables() {
    Component component = mockComponent();
    Instantiator ins = mockInstantiator(component);
    ComponentModel model = mockComponentModel();
    train_getModel(ins, model);
    replay();
    InternalComponentResources resources = new InternalComponentResourcesImpl(null, null, null, elementResources, "Foo.bar", null, ins, false);
    resources.storeRenderVariable("fred", "FRED");
    resources.storeRenderVariable("barney", "BARNEY");
    resources.postRenderCleanup();
    try {
        resources.getRenderVariable("fred");
        unreachable();
    } catch (IllegalArgumentException ex) {
        assertEquals(ex.getMessage(), "Component Foo.bar does not contain a stored render variable with name 'fred'.  Stored render variables: (none).");
    }
    verify();
}
Also used : InternalComponentResources(org.apache.tapestry5.internal.InternalComponentResources) ComponentModel(org.apache.tapestry5.model.ComponentModel) Instantiator(org.apache.tapestry5.internal.services.Instantiator) Component(org.apache.tapestry5.runtime.Component) Test(org.testng.annotations.Test)

Example 3 with None

use of org.apache.tapestry5.validator.None in project tapestry-5 by apache.

the class FormFragment method beginRender.

/**
 * Renders a &lt;div&gt; tag and provides an override of the {@link org.apache.tapestry5.services.FormSupport}
 * environmental.
 */
void beginRender(MarkupWriter writer) {
    FormSupport formSupport = environment.peekRequired(FormSupport.class);
    String clientId = getClientId();
    hiddenFieldPositioner = new HiddenFieldPositioner(writer, rules);
    Element element = writer.element(this.element, "id", clientId, "data-component-type", "core/FormFragment");
    if (alwaysSubmit) {
        element.attribute("data-always-submit", "true");
    }
    resources.renderInformalParameters(writer);
    if (!visible) {
        element.attribute("style", "display: none;");
        if (!alwaysSubmit) {
            javascriptSupport.require("t5/core/form-fragment").invoke("hide").with(clientId);
        }
    }
    componentActions = new ComponentActionSink(logger, clientDataEncoder);
    // Here's the magic of environmentals ... we can create a wrapper around
    // the normal FormSupport environmental that intercepts some of the behavior.
    // Here we're setting aside all the actions inside the FormFragment so that we
    // can control whether those actions occur when the form is submitted.
    FormSupport override = new FormSupportAdapter(formSupport) {

        @Override
        public <T> void store(T component, ComponentAction<T> action) {
            componentActions.store(component, action);
        }

        @Override
        public <T> void storeCancel(T component, ComponentAction<T> action) {
            componentActions.storeCancel(component, action);
        }

        @Override
        public <T> void storeAndExecute(T component, ComponentAction<T> action) {
            componentActions.store(component, action);
            action.execute(component);
        }
    };
    // Tada! Now all the enclosed components will use our override of FormSupport,
    // until we pop it off.
    environment.push(FormSupport.class, override);
}
Also used : ComponentActionSink(org.apache.tapestry5.corelib.internal.ComponentActionSink) HiddenFieldPositioner(org.apache.tapestry5.corelib.internal.HiddenFieldPositioner) Element(org.apache.tapestry5.dom.Element) FormSupportAdapter(org.apache.tapestry5.corelib.internal.FormSupportAdapter) FormSupport(org.apache.tapestry5.services.FormSupport)

Example 4 with None

use of org.apache.tapestry5.validator.None in project tapestry-5 by apache.

the class FieldValidatorSourceImplTest method missing_field_validator_constraint.

@SuppressWarnings("unchecked")
@Test
public void missing_field_validator_constraint() throws Exception {
    Validator validator = mockValidator();
    TypeCoercer coercer = mockTypeCoercer();
    FieldComponent field = newFieldComponent();
    ComponentResources resources = mockComponentResources();
    Messages containerMessages = mockMessages();
    FormSupport fs = mockFormSupport();
    Map<String, Validator> map = singletonMap("minlength", validator);
    train_getConstraintType(validator, Integer.class);
    train_getFormValidationId(fs, "myform");
    train_getComponentResources(field, resources);
    train_getId(resources, "fred");
    train_getContainerMessages(resources, containerMessages);
    train_contains(containerMessages, "myform-fred-minlength", false);
    train_contains(containerMessages, "fred-minlength", false);
    ValidatorMacro macro = mockValidatorMacro();
    train_alwaysNull(macro);
    replay();
    FieldValidatorSource source = new FieldValidatorSourceImpl(null, coercer, fs, map, macro);
    try {
        source.createValidators(field, "minlength");
        unreachable();
    } catch (IllegalArgumentException ex) {
        assertEquals(ex.getMessage(), "Validator 'minlength' requires a validation constraint (of type java.lang.Integer) but none was provided. The constraint may be provided inside the @Validator annotation on the property, or in the associated component message catalog as key 'myform-fred-minlength' or key 'fred-minlength'.");
    }
    verify();
}
Also used : FieldValidatorSource(org.apache.tapestry5.services.FieldValidatorSource) Messages(org.apache.tapestry5.commons.Messages) TypeCoercer(org.apache.tapestry5.commons.services.TypeCoercer) ValidatorMacro(org.apache.tapestry5.validator.ValidatorMacro) FieldValidator(org.apache.tapestry5.FieldValidator) Validator(org.apache.tapestry5.Validator) FormSupport(org.apache.tapestry5.services.FormSupport) ComponentResources(org.apache.tapestry5.ComponentResources) Test(org.testng.annotations.Test)

Example 5 with None

use of org.apache.tapestry5.validator.None in project tapestry-5 by apache.

the class DefaultRequestExceptionHandler method handleRequestException.

/**
 * Handles the exception thrown at some point the request was being processed
 *
 * First checks if there was a specific exception handler/page configured for this exception type, it's super class or super-super class.
 * Renders the default exception page if none was configured.
 *
 * @param exception
 *         The exception that was thrown
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public void handleRequestException(Throwable exception) throws IOException {
    // skip handling of known exceptions if there are none configured
    if (configuration.isEmpty()) {
        renderException(exception);
        return;
    }
    Throwable cause = exception;
    // Throw away the wrapped exceptions first
    while (cause instanceof TapestryException) {
        if (cause.getCause() == null)
            break;
        cause = cause.getCause();
    }
    Class<?> causeClass = cause.getClass();
    if (!configuration.containsKey(causeClass)) {
        // try at most two level of superclasses before delegating back to the default exception handler
        causeClass = causeClass.getSuperclass();
        if (causeClass == null || !configuration.containsKey(causeClass)) {
            causeClass = causeClass.getSuperclass();
            if (causeClass == null || !configuration.containsKey(causeClass)) {
                renderException(exception);
                return;
            }
        }
    }
    Object[] exceptionContext = formExceptionContext(cause);
    Object value = configuration.get(causeClass);
    Object page = null;
    ExceptionHandlerAssistant assistant = null;
    if (value instanceof ExceptionHandlerAssistant) {
        assistant = (ExceptionHandlerAssistant) value;
        // in case the assistant changes the context
        List context = Arrays.asList(exceptionContext);
        page = assistant.handleRequestException(exception, context);
        exceptionContext = context.toArray();
    } else if (!(value instanceof Class)) {
        renderException(exception);
        return;
    } else
        page = value;
    if (page == null)
        return;
    try {
        if (page instanceof Class)
            page = componentClassResolver.resolvePageClassNameToPageName(((Class) page).getName());
        Link link = page instanceof Link ? (Link) page : linkSource.createPageRenderLink(page.toString(), false, exceptionContext);
        if (request.isXHR()) {
            OutputStream os = response.getOutputStream("application/json;charset=UTF-8");
            JSONObject reply = new JSONObject();
            reply.in(InternalConstants.PARTIAL_KEY).put("redirectURL", link.toRedirectURI());
            os.write(reply.toCompactString().getBytes("UTF-8"));
            os.close();
            return;
        }
        // Normal behavior is just a redirect.
        response.sendRedirect(link);
    }// user's responsibility not to abuse the mechanism
     catch (Exception e) {
        logger.warn("A new exception was thrown while trying to handle an instance of {}.", exception.getClass().getName(), e);
        // Nothing to do but delegate
        renderException(exception);
    }
}
Also used : ExceptionHandlerAssistant(org.apache.tapestry5.ExceptionHandlerAssistant) JSONObject(org.apache.tapestry5.json.JSONObject) OutputStream(java.io.OutputStream) JSONObject(org.apache.tapestry5.json.JSONObject) List(java.util.List) TapestryException(org.apache.tapestry5.commons.internal.util.TapestryException) Link(org.apache.tapestry5.http.Link) OperationException(org.apache.tapestry5.ioc.internal.OperationException) IOException(java.io.IOException) ComponentEventException(org.apache.tapestry5.runtime.ComponentEventException) ContextAwareException(org.apache.tapestry5.ContextAwareException) TapestryException(org.apache.tapestry5.commons.internal.util.TapestryException)

Aggregations

OutputStream (java.io.OutputStream)2 FormSupport (org.apache.tapestry5.services.FormSupport)2 Test (org.testng.annotations.Test)2 ReadPreference (com.mongodb.ReadPreference)1 WriteConcern (com.mongodb.WriteConcern)1 IOException (java.io.IOException)1 List (java.util.List)1 Asset (org.apache.tapestry5.Asset)1 ComponentResources (org.apache.tapestry5.ComponentResources)1 ContextAwareException (org.apache.tapestry5.ContextAwareException)1 ExceptionHandlerAssistant (org.apache.tapestry5.ExceptionHandlerAssistant)1 FieldValidator (org.apache.tapestry5.FieldValidator)1 TrackableComponentEventCallback (org.apache.tapestry5.TrackableComponentEventCallback)1 Validator (org.apache.tapestry5.Validator)1 Messages (org.apache.tapestry5.commons.Messages)1 TapestryException (org.apache.tapestry5.commons.internal.util.TapestryException)1 CoercionTuple (org.apache.tapestry5.commons.services.CoercionTuple)1 TypeCoercer (org.apache.tapestry5.commons.services.TypeCoercer)1 ComponentActionSink (org.apache.tapestry5.corelib.internal.ComponentActionSink)1 FormSupportAdapter (org.apache.tapestry5.corelib.internal.FormSupportAdapter)1