org.apache.wicket.Application Java Examples

The following examples show how to use org.apache.wicket.Application. 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: LogoutPanel.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
/**
 * Construct logout panel.
 * @param id component id.
 */
public LogoutPanel(final String id) {
    super(id);

    final StatelessForm form = new StatelessForm(LOGOFF_LINK);

    final Button submit = new Button("logoffCmd") {
        @Override
        public void onSubmit() {
            final Map<String, Object> cmd = new HashMap<>();
            cmd.put(ShoppingCartCommand.CMD_LOGOUT, ShoppingCartCommand.CMD_LOGOUT);
            shoppingCartCommandFactory.execute(ShoppingCartCommand.CMD_LOGOUT, getCurrentCart(), cmd);
            ((AbstractWebPage) getPage()).persistCartIfNecessary();
            LogoutPanel.this.setResponsePage(Application.get().getHomePage());
        }
    };

    submit.setDefaultFormProcessing(false);

    form.add(submit);

    add(form);

}
 
Example #2
Source File: WebSocketHelper.java    From openmeetings with Apache License 2.0 6 votes vote down vote up
private static void sendAll(Consumer<IWebSocketConnection> sender) {
	new Thread(() -> {
		Application app = (Application)getApp();
		if (app == null) {
			return; // Application is not ready
		}
		WebSocketSettings settings = WebSocketSettings.Holder.get(app);
		IWebSocketConnectionRegistry reg = settings.getConnectionRegistry();
		Executor executor = settings.getWebSocketPushMessageExecutor();
		for (IWebSocketConnection wc : reg.getConnections(app)) {
			if (wc != null && wc.isOpen()) {
				executor.run(() -> sender.accept(wc));
			}
		}
	}).start();
}
 
Example #3
Source File: DateFormatValidator.java    From ontopia with Apache License 2.0 6 votes vote down vote up
@Override
protected void onValidate(IValidatable<String> validatable) {
  final String value = validatable.getValue();
  if (value == null) return;
  try {
    DateFormat df = createDateFormat();
    df.parse(value);
  } catch (ParseException e) {
    String message = Application.get().getResourceSettings().getLocalizer().getString(resourceKey(), (Component)null, 
          new Model<Serializable>(new Serializable() {
            @SuppressWarnings("unused")
            public String getValue() {
              return value;
            }
          }));
    component.error(AbstractFieldInstancePanel.createErrorMessage(fieldInstanceModel, new Model<String>(message)));
  }
}
 
Example #4
Source File: ServerSideJs.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
@Override
protected void onBeforeRender() {

    final boolean deploymentMode = Application.get().getConfigurationType() == RuntimeConfigurationType.DEPLOYMENT;

    addOrReplace(new Label("jsInclude", new StringBuilder()
        .append("<script type=\"text/javascript\">")
        .append("var ctx = {").append("\n")
        .append("  url: document.URL,\n")
        .append("  live: ").append(deploymentMode).append(",\n")
        .append("  page: '").append(getPage().getClass().getSimpleName()).append("',\n")
        .append("  root: '").append(getWicketUtil().getHttpServletRequest().getContextPath()).append("',\n")
        .append("  resources: {\n")
        .append("     areYouSure: '").append(getLocalizer().getString("areYouSure", this)).append("',\n")
        .append("     yes: '").append(getLocalizer().getString("yes", this)).append("',\n")
        .append("     no: '").append(getLocalizer().getString("no", this)).append("',\n")
        .append("     wishlistTagsInfo: '").append(getLocalizer().getString("wishlistTagsInfo", this)).append("',\n")
        .append("     wishlistTagLinkOffInfo: '").append(getLocalizer().getString("wishlistTagLinkOffInfo", this)).append("',\n")
        .append("     wishlistTagLinkOnInfo: '").append(getLocalizer().getString("wishlistTagLinkOnInfo", this)).append("'\n")
        .append("  }\n")
        .append("}\n")
        .append("</script>").toString()).setEscapeModelStrings(false));

    super.onBeforeRender();
}
 
Example #5
Source File: URIValidator.java    From ontopia with Apache License 2.0 6 votes vote down vote up
@Override
protected void onValidate(IValidatable<String> validatable) {
  final String value = validatable.getValue();
  if (value == null) return;
  try {
    new URILocator(value);
  } catch (Exception e) {
    String message = Application.get().getResourceSettings().getLocalizer().getString(resourceKey(), (Component)null, 
        new Model<Serializable>(new Serializable() {
          @SuppressWarnings("unused")
          public String getValue() {
            return value;
          }
        }));
    component.error(AbstractFieldInstancePanel.createErrorMessage(fieldInstanceModel, new Model<String>(message)));
  }
}
 
