Java Code Examples for org.apache.wicket.Session

The following examples show how to use org.apache.wicket.Session. These examples are extracted from open source projects. 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 Project: JPPF   Source File: ActionHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Update the actions managed by this handler based ont he selected nodes.
 * @param treeNodes the selected nodes.
 */
public void selectionChanged(final List<DefaultMutableTreeNode> treeNodes) {
  if (debugEnabled) log.debug("selected nodes: {}", treeNodes);
  for (final String id: actionLinks.keySet()) {
    final AbstractActionLink link = actionLinks.get(id);
    final UpdatableAction action = actions.get(id);
    if (action != null) {
      final JPPFWebSession session = (JPPFWebSession) Session.get();
      action.setAuthorized(session.getRoles());
      action.setEnabled(treeNodes);
      if (link != null) link.setEnabled(action.isAuthorized() && action.isEnabled());
    } else {
      if (link != null) link.setEnabled(true);
    }
  }
}
 
Example 2
Source Project: inception   Source File: AgreementPageMenuItem.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Only admins and project managers can see this page
 */
@Override
public boolean applies()
{
    Project sessionProject = Session.get().getMetaData(SessionMetaData.CURRENT_PROJECT);
    if (sessionProject == null) {
        return false;
    }
    
    // The project object stored in the session is detached from the persistence context and
    // cannot be used immediately in DB interactions. Fetch a fresh copy from the DB.
    Project project = projectService.getProject(sessionProject.getId());

    // Visible if the current user is a curator or project admin
    User user = userRepo.getCurrentUser();
    return (projectService.isCurator(project, user)
            || projectService.isProjectAdmin(project, user))
            && WebAnnoConst.PROJECT_TYPE_ANNOTATION.equals(project.getMode());
}
 
Example 3
Source Project: inception   Source File: KnowledgeBasePageMenuItem.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean applies()
{
    Project sessionProject = Session.get().getMetaData(SessionMetaData.CURRENT_PROJECT);
    if (sessionProject == null) {
        return false;
    }
    
    // The project object stored in the session is detached from the persistence context and
    // cannot be used immediately in DB interactions. Fetch a fresh copy from the DB.
    Project project = projectService.getProject(sessionProject.getId());

    // Not visible if the current user is not an annotator
    User user = userRepo.getCurrentUser();
    if (!(projectService.isAnnotator(project, user)
            && WebAnnoConst.PROJECT_TYPE_ANNOTATION.equals(project.getMode()))) {
        return false;
    }
    
    // not visible if the current project does not have knowledge bases
    return !kbService.getKnowledgeBases(project).isEmpty();
}
 
Example 4
Source Project: inception   Source File: ProjectDashboardPage.java    License: Apache License 2.0 6 votes vote down vote up
public ProjectDashboardPage(final PageParameters aPageParameters)
{
    super(aPageParameters);
    
    User currentUser = userRepository.getCurrentUser();
    
    // Check if use can access the project
    Project project = projectService.listAccessibleProjects(currentUser).stream()
            .filter(p -> p.getId().equals(
                    aPageParameters.get(PAGE_PARAM_PROJECT_ID).toOptionalLong()))
            .findFirst()
            .orElse(null);

    // If the user has no access, send the user back to the overview page
    if (project == null) {
        setResponsePage(ProjectsOverviewPage.class);
    }
    
    // Otherwise make the project the current project
    Session.get().setMetaData(CURRENT_PROJECT, project);
    
    commonInit();
}
 
Example 5
public DeleteEmailHtmlNotificationDemoPage(PageParameters parameters) {
	super(parameters);
	
	User user = userService.getByUserName(ConsoleNotificationIndexPage.DEFAULT_USERNAME);
	EmailAddress emailAddress = null;
	if (user != null) {
		emailAddress = Iterables.getFirst(user.getAdditionalEmails(), null);
	}
	if (user == null || emailAddress == null) {
		LOGGER.error("There is no user or email address available");
		Session.get().error(getString("console.notifications.noDataAvailable"));
		
		throw new RestartResponseException(ConsoleNotificationIndexPage.class);
	}

	if (emailAddress.getEmailHash() == null) {
		emailAddress.setEmailHash(userService.getHash(user, emailAddress.getEmail()));
	}
	
	add(new DeleteEmailHtmlNotificationPanel("htmlPanel", Model.of(emailAddress)));
}
 
