001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.wicket.ajax;
018
019import java.util.Optional;
020import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
021import org.apache.wicket.request.cycle.RequestCycle;
022import org.danekja.java.util.function.serializable.SerializableConsumer;
023
024/**
025 * Some AJAX related utility functions.
026 */
027public class AjaxUtils
028{
029
030    /**
031     * Runs action if current request is of type "AJAX". Otherwise, nothing is done.
032     *
033     * @param ajaxAction
034     *            The action to run a {@link SerializableConsumer}
035     */
036    public static void executeIfAjax(SerializableConsumer<AjaxRequestTarget> ajaxAction)
037    {
038        Optional<AjaxRequestTarget> target = RequestCycle.get().find(AjaxRequestTarget.class);
039        target.ifPresent(ajaxAction);
040    }
041
042
043    /**
044     * Runs action if current request is of type "AJAX" or a Websockets request. Otherwise, nothing is done.
045     *
046     * @param ajaxAction
047     *            The action to run a {@link SerializableConsumer}
048     */
049    public static void executeIfAjaxOrWebSockets(SerializableConsumer<IPartialPageRequestHandler> ajaxAction)
050    {
051        Optional<IPartialPageRequestHandler> target = RequestCycle.get().find(IPartialPageRequestHandler.class);
052        target.ifPresent(ajaxAction);
053    }
054
055}