Example #6
Source File: AbstractNamingModel.java    From wicket-orientdb with Apache License 2.0 6 votes vote down vote up
/**
 * Returns name
 * @param component component to look associated localization 
 * @return name
 */
public String getObject(Component component) {
	if(objectModel!=null)
	{
		T object = objectModel.getObject();
		if(object==null) return null;
		resourceKey = getResourceKey(object);
	}
	String defaultValue = getDefault();
	if(defaultValue==null) defaultValue = Strings.lastPathComponent(resourceKey, '.');
	if(defaultValue!=null) defaultValue = buitify(defaultValue);
	return Application.get()
			.getResourceSettings()
			.getLocalizer()
			.getString(resourceKey, null, defaultValue);
}
 
Example #7
Source File: PolymorphicPropertyViewer.java    From onedev with MIT License 6 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	
	String displayName = EditableUtils.getDisplayName(propertyValue.getClass());
	displayName = Application.get().getResourceSettings().getLocalizer().getString(displayName, this, displayName);
	
	add(new Label("type", displayName));
	add(new Label("typeDescription", new AbstractReadOnlyModel<String>() {

		@Override
		public String getObject() {
			return EditableUtils.getDescription(propertyValue.getClass());
		}
		
	}) {

		@Override
		protected void onConfigure() {
			super.onConfigure();
			setVisible(propertyValue != null && EditableUtils.getDescription(propertyValue.getClass()) != null);
		}
		
	});
	add(BeanContext.view("beanViewer", propertyValue, excludedProperties, true));
}
 
Example #8
Source File: UrlImporter.java    From webanno with Apache License 2.0 6 votes vote down vote up
private Optional<Import> resolveWebContextDependency(String url)
{
    LOG.debug("Going to resolve an import from the web context: {}", url);
    String resourceName = url.substring(WEB_CONTEXT_SCHEME.length());
    if (resourceName.indexOf(0) == '/') {
        resourceName = resourceName.substring(1);
    }

    final ServletContext context = ((WebApplication) Application.get()).getServletContext();
    try {
        return Optional.of(buildImport(context.getResource(resourceName)));
    }
    catch (MalformedURLException ex) {
        throw new IllegalArgumentException(
                "Cannot create a URL to a resource in the web context", ex);
    }
}
 
Example #9
Source File: AbstractDataInstallator.java    From wicket-orientdb with Apache License 2.0 6 votes vote down vote up
@Override
public void onAfterInitialized(Application application) {
	OrientDbWebApplication app = (OrientDbWebApplication)application;
	ODatabaseDocument db = getDatabase(app);
	try
	{
		installData(app, db);
	}
	catch(Exception ex)
	{
		LOG.error("Data can't be installed", ex);
	}
	finally
	{
		db.close();
	}
}
 
Example #10
Source File: SimpleWebSocketConnectionRegistry.java    From onedev with MIT License 6 votes vote down vote up
/**
 * Returns a collection of currently active websockets. The connections might close at any time.
 *
 * @param application
 *          The application
 * @return a collection of currently active websockets
 */
public Collection<IWebSocketConnection> getConnections(Application application)
{
	Args.notNull(application, "application");

	Collection<IWebSocketConnection> connections = new ArrayList<>();
	ConcurrentMap<String, ConcurrentMap<IKey, IWebSocketConnection>> connectionsBySession = application.getMetaData(KEY);
	if (connectionsBySession != null)
	{
		for (ConcurrentMap<IKey, IWebSocketConnection> connectionsByPage : connectionsBySession.values())
		{
			connections.addAll(connectionsByPage.values());
		}
	}
	return connections;
}
 
Example #11
Source File: SimpleWebSocketConnectionRegistry.java    From onedev with MIT License 6 votes vote down vote up
@Override
public Collection<IWebSocketConnection> getConnections(Application application, String sessionId)
{
	Args.notNull(application, "application");
	Args.notNull(sessionId, "sessionId");

	Collection<IWebSocketConnection> connections = Collections.emptyList();
	ConcurrentMap<String, ConcurrentMap<IKey, IWebSocketConnection>> connectionsBySession = application.getMetaData(KEY);
	if (connectionsBySession != null)
	{
		ConcurrentMap<IKey, IWebSocketConnection> connectionsByPage = connectionsBySession.get(sessionId);
		if (connectionsByPage != null)
		{
			connections = connectionsByPage.values();
		}
	}
	return connections;
}
 
