예제 #1
0
  public void doExecute(PageParameters parameters) {

    final String login = parameters.getString("login");
    final String clearPassword = parameters.getString("password");

    WicketSession session = WicketSession.get();
    //		GameService gameService = WicketApplication.get().getGameService();
    UserService userService = WicketApplication.get().getUserService();
    //		GameTO gTO = null;
    UserTO uTO = null;

    if (session.signIn(login, clearPassword)) {
      System.out.println("session.signIn");
      session.bind();
      LoginResultTO loginResultTO = session.getLoginResultTO();

      try {
        //				gTO =
        // gameService.findGameById(userService.findUserById(loginResultTO.getUserId()).getGameId());
        uTO = userService.findUserById(loginResultTO.getUserId());
      } catch (InstanceNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      XStream xf = xStreamFactory.createXStream();
      this.selement = xf.toXML(uTO);
      //			this.element = TOToXMLConversor.toXML(uTO);
      //			this.element = TOToXMLConversor.toXML(loginResultTO);
      //			if( gTO!= null )
      //				this.element.addContent(TOToXMLConversor.toXML(gTO));
    } else {
      System.out.println("not session.signIn");
    }
  }
  public TokenQueue(PageParameters parameters) {
    super(parameters);

    try {
      slimservice.tokenQueue(
          parameters.getString("userid"),
          parameters.getString("access_token"),
          parameters.getString("access_token_secret"));
    } catch (TwitterException e) {
      error("Twitter API Error...");
    }
  }
예제 #3
0
 private static StyleInfo extractStyle(
     PageParameters params, Catalog catalog, FeatureTypeInfo layer) {
   if (params.containsKey("style")) {
     String style = params.getString("style");
     return catalog.getStyleByName(style);
   } else {
     List<LayerInfo> styles = catalog.getLayers(layer);
     if (styles.size() > 0) {
       return styles.get(0).getDefaultStyle();
     } else {
       return null;
     }
   }
 }
예제 #4
0
  public BasePage(PageParameters param, String titleKey) {
    super(param);

    if (param != null && !param.isEmpty()) {
      try {
        if (param.containsKey("id")) {
          id = param.getLong("id");
        }
      } catch (StringValueConversionException exc) {
        exc.printStackTrace();
      }
    }

    initialize(titleKey);
  }
예제 #5
0
 private void updatePost(Post post) {
   try {
     post.setModified(new Date());
     logger.debug("Updating post: " + post);
     Post updatedPost = postService.update(post);
     setResponsePage(
         ListPostPage.class,
         PageParametersUtils.fromStringMessage(
             getString("post.list.updated", new Model(updatedPost))));
   } catch (Exception e) {
     logger.error("Error while updating post", e);
     PageParameters parameters = PageParametersUtils.fromException(e);
     parameters.put(EditPostPage.PARAM_POST_KEY, post);
     throw new RestartResponseException(EditPostPage.class, parameters);
   }
 }
예제 #6
0
  public void layout() {
    super.layout();

    add(CSSPackageResource.getHeaderContribution(getClass(), "change.css"));

    Project project = getProject();
    String id = getPageParameters().getString("id");

    if (project == null) {
      notFoundError();
      return;
    }

    String prefix = "";
    Project root = getProject();
    File searchDir = getStorage().getWorkingDirectory(getProject());
    while (root.getParent() != null) {
      prefix = searchDir.getName() + File.separatorChar + prefix;
      root = root.getParent();
      searchDir = searchDir.getParentFile();
    }
    final String stripPrefix = prefix;

    ChangeSet changeSet = Manager.getInstance().getScmService().getChangeSet(root, id);
    if (changeSet == null) {
      notFoundError();
      return;
    }

    revision = changeSet.getId();
    ((HibernateRequestCycle) getRequestCycle()).getHibernateSession().refresh(changeSet);

    if (changeSet.getPrevious() != null) {
      PageParameters params = getProjectPageParameters();
      params.add("id", changeSet.getPrevious().getId());

      addLink(new BookmarkableMenuLink(getClass(), params, "\u25c0 previous changeset"));
    }
    if (changeSet.getNext() != null) {
      PageParameters params = getProjectPageParameters();
      params.add("id", changeSet.getNext().getId());

      addLink(new BookmarkableMenuLink(getClass(), params, "\u25ba next changeset"));
    }

    add(new ChangeSetPanel("changeset", changeSet, stripPrefix));
  }
  public ContributionCommentSuccessPage(PageParameters parameters) {
    super(parameters);

    contributionId = parameters.getInt("contribution");

    boolean success =
        HibernateUtils.wrapTransaction(
            getHibernateSession(),
            new HibernateTask() {
              public boolean run(Session session) {
                contribution =
                    (Contribution)
                        session
                            .createQuery("select c from Contribution as c where c.id = :id")
                            .setInteger("id", contributionId)
                            .uniqueResult();
                return true;
              }
            });

    if (!success) {
      logger.info("unknown contribution of id " + contributionId);
      throw new RestartResponseAtInterceptPageException(NotFoundPage.class);
    }

    initializeLocation(getNavMenu().getLocationByKey("teacherIdeas"));

    add(
        new LocalizedText(
            "comment-header",
            "contribution.comment.success",
            new Object[] {HtmlUtils.encode(contribution.getTitle())}));

    add(
        new LocalizedText(
            "comment-success",
            "contribution.comment.successRedirection",
            new Object[] {
              ContributionPage.getLinker(contributionId).getHref(getPageContext(), getPhetCycle()),
              REDIRECTION_DELAY_SECONDS
            }));

    Label redirector = new Label("redirector", "");
    redirector.add(
        new AttributeModifier(
            "content",
            true,
            new Model<String>(
                REDIRECTION_DELAY_SECONDS
                    + ";url="
                    + ContributionPage.getLinker(contributionId)
                        .getRawUrl(getPageContext(), getPhetCycle()))));
    add(redirector);

    setTitle(
        StringUtils.messageFormat(
            PhetLocalizer.get().getString("contribution.comment.success", this),
            new Object[] {HtmlUtils.encode(contribution.getTitle())}));
  }
예제 #8
0
    public void onSubmit() {
      Session session = ((HibernateStorage) getStorage()).getHibernateSession();
      Transaction tx = session.beginTransaction();
      user = (org.headsupdev.agile.api.User) session.merge(user);

      ((StoredUser) user).setPassword(pass1);
      if (me) {
        ((HeadsUpSession) getSession()).setUser(user);
      }

      session.update(user);
      tx.commit();

      PageParameters params = new PageParameters();
      params.add("username", user.getUsername());
      setResponsePage(getPageClass("account"), params);
    }
예제 #9
0
 private void redirectToCreateDownloadPage() {
   // link from upload center
   if (isCreateLinkFromUploadCenter() && isAuthor()) {
     Download newDownload = downloadService.newDownloadEntity();
     newDownload.setUrl(params.getString("create"));
     IModel<Download> downloadModel = Model.of(newDownload);
     setResponsePage(new DownloadEditPage(downloadModel));
   }
 }
예제 #10
0
  public UpdateAccountPage(PageParameters pageParameters) {
    final String accountNo = pageParameters.getString("accountNo");

    add(new Label("accountNo", accountNo));

    final Account account = accountServiceImpl.getAccountByAccountNumber(Long.parseLong(accountNo));

    add(new Label("balance", account.getBalance().toString()));
    add(new AccountTransactionForm("accountTransactionForm", account));
  }
예제 #11
0
 private static StyleInfo extractStyle(PageParameters params, Catalog catalog, LayerInfo layer) {
   if (params.containsKey("style")) {
     String style = params.getString("style");
     String[] parts = style.split(":", 2);
     if (parts.length == 1) {
       return catalog.getStyleByName(parts[0]);
     } else if (parts.length == 2) {
       return catalog.getStyleByName(parts[0], parts[1]);
     } else {
       throw new IllegalStateException(
           "After splitting, there should be only 1 or 2 parts.  Got: " + Arrays.toString(parts));
     }
   } else {
     if (layer != null) {
       return layer.getDefaultStyle();
     } else {
       return null;
     }
   }
 }
예제 #12
0
 private static LayerInfo extractLayer(PageParameters params, Catalog catalog) {
   if (params.containsKey("layer")) {
     String name = params.getString("layer");
     return catalog.getLayerByName(name);
   } else {
     // TODO: Revisit this behavior
     // give some slight preference to the topp:states layer to make
     // demoing a bit more consistent.
     LayerInfo states = catalog.getLayerByName("topp:states");
     if (states != null) {
       return states;
     } else {
       List<LayerInfo> layers = catalog.getLayers();
       if (layers.size() > 0) {
         return layers.get(0);
       } else {
         return null;
       }
     }
   }
 }
예제 #13
0
 private static FeatureTypeInfo extractLayer(PageParameters params, Catalog catalog) {
   if (params.containsKey("layer")) {
     String[] name = params.getString("layer").split(":", 2);
     return catalog.getResourceByName(name[0], name[1], FeatureTypeInfo.class);
   } else {
     // TODO: Revisit this behavior
     // give some slight preference to the topp:states layer to make
     // demoing a bit more consistent.
     FeatureTypeInfo states = catalog.getResourceByName("topp", "states", FeatureTypeInfo.class);
     if (states != null) {
       return states;
     } else {
       List<FeatureTypeInfo> layers = catalog.getResources(FeatureTypeInfo.class);
       if (layers.size() > 0) {
         return layers.get(0);
       } else {
         return null;
       }
     }
   }
 }
 /**
  * Constructor called by Wicket with an auth response (since the response has parameters
  * associated with it... LOTS of them!). And, by the way, the auth response is the Request for
  * this classl (not to be confusing).
  *
  * @param pageParameters The request parameters (which are the response parameters from the OP).
  */
 public OpenIdRegistrationSavePage(final PageParameters pageParameters) {
   RegistrationModel registrationModel = new RegistrationModel();
   if (!pageParameters.isEmpty()) {
     //
     // If this is a return trip (the OP will redirect here once authentication
     /// is compelete), then verify the response. If it looks good, send the
     /// user to the RegistrationSuccessPage. Otherwise, display a message.
     //
     final String isReturn = pageParameters.getString("is_return");
     if (isReturn.equals("true")) {
       //
       // Grab the session object so we can let openid4java do verification.
       //
       final MakotoOpenIdAwareSession session = (MakotoOpenIdAwareSession) getSession();
       final DiscoveryInformation discoveryInformation = session.getDiscoveryInformation();
       //
       // Delegate to the Service object to do verification. It will return
       /// the RegistrationModel to use to display the information that was
       /// retrieved from the OP about the User-Supplied identifier. The
       /// RegistrationModel reference will be null if there was a problem
       /// (check the logs for more information if this happens).
       //
       registrationModel =
           RegistrationService.processReturn(
               discoveryInformation, pageParameters, RegistrationService.getReturnToUrl());
       if (registrationModel == null) {
         //
         // Oops, something went wrong. Display a message on the screen.
         /// Check the logs for more information.
         //
         error(
             "Open ID Confirmation Failed. No information was retrieved from the OpenID Provider. You will have to enter all information by hand into the text fields provided.");
       }
     }
   }
   add(new OpenIdRegistrationInformationDisplayForm("form", registrationModel));
 }
예제 #15
0
  public SimulationFAQPage(PageParameters parameters) {
    super(parameters);

    final String simName = parameters.getString("simulation");

    Result<FAQList> faqListResult =
        HibernateUtils.resultCatchTransaction(
            getHibernateSession(),
            new Task<FAQList>() {
              public FAQList run(Session session) {
                LocalizedSimulation lsim =
                    HibernateUtils.getBestSimulation(session, getMyLocale(), simName);
                simTitle = lsim.getTitle();
                Simulation simulation = lsim.getSimulation();
                if (!simulation.isFaqVisible() || simulation.getFaqList() == null) {
                  throw new TaskException("Simulation does not have a FAQ visible");
                }
                return simulation.getFaqList();
              }
            });

    if (!faqListResult.success) {
      throw new RestartResponseAtInterceptPageException(NotFoundPage.class);
    }

    // TODO: better way of handling look-ups for message-formatted strings (with locales).
    // consolidate into PhetLocalizer
    String title =
        StringUtils.messageFormat(
            getPhetLocalizer().getString("simulation.faq.title", this),
            new Object[] {simTitle},
            getMyLocale());
    setTitle(title);

    add(new Label("faq-header", title));

    // TODO: meta description!
    //        setMetaDescription( ogDescription );

    add(new FAQPanel("faq-panel", faqListResult.value.getName(), getPageContext()));

    initializeLocationWithSet(new ArrayList<NavLocation>());
  }
예제 #16
0
  public FarmingGraphPage(PageParameters parameters) throws Exception {
    final int farmStrategyID = parameters.getInt("farmStrategyID");
    farmStrategy = farmStrategyBO.getById(FarmStrategyId.farmStrategyId(farmStrategyID));
    add(new Label("strategyName", farmStrategy.getStrategyName()));
    add(
        ArmoryImage.createArmoryImage(
            (AuctioneerWebApp) getApplication(), "icon", farmStrategy.getIconItem()));
    setPageTitle("Farming - " + farmStrategy.getStrategyName());

    final PropertyModel<List<FarmStrategyLoot>> materialListModel =
        new PropertyModel<List<FarmStrategyLoot>>(this, "farmStrategy.loot");

    ListView<FarmStrategyLoot> listView =
        new ListView<FarmStrategyLoot>("lootList", materialListModel) {
          private static final long serialVersionUID = 1L;

          @Override
          protected void populateItem(ListItem<FarmStrategyLoot> item) {

            final FarmStrategyLoot loot = item.getModelObject();
            PageParameters params = new PageParameters();
            params.add("itemID", String.valueOf(loot.getItem().getArmoryId().toInt()));
            final Link<String> lootLine =
                new BookmarkablePageLink<String>("lootLine", PriceWatchGraphPage.class, params);

            lootLine.add(new WowheadTooltip(loot.getItem().getArmoryId()));
            lootLine.add(
                ArmoryImage.createArmoryImage(
                    (AuctioneerWebApp) getApplication(), "icon", loot.getItem()));
            final String name = loot.getItemCount() + " x " + loot.getItem().getItemName();
            lootLine.add(new Label("name", name));
            item.add(lootLine);
          }
        };
    listView.setReuseItems(true);
    listView.setOutputMarkupId(true);
    add(listView);

    add(new Label("minProfit", goldToString(farmStrategy.getTotalSafeProfit())));
    add(new Label("medianProfit", goldToString(farmStrategy.getTotalProfit())));
  }
예제 #17
0
 @Override
 public void onSubmit() {
   PageParameters p = new PageParameters();
   p.put("nextpage", nextpage);
   setResponsePage(getPage().getClass(), p);
 }
예제 #18
0
  public Publicline(final PageParameters parameters) {
    super(parameters);
    nextpage = parameters.getAsLong("nextpage");
    username = parameters.getString("username");
    if (username == null) {
      username = "******";
      add(new Label("h2name", "Public"));
    } else {
      add(new Label("h2name", username + "'s"));
    }

    Timeline timeline = getUserline(username, nextpage);
    List<Tweet> tweets = timeline.getView();
    if (tweets.size() > 0) {
      add(new ListView<Tweet>("tweetlist", tweets) {
            @Override
            public void populateItem(final ListItem<Tweet> listitem) {
              listitem.add(
                  new Link("link") {
                    @Override
                    public void onClick() {
                      PageParameters p = new PageParameters();
                      p.put("username", listitem.getModel().getObject().getUname());
                      setResponsePage(Publicline.class, p);
                    }
                  }.add(new Label("tuname", listitem.getModel().getObject().getUname())));
              listitem.add(new Label("tbody", ": " + listitem.getModel().getObject().getBody()));
            }
          })
          .setVersioned(false);
      Long linktopaginate = timeline.getNextview();
      if (linktopaginate != null) {
        nextpage = linktopaginate;
        WebMarkupContainer pagediv = new WebMarkupContainer("pagedown");
        PageForm pager = new PageForm("pageform");
        pagediv.add(pager);
        add(pagediv);
      } else {
        add(
            new WebMarkupContainer("pagedown") {
              @Override
              public boolean isVisible() {
                return false;
              }
            });
      }
    } else {
      ArrayList<String> hack = new ArrayList<String>(1);
      hack.add("There are no tweets yet. Log in and post one!");
      add(new ListView<String>("tweetlist", hack) {
            @Override
            public void populateItem(final ListItem<String> listitem) {
              listitem.add(
                  new Link("link") {
                    @Override
                    public void onClick() {}
                  }.add(new Label("tuname", "")));
              listitem.add(new Label("tbody", listitem.getModel().getObject()));
            }
          })
          .setVersioned(false);
      add(
          new WebMarkupContainer("pagedown") {
            @Override
            public boolean isVisible() {
              return false;
            }
          });
    }
  }
예제 #19
0
  private void setup(PageParameters params) {
    setupPage("", "");
    // check to see if we should display a login message
    boolean authenticateView = GitBlit.getBoolean(Keys.web.authenticateViewPages, true);
    if (authenticateView && !GitBlitWebSession.get().isLoggedIn()) {
      authenticationError("Please login");
      return;
    }

    String projectName = WicketUtils.getProjectName(params);
    if (StringUtils.isEmpty(projectName)) {
      throw new GitblitRedirectException(GitBlitWebApp.get().getHomePage());
    }

    ProjectModel project = getProjectModel(projectName);
    if (project == null) {
      throw new GitblitRedirectException(GitBlitWebApp.get().getHomePage());
    }

    add(new Label("projectTitle", project.getDisplayName()));
    add(new Label("projectDescription", project.description));

    String feedLink =
        SyndicationServlet.asLink(
            getRequest().getRelativePathPrefixToContextRoot(), projectName, null, 0);
    add(new ExternalLink("syndication", feedLink));

    add(
        WicketUtils.syndicationDiscoveryLink(
            SyndicationServlet.getTitle(project.getDisplayName(), null), feedLink));

    // project markdown message
    String pmessage = transformMarkdown(project.projectMarkdown);
    Component projectMessage =
        new Label("projectMessage", pmessage)
            .setEscapeModelStrings(false)
            .setVisible(pmessage.length() > 0);
    add(projectMessage);

    // markdown message above repositories list
    String rmessage = transformMarkdown(project.repositoriesMarkdown);
    Component repositoriesMessage =
        new Label("repositoriesMessage", rmessage)
            .setEscapeModelStrings(false)
            .setVisible(rmessage.length() > 0);
    add(repositoriesMessage);

    UserModel user = GitBlitWebSession.get().getUser();
    if (user == null) {
      user = UserModel.ANONYMOUS;
    }
    int daysBack = params == null ? 0 : WicketUtils.getDaysBack(params);
    if (daysBack < 1) {
      daysBack = GitBlit.getInteger(Keys.web.activityDuration, 7);
    }
    // reset the daysback parameter so that we have a complete project
    // repository list.  the recent activity will be built up by the
    // reflog utils.
    params.remove("db");

    List<RepositoryModel> repositories = getRepositories(params);
    Collections.sort(
        repositories,
        new Comparator<RepositoryModel>() {
          @Override
          public int compare(RepositoryModel o1, RepositoryModel o2) {
            // reverse-chronological sort
            return o2.lastChange.compareTo(o1.lastChange);
          }
        });

    addActivity(user, repositories, getString("gb.recentActivity"), daysBack);

    if (repositories.isEmpty()) {
      add(new Label("repositoryList").setVisible(false));
    } else {
      FilterableRepositoryList repoList =
          new FilterableRepositoryList("repositoryList", repositories);
      repoList.setAllowCreate(user.canCreate(project.name + "/"));
      add(repoList);
    }
  }
예제 #20
0
  protected List<ProjectModel> getProjects(PageParameters params) {
    if (params == null) {
      return getProjectModels();
    }

    boolean hasParameter = false;
    String regex = WicketUtils.getRegEx(params);
    String team = WicketUtils.getTeam(params);
    int daysBack = params.getInt("db", 0);
    int maxDaysBack = app().settings().getInteger(Keys.web.activityDurationMaximum, 30);

    List<ProjectModel> availableModels = getProjectModels();
    Set<ProjectModel> models = new HashSet<ProjectModel>();

    if (!StringUtils.isEmpty(regex)) {
      // filter the projects by the regex
      hasParameter = true;
      Pattern pattern = Pattern.compile(regex);
      for (ProjectModel model : availableModels) {
        if (pattern.matcher(model.name).find()) {
          models.add(model);
        }
      }
    }

    if (!StringUtils.isEmpty(team)) {
      // filter the projects by the specified teams
      hasParameter = true;
      List<String> teams = StringUtils.getStringsFromValue(team, ",");

      // need TeamModels first
      List<TeamModel> teamModels = new ArrayList<TeamModel>();
      for (String name : teams) {
        TeamModel teamModel = app().users().getTeamModel(name);
        if (teamModel != null) {
          teamModels.add(teamModel);
        }
      }

      // brute-force our way through finding the matching models
      for (ProjectModel projectModel : availableModels) {
        for (String repositoryName : projectModel.repositories) {
          for (TeamModel teamModel : teamModels) {
            if (teamModel.hasRepositoryPermission(repositoryName)) {
              models.add(projectModel);
            }
          }
        }
      }
    }

    if (!hasParameter) {
      models.addAll(availableModels);
    }

    // time-filter the list
    if (daysBack > 0) {
      if (maxDaysBack > 0 && daysBack > maxDaysBack) {
        daysBack = maxDaysBack;
      }
      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.HOUR_OF_DAY, 0);
      cal.set(Calendar.MINUTE, 0);
      cal.set(Calendar.SECOND, 0);
      cal.set(Calendar.MILLISECOND, 0);
      cal.add(Calendar.DATE, -1 * daysBack);
      Date threshold = cal.getTime();
      Set<ProjectModel> timeFiltered = new HashSet<ProjectModel>();
      for (ProjectModel model : models) {
        if (model.lastChange.after(threshold)) {
          timeFiltered.add(model);
        }
      }
      models = timeFiltered;
    }

    List<ProjectModel> list = new ArrayList<ProjectModel>(models);
    Collections.sort(list);
    return list;
  }