Example 6
Source Project: onedev   Source File: OpenIdConnector.java    License: MIT License 6 votes vote down vote up
@Override
public void initiateLogin() {
	try {
		ClientID clientID = new ClientID(clientId);
		
		State state = new State(UUID.randomUUID().toString());
		Session.get().setAttribute(SESSION_ATTR_STATE, state.getValue());
		Session.get().setAttribute(SESSION_ATTR_PROVIDER_METADATA, discoverProviderMetadata());
		
		String scopes = "openid email profile";
		if (groupsClaim != null)
			scopes = scopes + " " + groupsClaim;
		
		AuthenticationRequest request = new AuthenticationRequest(
				new URI(getCachedProviderMetadata().getAuthorizationEndpoint()),
			    new ResponseType("code"), Scope.parse(scopes), clientID, getCallbackUri(),
			    state, new Nonce());
		throw new RedirectToUrlException(request.toURI().toString());
	} catch (URISyntaxException|SerializeException e) {
		throw new RuntimeException(e);
	}		
}
 
Example 7
Source Project: onedev   Source File: InvalidBuildPage.java    License: MIT License 6 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	add(new Link<Void>("delete") {

		@Override
		public void onClick() {
			OneDev.getInstance(BuildManager.class).delete(getBuild());
			
			Session.get().success("Build #" + getBuild().getNumber() + " deleted");
			
			String redirectUrlAfterDelete = WebSession.get().getRedirectUrlAfterDelete(Build.class);
			if (redirectUrlAfterDelete != null)
				throw new RedirectToUrlException(redirectUrlAfterDelete);
			else
				setResponsePage(ProjectBuildsPage.class, ProjectBuildsPage.paramsOf(getProject()));
		}

		@Override
		protected void onConfigure() {
			super.onConfigure();
			setVisible(SecurityUtils.canManage(getBuild()));
		}
		
	}.add(new ConfirmClickModifier("Do you really want to delete build #" + getBuild().getNumber() + "?")));
}
 
Example 8
Source Project: the-app   Source File: LoginModalPanel.java    License: Apache License 2.0 6 votes vote down vote up
private LoginPanel loginPanel() {
    return new LoginPanel("loginPanel") {

        @Override
        protected boolean isSubmitLinkVisible() {
            return false;
        }

        @Override
        protected void submitLoginForm(AjaxRequestTarget target, LoginInfo loginInfo) {
            boolean authenticate = authenticate(loginInfo);
            if (authenticate) {
                Session.get().info(getString("authentication.success"));

                setResponsePage(getPage());
                send(getPage(), Broadcast.BREADTH, new LoginEvent(LoginModalPanel.this, target));

            } else {
                error(getString("authentication.failed"));
                target.add(modalContainer);
            }
        }
    };
}
 
Example 9
Source Project: webanno   Source File: CurationPage.java    License: Apache License 2.0 6 votes vote down vote up
public CurationPage()
{
    super();
    LOG.debug("Setting up curation page without parameters");
    commonInit();
    
    Map<String, StringValue> fragmentParameters = Session.get()
            .getMetaData(SessionMetaData.LOGIN_URL_FRAGMENT_PARAMS);
    if (fragmentParameters != null) {
        // Clear the URL fragment parameters - we only use them once!
        Session.get().setMetaData(SessionMetaData.LOGIN_URL_FRAGMENT_PARAMS, null);
        
        StringValue project = fragmentParameters.get(PAGE_PARAM_PROJECT_ID);
        StringValue document = fragmentParameters.get(PAGE_PARAM_DOCUMENT_ID);
        StringValue focus = fragmentParameters.get(PAGE_PARAM_FOCUS);
        
        handleParameters(null, project, document, focus, false);
    }
}
 