Example #12
Source File: AbstractWebPage.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
private void determineStatefulComponentOnDev() {

        if (Application.get().getConfigurationType() == RuntimeConfigurationType.DEVELOPMENT && !isPageStateless()) {

            final List<String> statefulComponentIds = new ArrayList<>();
            this.visitChildren(Component.class, (object, objectIVisit) -> {
                if (!object.isStateless()) {
                    statefulComponentIds.add(object.getId());
                }
            });
            LOG.warn("[DEV] Page {} is stateful because of the following components: {}", getClass().getCanonicalName(), statefulComponentIds);

        }
    }
 
Example #13
Source File: Initializer.java    From pm-wicket-utils with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void init(Application application) {
	if(application instanceof WebApplication){
		WebApplication app = (WebApplication) application;
		
		// add DynamicListView handler
		app.getAjaxRequestTargetListeners().add(new AjaxListSetView.AjaxListener());
	}
}
 
Example #14
Source File: OneWebApplication.java    From onedev with MIT License 5 votes vote down vote up
@Override
public final IProvider<IExceptionMapper> getExceptionMapperProvider() {
	return new IProvider<IExceptionMapper>() {

		@Override
		public IExceptionMapper get() {
			return new DefaultExceptionMapper() {

				@Override
				protected IRequestHandler mapExpectedExceptions(Exception e, Application application) {
					RequestCycle requestCycle = RequestCycle.get();
					boolean isAjax = ((WebRequest)requestCycle.getRequest()).isAjax();
					if (isAjax && (e instanceof ListenerInvocationNotAllowedException || e instanceof ComponentNotFoundException))
						return EmptyAjaxRequestHandler.getInstance();
					
					IRequestMapper mapper = Application.get().getRootRequestMapper();
					if (mapper.mapRequest(requestCycle.getRequest()) instanceof ResourceReferenceRequestHandler)
						return new ResourceErrorRequestHandler(e);
					
					HttpServletResponse response = (HttpServletResponse) requestCycle.getResponse().getContainerResponse();
					if (!response.isCommitted()) {
						InUseException inUseException = ExceptionUtils.find(e, InUseException.class);
						if (inUseException != null)
							return createPageRequestHandler(new PageProvider(new InUseErrorPage(inUseException)));
						else
							return createPageRequestHandler(new PageProvider(new GeneralErrorPage(e)));
					} else {
						return super.mapExpectedExceptions(e, application);
					}
				}
				
			};
		}
		
	};
}
 
Example #15
Source File: OrientDbWebApplication.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
protected static <T extends OrientDbWebApplication> T lookupApplication(Class<T> appClass)
{
	Application app = Application.exists()?Application.get():null;
	if(app!=null && appClass.isInstance(app)) return (T)app;
	else
	{
		for(String appKey: Application.getApplicationKeys())
		{
			app = Application.get(appKey);
			if(appClass.isInstance(app)) return (T)app;
		}
	}
	return null;
}
 
Example #16
Source File: ApplicationHelper.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
public static IApplication ensureApplication(Long langId) {
	IApplication a = ensureApplication();
	if (ThreadContext.getRequestCycle() == null) {
		ServletWebRequest req = new ServletWebRequest(new MockHttpServletRequest((Application)a, new MockHttpSession(a.getServletContext()), a.getServletContext()), "");
		RequestCycleContext rctx = new RequestCycleContext(req, new MockWebResponse(), a.getRootRequestMapper(), a.getExceptionMapperProvider().get());
		ThreadContext.setRequestCycle(new RequestCycle(rctx));
	}
	if (ThreadContext.getSession() == null) {
		WebSession s = WebSession.get();
		if (langId > 0) {
			((IWebSession)s).setLanguage(langId);
		}
	}
	return a;
}
 
Example #17
Source File: FormComponent.java    From onedev with MIT License 5 votes vote down vote up
private String substitute(String string, final Map<String, Object> vars)
	throws IllegalStateException
{
	return new VariableInterpolator(string, Application.get()
		.getResourceSettings()
		.getThrowExceptionOnMissingResource())
	{
		private static final long serialVersionUID = 1L;

		@SuppressWarnings({ "rawtypes", "unchecked" })
		@Override
		protected String getValue(String variableName)
		{
			Object value = vars.get(variableName);
			
			if (value == null ||value instanceof String)
			{
				return String.valueOf(value);
			}
			
			IConverter converter = getConverter(value.getClass());
			
			if (converter == null)
			{
				return Strings.toString(value);
			}
			else
			{
				return converter.convertToString(value, getLocale());
			}
		}
	}.toString();
}
 