예제 #21
0
  private void setup(PageParameters params) {
    setupPage("", "");

    // default values
    ArrayList<String> repositories = new ArrayList<String>();
    String query = "";
    int page = 1;
    int pageSize = app().settings().getInteger(Keys.web.itemsPerPage, 50);

    // display user-accessible selections
    UserModel user = GitBlitWebSession.get().getUser();
    List<String> availableRepositories = new ArrayList<String>();
    for (RepositoryModel model : app().repositories().getRepositoryModels(user)) {
      if (model.hasCommits && !ArrayUtils.isEmpty(model.indexedBranches)) {
        availableRepositories.add(model.name);
      }
    }

    if (params != null) {
      String repository = WicketUtils.getRepositoryName(params);
      if (!StringUtils.isEmpty(repository)) {
        repositories.add(repository);
      }

      page = WicketUtils.getPage(params);

      if (params.containsKey("repositories")) {
        String value = params.getString("repositories", "");
        List<String> list = StringUtils.getStringsFromValue(value);
        repositories.addAll(list);
      }

      if (params.containsKey("allrepos")) {
        repositories.addAll(availableRepositories);
      }

      if (params.containsKey("query")) {
        query = params.getString("query", "");
      } else {
        String value = WicketUtils.getSearchString(params);
        String type = WicketUtils.getSearchType(params);
        com.gitblit.Constants.SearchType searchType =
            com.gitblit.Constants.SearchType.forName(type);
        if (!StringUtils.isEmpty(value)) {
          if (searchType == SearchType.COMMIT) {
            query = "type:" + searchType.name().toLowerCase() + " AND \"" + value + "\"";
          } else {
            query = searchType.name().toLowerCase() + ":\"" + value + "\"";
          }
        }
      }
    }

    boolean luceneEnabled = app().settings().getBoolean(Keys.web.allowLuceneIndexing, true);
    if (luceneEnabled) {
      if (availableRepositories.size() == 0) {
        info(getString("gb.noIndexedRepositoriesWarning"));
      }
    } else {
      error(getString("gb.luceneDisabled"));
    }

    // enforce user-accessible repository selections
    Set<String> uniqueRepositories = new LinkedHashSet<String>();
    for (String selectedRepository : repositories) {
      if (availableRepositories.contains(selectedRepository)) {
        uniqueRepositories.add(selectedRepository);
      }
    }
    ArrayList<String> searchRepositories = new ArrayList<String>(uniqueRepositories);

    // search form
    final Model<String> queryModel = new Model<String>(query);
    final Model<ArrayList<String>> repositoriesModel =
        new Model<ArrayList<String>>(searchRepositories);
    final Model<Boolean> allreposModel =
        new Model<Boolean>(params != null && params.containsKey("allrepos"));
    SessionlessForm<Void> form =
        new SessionlessForm<Void>("searchForm", getClass()) {

          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit() {
            String q = queryModel.getObject();
            if (StringUtils.isEmpty(q)) {
              error(getString("gb.undefinedQueryWarning"));
              return;
            }
            if (repositoriesModel.getObject().size() == 0 && !allreposModel.getObject()) {
              error(getString("gb.noSelectedRepositoriesWarning"));
              return;
            }
            PageParameters params = new PageParameters();
            params.put("repositories", StringUtils.flattenStrings(repositoriesModel.getObject()));
            params.put("query", queryModel.getObject());
            params.put("allrepos", allreposModel.getObject());
            LuceneSearchPage page = new LuceneSearchPage(params);
            setResponsePage(page);
          }
        };

    ListMultipleChoice<String> selections =
        new ListMultipleChoice<String>(
            "repositories", repositoriesModel, availableRepositories, new StringChoiceRenderer());
    selections.setMaxRows(8);
    form.add(selections.setEnabled(luceneEnabled));
    form.add(new TextField<String>("query", queryModel).setEnabled(luceneEnabled));
    form.add(new CheckBox("allrepos", allreposModel));
    add(form.setEnabled(luceneEnabled));

    // execute search
    final List<SearchResult> results = new ArrayList<SearchResult>();
    if (!ArrayUtils.isEmpty(searchRepositories) && !StringUtils.isEmpty(query)) {
      results.addAll(app().repositories().search(query, page, pageSize, searchRepositories));
    }

    // results header
    if (results.size() == 0) {
      if (!ArrayUtils.isEmpty(searchRepositories) && !StringUtils.isEmpty(query)) {
        add(new Label("resultsHeader", query).setRenderBodyOnly(true));
        add(new Label("resultsCount", getString("gb.noHits")).setRenderBodyOnly(true));
      } else {
        add(new Label("resultsHeader").setVisible(false));
        add(new Label("resultsCount").setVisible(false));
      }
    } else {
      add(new Label("resultsHeader", query).setRenderBodyOnly(true));
      add(
          new Label(
                  "resultsCount",
                  MessageFormat.format(
                      getString("gb.queryResults"),
                      results.get(0).hitId,
                      results.get(results.size() - 1).hitId,
                      results.get(0).totalHits))
              .setRenderBodyOnly(true));
    }

    // search results view
    ListDataProvider<SearchResult> resultsDp = new ListDataProvider<SearchResult>(results);
    final DataView<SearchResult> resultsView =
        new DataView<SearchResult>("searchResults", resultsDp) {
          private static final long serialVersionUID = 1L;

          @Override
          public void populateItem(final Item<SearchResult> item) {
            final SearchResult sr = item.getModelObject();
            switch (sr.type) {
              case commit:
                {
                  Label icon = WicketUtils.newIcon("type", "icon-refresh");
                  WicketUtils.setHtmlTooltip(icon, "commit");
                  item.add(icon);
                  item.add(
                      new LinkPanel(
                          "summary",
                          null,
                          sr.summary,
                          CommitPage.class,
                          WicketUtils.newObjectParameter(sr.repository, sr.commitId)));
                  // show tags
                  Fragment fragment = new Fragment("tags", "tagsPanel", LuceneSearchPage.this);
                  List<String> tags = sr.tags;
                  if (tags == null) {
                    tags = new ArrayList<String>();
                  }
                  ListDataProvider<String> tagsDp = new ListDataProvider<String>(tags);
                  final DataView<String> tagsView =
                      new DataView<String>("tag", tagsDp) {
                        private static final long serialVersionUID = 1L;

                        @Override
                        public void populateItem(final Item<String> item) {
                          String tag = item.getModelObject();
                          Component c =
                              new LinkPanel(
                                  "tagLink",
                                  null,
                                  tag,
                                  TagPage.class,
                                  WicketUtils.newObjectParameter(
                                      sr.repository, Constants.R_TAGS + tag));
                          WicketUtils.setCssClass(c, "tagRef");
                          item.add(c);
                        }
                      };
                  fragment.add(tagsView);
                  item.add(fragment);
                  break;
                }
              case blob:
                {
                  Label icon = WicketUtils.newIcon("type", "icon-file");
                  WicketUtils.setHtmlTooltip(icon, "blob");
                  item.add(icon);
                  item.add(
                      new LinkPanel(
                          "summary",
                          null,
                          sr.path,
                          BlobPage.class,
                          WicketUtils.newPathParameter(sr.repository, sr.branch, sr.path)));
                  item.add(new Label("tags").setVisible(false));
                  break;
                }
            }
            item.add(
                new Label("fragment", sr.fragment)
                    .setEscapeModelStrings(false)
                    .setVisible(!StringUtils.isEmpty(sr.fragment)));
            item.add(
                new LinkPanel(
                    "repository",
                    null,
                    sr.repository,
                    SummaryPage.class,
                    WicketUtils.newRepositoryParameter(sr.repository)));
            if (StringUtils.isEmpty(sr.branch)) {
              item.add(new Label("branch", "null"));
            } else {
              item.add(
                  new LinkPanel(
                      "branch",
                      "branch",
                      StringUtils.getRelativePath(Constants.R_HEADS, sr.branch),
                      LogPage.class,
                      WicketUtils.newObjectParameter(sr.repository, sr.branch)));
            }
            item.add(new Label("author", sr.author));
            item.add(
                WicketUtils.createDatestampLabel("date", sr.date, getTimeZone(), getTimeUtils()));
          }
        };
    add(resultsView.setVisible(results.size() > 0));

    PageParameters pagerParams = new PageParameters();
    pagerParams.put("repositories", StringUtils.flattenStrings(repositoriesModel.getObject()));
    pagerParams.put("query", queryModel.getObject());

    boolean showPager = false;
    int totalPages = 0;
    if (results.size() > 0) {
      totalPages =
          (results.get(0).totalHits / pageSize) + (results.get(0).totalHits % pageSize > 0 ? 1 : 0);
      showPager = results.get(0).totalHits > pageSize;
    }

    add(
        new PagerPanel("topPager", page, totalPages, LuceneSearchPage.class, pagerParams)
            .setVisible(showPager));
    add(
        new PagerPanel("bottomPager", page, totalPages, LuceneSearchPage.class, pagerParams)
            .setVisible(showPager));
  }
 public static PageParameters createParams(final boolean isReturn) {
   final PageParameters params = new PageParameters();
   params.add("is_return", String.valueOf(isReturn));
   return params;
 }