Example 10
Source Project: webanno   Source File: LoginPage.java    License: Apache License 2.0 6 votes vote down vote up
private void setDefaultResponsePageIfNecessary()
{
    // This does not work because it was Spring Security that intercepted the access, not
    // Wicket continueToOriginalDestination();

    String redirectUrl = getRedirectUrl();
    
    if (redirectUrl == null || redirectUrl.contains(".IBehaviorListener.")
            || redirectUrl.contains("-logoutPanel-")) {
        log.debug("Redirecting to welcome page");
        setResponsePage(getApplication().getHomePage());
    }
    else {
        log.debug("Redirecting to saved URL: [{}]", redirectUrl);
        if (isNotBlank(form.urlfragment) && form.urlfragment.startsWith("!")) {
            Url url = Url.parse("http://dummy?" + form.urlfragment.substring(1));
            UrlRequestParametersAdapter adapter = new UrlRequestParametersAdapter(url);
            LinkedHashMap<String, StringValue> params = new LinkedHashMap<>();
            for (String name : adapter.getParameterNames()) {
                params.put(name, adapter.getParameterValue(name));
            }
            Session.get().setMetaData(SessionMetaData.LOGIN_URL_FRAGMENT_PARAMS, params);
        }
        throw new NonResettingRestartException(redirectUrl);
    }
}
 
Example 11
Source Project: webanno   Source File: AnnotationPage.java    License: Apache License 2.0 6 votes vote down vote up
public AnnotationPage()
{
    super();
    LOG.debug("Setting up annotation page without parameters");

    setModel(Model.of(new AnnotatorStateImpl(Mode.ANNOTATION)));
    // Ensure that a user is set
    getModelObject().setUser(userRepository.getCurrentUser());

    Map<String, StringValue> fragmentParameters = Session.get()
            .getMetaData(SessionMetaData.LOGIN_URL_FRAGMENT_PARAMS);
    StringValue focus = StringValue.valueOf(0);
    if (fragmentParameters != null) {
        // Clear the URL fragment parameters - we only use them once!
        Session.get().setMetaData(SessionMetaData.LOGIN_URL_FRAGMENT_PARAMS, null);

        StringValue project = fragmentParameters.get(PAGE_PARAM_PROJECT_ID);
        StringValue projectName = fragmentParameters.get(PAGE_PARAM_PROJECT_NAME);
        StringValue document = fragmentParameters.get(PAGE_PARAM_DOCUMENT_ID);
        StringValue name = fragmentParameters.get(PAGE_PARAM_DOCUMENT_NAME);
        focus = fragmentParameters.get(PAGE_PARAM_FOCUS);

        handleParameters(project, projectName, document, name, focus, false);
    }
    commonInit(focus);
}
 
Example 12
Source Project: sakai   Source File: GradebookPage.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * Getter for the GradebookUiSettings. Used to store a few UI related settings in the PreferencesService (serialized to db)
 *
 */
public GradebookUiSettings getUiSettings() {

	GradebookUiSettings settings = (GradebookUiSettings) Session.get().getAttribute("GBNG_UI_SETTINGS");

	if (settings == null) {
		settings = new GradebookUiSettings();
		settings.initializeCategoryColors(this.businessService.getGradebookCategories());
		settings.setCategoryColor(getString(GradebookPage.UNCATEGORISED), GradebookUiSettings.generateRandomRGBColorString(null));
		setUiSettings(settings);
	}

	// See if the user has a database-persisted preference for Group by Category
	String userGbUiCatPref = this.businessService.getUserGbPreference("GROUP_BY_CAT");
	if (StringUtils.isNotBlank(userGbUiCatPref)) {
		settings.setCategoriesEnabled(new Boolean(userGbUiCatPref));
	}
	else {
		settings.setCategoriesEnabled(this.businessService.categoriesAreEnabled());
	}

	return settings;
}
 