Example #18
Source File: OClassMetaPanel.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
protected void setValue(OClass entity, String critery, V value) {
	ODatabaseDocument db = OrientDbWebSession.get().getDatabase();
	db.commit();
	try
	{
		CustomAttribute custom;
		if(OClassPrototyper.CLUSTER_SELECTION.equals(critery))
		{
			if(value!=null) entity.setClusterSelection(value.toString());
		}
		else if((CustomAttribute.ON_CREATE_FIELDS.getName().equals(critery)) && (custom = CustomAttribute.getIfExists(critery)) != null)
		{
			custom.setValue(entity, value!=null?Joiner.on(",").join((List<String>) value):null);
		}
		else if((custom = CustomAttribute.getIfExists(critery))!=null)
		{
			custom.setValue(entity, value);
		}
		else if (OClassPrototyper.SUPER_CLASSES.equals(critery))
		{
			if(value!=null) entity.setSuperClasses((List<OClass>) value);
		}
		else
		{
			PropertyResolver.setValue(critery, entity, value, new PropertyResolverConverter(Application.get().getConverterLocator(),
					Session.get().getLocale()));
		}
	} finally
	{
		db.begin();
	}
}
 
Example #19
Source File: WicketApplicationFilter.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException
{
  // Sollte eigentlich immer NULL ergeben, aber man weiss nie ...
  final Application previousOne = (Application.exists() == true) ? Application.get() : null;
  org.apache.wicket.ThreadContext.setApplication(this.application);
  try {
    chain.doFilter(request, response);
  } finally {
    if (previousOne != null) {
      org.apache.wicket.ThreadContext.setApplication(previousOne);
    } else {
      org.apache.wicket.ThreadContext.setApplication(null);
    }
  }
}
 
Example #20
Source File: Initializer.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Application application) {
	ScriptExecutor.registerScriptEngineFactory(new ODBScriptEngineFactory());
	ScriptExecutor.registerScriptEngineFactory(new ODBConsoleEngineFactory());
	ScriptResultRendererManager.INSTANCE.registerRenderer(new ODBScriptResultRenderer());
	OrienteerWebApplication app = (OrienteerWebApplication)application;
	app.registerModule(Module.class);
	
}
 
Example #21
Source File: TestAdmin.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
@AfterEach
public void tearDown() throws Exception {
	resetH2Home();
	System.getProperties().remove(OM_HOME);
	WebApplication app = (WebApplication)Application.get(getWicketApplicationName());
	if (app != null) {
		destroyApplication();
		setInitComplete(false);
	}
	System.setProperty("context", DEFAULT_CONTEXT_NAME);
	setWicketApplicationName(DEFAULT_CONTEXT_NAME);
	deleteQuietly(tempFolder);
}
 
Example #22
Source File: WebSocketMessageSenderDefault.java    From wicket-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public void send(IWebSocketPushMessage event) {
	Application application = Application.get(WicketWebInitializer.WICKET_FILTERNAME);
	WebSocketSettings webSocketSettings = WebSocketSettings.Holder.get(application);
	IWebSocketConnectionRegistry connectionRegistry = webSocketSettings.getConnectionRegistry();
	Collection<IWebSocketConnection> connections = connectionRegistry.getConnections(application);
	log.trace("sending event to {} connections", connections.size());
	for (IWebSocketConnection connection : connections) {
		connection.sendMessage(event);
	}
}
 
Example #23
Source File: LinkUtils.java    From artifact-listener with Apache License 2.0 5 votes vote down vote up
public static EmailAddress extractEmailFromHashPageParameter(IEmailAddressService emailAddressService, PageParameters parameters,
		Class<? extends Page> redirectPageClass) {
	String hash = parameters.get(LinkUtils.HASH_PARAMETER).toString();
	EmailAddress emailAddress = emailAddressService.getByHash(hash);

	if (emailAddress == null) {
		LOGGER.error("Unable to get email address from hash");
		MavenArtifactNotifierSession.get().error(
				Application.get().getResourceSettings().getLocalizer().getString("common.error.noItem", null));

		throw new RestartResponseException(redirectPageClass);
	}
	return emailAddress;
}
 
Example #24
Source File: ScrollIntoViewResourceReference.java    From onedev with MIT License 5 votes vote down vote up
@Override
public List<HeaderItem> getDependencies() {
	List<HeaderItem> dependencies = new ArrayList<>();
	dependencies.add(JavaScriptHeaderItem.forReference(Application.get().getJavaScriptLibrarySettings().getJQueryReference()));
	dependencies.add(JavaScriptHeaderItem.forReference(new JQueryUIResourceReference()));
	return dependencies;
}
 