예제 #23
0
 public MenuPage(PageParameters pageParameters) {
   panelClassName = pageParameters.getString("panel", "");
   add(createPanel("content", panelClassName));
 }
예제 #24
0
 private boolean isCreateLinkFromUploadCenter() {
   return params.containsKey("create");
 }
예제 #25
0
  public StaticPage(PageParameters parameters) {
    super(parameters);

    try {
      String path = parameters.getString(TranslationUrlStrategy.PATH);

      final Class panelClass = panelMap.get(path);

      // set content width the the CONTENT_WIDTH field of the panel if it exists
      try {
        Field contentWidth = panelClass.getField("CONTENT_WIDTH");
        if (contentWidth.getType().equals(int.class)) {
          setContentWidth(contentWidth.getInt(null));
        }
      } catch (NoSuchFieldException e) {
        // do nothing, not every panel will have a field CONTENT_WIDTH
      }

      // determine whether it is cacheable or not
      boolean cacheable = false;
      for (Class iface : panelClass.getInterfaces()) {
        if (iface.equals(CacheableUrlStaticPanel.class)) {
          cacheable = true;
          break;
        }
      }

      if (cacheable) {
        // we don't want to have caching enabled on the installer ripper or other things of that
        // nature
        cacheable = DistributionHandler.allowCaching(getPhetCycle());
      }

      Method getKeyMethod = panelClass.getMethod("getKey");
      String key = (String) getKeyMethod.invoke(null);

      if (cacheable) {
        logger.debug("cacheable static panel: " + panelClass.getSimpleName());
        add(
            new SimplePanelCacheEntry(
                panelClass, this.getClass(), getPageContext().getLocale(), path, getPhetCycle()) {
              public PhetPanel constructPanel(String id, PageContext context) {
                try {
                  Constructor ctor = panelClass.getConstructor(String.class, PageContext.class);
                  PhetPanel panel = (PhetPanel) ctor.newInstance("panel", getPageContext());
                  return panel;
                } catch (InvocationTargetException e) {
                  e.printStackTrace();
                } catch (NoSuchMethodException e) {
                  e.printStackTrace();
                } catch (IllegalAccessException e) {
                  e.printStackTrace();
                } catch (InstantiationException e) {
                  e.printStackTrace();
                }
                throw new RuntimeException("failed to construct panel!");
              }
            }.instantiate("panel", getPageContext(), getPhetCycle()));
      } else {
        Constructor ctor = panelClass.getConstructor(String.class, PageContext.class);
        PhetPanel panel = (PhetPanel) ctor.newInstance("panel", getPageContext());
        add(panel);
      }

      setTitle(getLocalizer().getString(key + ".title", this));
      NavLocation navLocation = getNavMenu().getLocationByKey(key);
      if (navLocation == null) {
        logger.warn("nav location == null for " + panelClass.getCanonicalName());
      }
      initializeLocation(navLocation);

      if (PhetWicketApplication.get().isDevelopment()) {
        add(
            new RawBodyLabel(
                "debug-static-page-class",
                "<!-- static page " + panelClass.getCanonicalName() + " -->"));
      } else {
        add(new InvisibleComponent("debug-static-page-class"));
      }

    } catch (RuntimeException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InstantiationException e) {
      e.printStackTrace();
    }

    this.getPhetCycle().setMinutesToCache(15);
  }