Example 13
Source Project: ontopia   Source File: SignInPage.java    License: Apache License 2.0 6 votes vote down vote up
public SignInPage(PageParameters params) {
super(params);
    
add(new StartPageHeaderPanel("header"));
add(new FooterPanel("footer"));

   add(new Label("title", new ResourceModel("page.title.signin")));

   add(new Label("message", new AbstractReadOnlyModel<String>() {
       @Override
       public String getObject() {
         OntopolySession session = (OntopolySession)Session.findOrCreate();
         return session.getSignInMessage();
       }
     }));
   add(new SignInForm("form"));
 }
 
Example 14
Source Project: ontopia   Source File: LockPanel.java    License: Apache License 2.0 6 votes vote down vote up
protected boolean acquireLock() {
  // create lock id and lock key
  OntopolySession session = (OntopolySession)Session.get();
  String lockerId = session.getLockerId(getRequest());
  LockManager.Lock lock = session.lock((Topic)getDefaultModelObject(), lockerId);
  this.lockedBy = lock.getLockedBy();
  this.lockedAt = new Date(lock.getLockTime()).toString();
  this.lockKey = lock.getLockKey();
  if (!lock.ownedBy(lockerId)) {
    this.lockedByOther = true;
    //! System.out.println("Got lock: false: " + lock);
    return false;
  } else {
    //! System.out.println("Got lock: true" + lock);
    return true;
  }
}
 
Example 15
@Override
protected void onConfigure() {
	super.onConfigure();
	
	FeedbackMessages feedbackMessages = Session.get().getFeedbackMessages();
	
	if(feedbackMessages.hasMessage(getFeedbackMessageFilter())){
		messageHolder.setVisible(true);
		List<FeedbackMessage> messages = feedbackMessages.messages(getFeedbackMessageFilter());
		FeedbackMessage message = messages.get(0);
		onDisplayError(message);
		message.markRendered();
	} else {
		messageHolder.setVisible(false);
	}
}
 
Example 16
Source Project: AppStash   Source File: LoginModalPanel.java    License: Apache License 2.0 6 votes vote down vote up
private LoginPanel loginPanel() {
    return new LoginPanel("loginPanel") {

        @Override
        protected boolean isSubmitLinkVisible() {
            return false;
        }

        @Override
        protected void submitLoginForm(AjaxRequestTarget target, LoginInfo loginInfo) {
            boolean authenticate = authenticate(loginInfo);
            if (authenticate) {
                Session.get().info(getString("authentication.success"));

                setResponsePage(getPage());
                send(getPage(), Broadcast.BREADTH, new LoginEvent(LoginModalPanel.this, target));

            } else {
                error(getString("authentication.failed"));
                target.add(modalContainer);
            }
        }
    };
}
 
Example 17
public NewVersionsAdditionalEmailHtmlNotificationDemoPage(PageParameters parameters) {
	super(parameters);
	
	User user = userService.getByUserName(ConsoleNotificationIndexPage.DEFAULT_USERNAME);
	if (user == null) {
		LOGGER.error("There is no user available");
		Session.get().error(getString("console.notifications.noDataAvailable"));
		
		throw new RestartResponseException(ConsoleNotificationIndexPage.class);
	}
	
	Collection<EmailAddress> emailAddresses = user.getAdditionalEmails();
	if (emailAddresses == null || emailAddresses.isEmpty()) {
		LOGGER.error("There is no additional email address available");
		Session.get().error(getString("console.notifications.noDataAvailable"));
		
		throw new RestartResponseException(ConsoleNotificationIndexPage.class);
	}
	EmailAddress additionalEmail = Iterables.get(emailAddresses, 0);
	
	List<ArtifactVersionNotification> notifications = userService.listRecentNotifications(user);
	
	IModel<List<ArtifactVersionNotification>> notificationsModel = new ListModel<ArtifactVersionNotification>(notifications);
	add(new NewVersionsHtmlNotificationPanel("htmlPanel", notificationsModel,
			new GenericEntityModel<Long, EmailAddress>(additionalEmail)));
}
 