Example #25
Source File: LoginPanel.java    From AppStash with Apache License 2.0 5 votes vote down vote up
protected void submitLoginForm(AjaxRequestTarget target, LoginInfo loginInfo) {
    boolean authenticate = authenticate(loginInfo);
    if (!authenticate) {
        error(getString("authentication.failed"));
        target.add(feedback);
    } else {
        getAuthenticationService().getAuthenticatedUserInfo();
        Session.get().info(getString("authentication.success"));
        send(this, Broadcast.BREADTH, new LoginEvent(LoginPanel.this, target));
        setResponsePage(Application.get().getHomePage());
    }
}
 
Example #26
Source File: Initializer.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
/**
 * Stop {@link PersistService}
 * @see <a href="https://github.com/xvik/guice-persist-orient#lifecycle">Lifecycle of guice-persist-orient</a>
 * @param application Wicket application
 */
@Override
public void destroy(Application application) {
    OrienteerWebApplication app = (OrienteerWebApplication) application;
    PersistService persistService = app.getServiceInstance(PersistService.class);
    persistService.stop();
}
 
Example #27
Source File: WishListItemAddPage.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void onBeforeRender() {

    final PageParameters params = getPageParameters();

    final String skuCode = params.get(ShoppingCartCommand.CMD_ADDTOWISHLIST).toString();
    final String wlType = params.get(ShoppingCartCommand.CMD_ADDTOWISHLIST_P_TYPE).toString();
    final String pageType = params.get(WebParametersKeys.PAGE_TYPE).toString();

    executeHttpPostedCommands();
    super.onBeforeRender();
    persistCartIfNecessary();


    if ("cart".equals(pageType)) {
        if (StringUtils.isNotBlank(skuCode)) {
            throw new RedirectToUrlException("/cart/" + WebParametersKeys.WISHLIST_ITEM_ADDED + "/" + skuCode + "/" + WebParametersKeys.WISHLIST_ITEM_TYPE + "/" + wlType);
        }
        throw new RedirectToUrlException("/cart");
    } else if ("wishlist".equals(pageType)) {
        if (StringUtils.isNotBlank(skuCode)) {
            throw new RedirectToUrlException("/wishlist?" + WebParametersKeys.WISHLIST_ITEM_ADDED + "=" + skuCode);
        }
        throw new RedirectToUrlException("/wishlist");
    }

    final PageParameters targetParams = getWicketUtil().getFilteredRequestParameters(params);
    if (StringUtils.isNotBlank(skuCode)) {

        final ProductSku sku = productServiceFacade.getProductSkuBySkuCode(skuCode);
        targetParams.set(WebParametersKeys.SKU_ID, sku.getSkuId());
        targetParams.set(WebParametersKeys.WISHLIST_ITEM_ADDED, skuCode);
        targetParams.set(WebParametersKeys.WISHLIST_ITEM_TYPE, wlType);

    }
    throw new RestartResponseException(Application.get().getHomePage(), targetParams);

}
 
Example #28
Source File: Initializer.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
/**
 * Start {@link PersistService}
 * @see <a href="https://github.com/xvik/guice-persist-orient#lifecycle">Lifecycle of guice-persist-orient</a>
 * @param application Wicket application
 */
@Override
public void init(Application application) {
    OrienteerWebApplication app = (OrienteerWebApplication) application;
    PersistService persistService = app.getServiceInstance(PersistService.class);
    persistService.start();
}
 
Example #29
Source File: BootstrapFeedbackPanelJavascriptReference.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
public List<HeaderItem> getDependencies()
{
    List<HeaderItem> dependencies = new ArrayList<>(super.getDependencies());
    dependencies.add(JavaScriptHeaderItem.forReference(
            Application.get().getJavaScriptLibrarySettings().getJQueryReference()));

    return dependencies;
}
 
Example #30
Source File: CheckoutPage.java    From the-app with Apache License 2.0 5 votes vote down vote up
protected void validateCheckoutPage() {
    try {
        if (checkout.getOrderItemInfos().isEmpty()) {
            getSession().error(getString("checkout.validation.failed"));
            LOGGER.debug("Basket is empty and CheckoutPage could not be created");
            throw new RestartResponseException(Application.get().getHomePage());
        }
    } catch (Exception e) {
        getSession().error("Cart is not available yet, please try again later.");
        LOGGER.error("A backend error seems to be occurred: ", e);
        throw new RestartResponseException(Application.get().getHomePage());
    }
}