Example 18
Source Project: JPPF   Source File: HeaderPanel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 */
public HeaderPanel() {
  super("jppf.header");
  final String user = JPPFWebSession.getSignedInUser();
  final Locale locale = Session.get().getLocale();
  final String s = (user != null)
    ? LocalizationUtils.getLocalized(getClass().getName(), "jppf.header.user.label", locale) + " " + user
    : LocalizationUtils.getLocalized(getClass().getName(), "jppf.header.not.signed_in.label", locale);
  add(new Label("jppf.header.user", Model.of(s)));
  final Form<String> form = new Form<>("login.signout.form");
  final AjaxButton link = new AjaxButton("login.signout.link", Model.of("Sign out")) {
    @Override
    protected void onSubmit(final AjaxRequestTarget target) {
      AuthenticatedWebSession.get().signOut();
      AuthenticatedWebSession.get().invalidate();
      target.add(getForm());
      setResponsePage(getApplication().getHomePage());
    }
  };

  form.add(link);
  showIPCheckBox = new AjaxCheckBox("jppf.header.show.ip", Model.of(JPPFWebSession.get().isShowIP())) {
    @Override
    protected void onUpdate(final AjaxRequestTarget target) {
      final Boolean newSelection = this.getModelObject();
      JPPFWebSession.get().setShowIP((newSelection != null) && newSelection);
    }
  };
  form.add(showIPCheckBox);
  form.setVisible(user != null);
  link.setVisible(user != null);
  add(form);
}
 
Example 19
/**
 * Get the expansion for the session.
 * 
 * @return expansion
 */
public static EntityTreeExpansionState get() {
	EntityTreeExpansionState expansion = Session.get().getMetaData(KEY);
    if (expansion == null) {
        expansion = new EntityTreeExpansionState();
        Session.get().setMetaData(KEY, expansion);
    }
    return expansion;
}
 
Example 20
public NewVersionsHtmlNotificationDemoPage(PageParameters parameters) {
	super(parameters);
	
	User user = userService.getByUserName(ConsoleNotificationIndexPage.DEFAULT_USERNAME);
	if (user == null) {
		LOGGER.error("There is no user or email address available");
		Session.get().error(getString("console.notifications.noDataAvailable"));
		
		throw new RestartResponseException(ConsoleNotificationIndexPage.class);
	}
	List<ArtifactVersionNotification> notifications = userService.listRecentNotifications(user);
	
	IModel<List<ArtifactVersionNotification>> notificationsModel = new ListModel<ArtifactVersionNotification>(notifications);
	add(new NewVersionsHtmlNotificationPanel("htmlPanel", notificationsModel));
}
 
Example 21
Source Project: inception   Source File: MenuBar.java    License: Apache License 2.0 5 votes vote down vote up
public MenuBar(String aId)
{
    super(aId);
    
    add(new BookmarkablePageLink<>("homeLink", getApplication().getHomePage()));

    add(new BookmarkablePageLink<>("dashboardLink", ProjectDashboardPage.class)
            .add(visibleWhen(() ->  Session.get().getMetaData(CURRENT_PROJECT) != null)));

    add(new BookmarkablePageLink<>("projectsLink", ProjectsOverviewPage.class)
            .add(visibleWhen(() -> userRepository.getCurrentUser() != null)));

    add(new BookmarkablePageLink<>("adminLink", AdminDashboardPage.class)
            .add(visibleWhen(this::adminAreaAccessRequired))); 
}
 
Example 22
Source Project: nextreports-server   Source File: AnalysisDataProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public long size() {
	try {
		return analysisReader.getRowCount(analysis);
	} catch (AnalysisException ex) {
		LOG.error(ex.getMessage(), ex);
		Session.get().error(ex.getMessage());
		return 0;
	}
}
 
Example 23
Source Project: inception   Source File: SearchPage.java    License: Apache License 2.0 5 votes vote down vote up
public SearchPage()
{
    project = Session.get().getMetaData(SessionMetaData.CURRENT_PROJECT);
    if (project == null) {
        abort();
    }

    add(new SearchForm("searchForm"));

    List<IColumn<ExternalSearchResult, String>> columns = new ArrayList<>();

    columns.add(new AbstractColumn<ExternalSearchResult, String>(new Model<>("Results"))
    {
        private static final long serialVersionUID = 3795885786416467291L;

        @Override
        public void populateItem(Item<ICellPopulator<ExternalSearchResult>> cellItem,
                String componentId, IModel<ExternalSearchResult> model)
        {
            @SuppressWarnings("rawtypes")
            Item rowItem = cellItem.findParent( Item.class );
            int rowIndex = rowItem.getIndex();
            ResultRowView rowView = new ResultRowView(componentId, rowIndex + 1, model);
            cellItem.add(rowView);
        }
    });

    dataProvider = new ExternalResultDataProvider(externalSearchService,
            userRepository.getCurrentUser());

    dataTableContainer = new WebMarkupContainer("dataTableContainer");
    dataTableContainer.setOutputMarkupId(true);
    add(dataTableContainer);

    dataTableContainer.add(new DefaultDataTable<>("resultsTable", columns, dataProvider, 10));
}
 
Example 24
Source Project: onedev   Source File: PasswordEditPanel.java    License: MIT License 5 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	
	PasswordEditBean bean = new PasswordEditBean();
	
	Set<String> excludedProperties = new HashSet<>();
	
	// in case administrator changes password we do not ask for old password
	if (SecurityUtils.isAdministrator()) 
		excludedProperties.add("oldPassword");
	
	Form<?> form = new Form<Void>("form") {

		@Override
		protected void onSubmit() {
			super.onSubmit();
			getUser().setPassword(AppLoader.getInstance(PasswordService.class).encryptPassword(bean.getNewPassword()));
			OneDev.getInstance(UserManager.class).save(getUser(), null);
			Session.get().success("Password has been changed");

			bean.setOldPassword(null);
			
			setResponsePage(getPage().getClass(), getPage().getPageParameters());
		}

	};
	add(form);
	
	form.add(BeanContext.edit("editor", bean, excludedProperties, true));
}
 
Example 25
Source Project: onedev   Source File: InvalidPullRequestPage.java    License: MIT License 5 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	add(new Link<Void>("delete") {

		@Override
		public void onClick() {
			PullRequest request = requestModel.getObject();
			OneDev.getInstance(PullRequestManager.class).delete(request);
			
			Session.get().success("Pull request #" + request.getNumber() + " deleted");
			
			String redirectUrlAfterDelete = WebSession.get().getRedirectUrlAfterDelete(PullRequest.class);
			if (redirectUrlAfterDelete != null)
				throw new RedirectToUrlException(redirectUrlAfterDelete);
			else
				setResponsePage(ProjectPullRequestsPage.class, ProjectPullRequestsPage.paramsOf(getProject()));
		}

		@Override
		protected void onConfigure() {
			super.onConfigure();
			setVisible(SecurityUtils.canManage(requestModel.getObject().getTargetProject()));
		}
		
	}.add(new ConfirmClickModifier("Do you really want to delete pull request #" + requestModel.getObject().getNumber() + "?")));
}
 
Example 26
Source Project: onedev   Source File: PullRequestDetailPage.java    License: MIT License 5 votes vote down vote up
private WebMarkupContainer newManageContainer() {
	WebMarkupContainer container = new WebMarkupContainer("manage");
	container.setVisible(SecurityUtils.canManage(getPullRequest().getTargetProject()));
	container.add(new Link<Void>("synchronize") {

		@Override
		protected void onConfigure() {
			super.onConfigure();
			setVisible(getPullRequest().isOpen());
		}

		@Override
		public void onClick() {
			getPullRequestManager().check(getPullRequest());
			if (getPullRequest().getCheckError() == null) 
				Session.get().success("Pull request is synchronized");
		}
		
	});
	container.add(new Link<Void>("delete") {

		@Override
		public void onClick() {
			PullRequest request = getPullRequest();
			getPullRequestManager().delete(request);
			Session.get().success("Pull request #" + request.getNumber() + " deleted");
			
			String redirectUrlAfterDelete = WebSession.get().getRedirectUrlAfterDelete(PullRequest.class);
			if (redirectUrlAfterDelete != null)
				throw new RedirectToUrlException(redirectUrlAfterDelete);
			else
				setResponsePage(ProjectPullRequestsPage.class, ProjectPullRequestsPage.paramsOf(getProject()));
		}
		
	}.add(new ConfirmClickModifier("Do you really want to delete this pull request?")));
	return container;
}
 
Example 27
Source Project: onedev   Source File: NewProjectPage.java    License: MIT License 5 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	
	Project project = new Project();
	
	Collection<String> properties = Sets.newHashSet("name", "description", "issueManagementEnabled");
	
	BeanEditor editor = BeanContext.edit("editor", project, properties, false);
	
	Form<?> form = new Form<Void>("form") {

		@Override
		protected void onSubmit() {
			super.onSubmit();
			
			ProjectManager projectManager = OneDev.getInstance(ProjectManager.class);
			Project projectWithSameName = projectManager.find(project.getName());
			if (projectWithSameName != null) {
				editor.error(new Path(new PathNode.Named("name")),
						"This name has already been used by another project");
			} else {
				projectManager.create(project);
				Session.get().success("New project created");
				setResponsePage(ProjectBlobPage.class, ProjectBlobPage.paramsOf(project));
			}
		}
		
	};
	form.add(editor);
	
	add(form);
}
 
Example 28
Source Project: onedev   Source File: NewMilestonePage.java    License: MIT License 5 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();

	Milestone milestone = new Milestone();
	
	BeanEditor editor = BeanContext.edit("editor", milestone);
	Form<?> form = new Form<Void>("form") {

		@Override
		protected void onSubmit() {
			super.onSubmit();

			MilestoneManager milestoneManager = OneDev.getInstance(MilestoneManager.class);
			Milestone milestoneWithSameName = milestoneManager.find(getProject(), milestone.getName());
			if (milestoneWithSameName != null) {
				editor.error(new Path(new PathNode.Named("name")),
						"This name has already been used by another milestone in the project");
			} 
			if (editor.isValid()){
				milestone.setProject(getProject());
				milestoneManager.save(milestone);
				Session.get().success("New milestone created");
				setResponsePage(MilestoneDetailPage.class, MilestoneDetailPage.paramsOf(milestone, null));
			}
			
		}
		
	};
	form.add(editor);
	add(form);
}
 
Example 29
Source Project: onedev   Source File: InvalidCodeCommentPage.java    License: MIT License 5 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	add(new Link<Void>("delete") {

		@Override
		public void onClick() {
			OneDev.getInstance(CodeCommentManager.class).delete(getCodeComment());
			
			Session.get().success("Code comment #" + getCodeComment().getId() + " deleted");
			
			String redirectUrlAfterDelete = WebSession.get().getRedirectUrlAfterDelete(CodeComment.class);
			if (redirectUrlAfterDelete != null)
				throw new RedirectToUrlException(redirectUrlAfterDelete);
			else
				setResponsePage(ProjectCodeCommentsPage.class, ProjectCodeCommentsPage.paramsOf(getProject()));
			
		}

		@Override
		protected void onConfigure() {
			super.onConfigure();
			setVisible(SecurityUtils.canManageCodeComments(getCodeComment().getProject()));
		}
		
	}.add(new ConfirmClickModifier("Really want to delete this code comment?")));
}
 
Example 30
Source Project: Orienteer   Source File: UserOnlineModule.java    License: Apache License 2.0 5 votes vote down vote up
private ISessionListener createUserOnlineListener() {
    return new ISessionListener() {
        @Override
        public void onCreated(Session session) {}

        @Override
        public void onUnbound(final String sessionId) {
            DBClosure.sudoConsumer(db -> {
                String sql = String.format("update %s set %s = ? where %s = ?", OUser.CLASS_NAME,
                        PROP_ONLINE, PROP_LAST_SESSION_FIELD);
                db.command(new OCommandSQL(sql)).execute(false, sessionId);
            });
        }
    };
}