Beispiel #1
0
 /**
  * Authenticate a user based on a username and password.
  *
  * @param username
  * @param password
  * @return a user object or null
  */
 @Override
 public UserModel authenticate(String username, char[] password) {
   Properties allUsers = read();
   String userInfo = allUsers.getProperty(username);
   if (StringUtils.isEmpty(userInfo)) {
     return null;
   }
   UserModel returnedUser = null;
   UserModel user = getUserModel(username);
   if (user.password.startsWith(StringUtils.MD5_TYPE)) {
     // password digest
     String md5 = StringUtils.MD5_TYPE + StringUtils.getMD5(new String(password));
     if (user.password.equalsIgnoreCase(md5)) {
       returnedUser = user;
     }
   } else if (user.password.startsWith(StringUtils.COMBINED_MD5_TYPE)) {
     // username+password digest
     String md5 =
         StringUtils.COMBINED_MD5_TYPE
             + StringUtils.getMD5(username.toLowerCase() + new String(password));
     if (user.password.equalsIgnoreCase(md5)) {
       returnedUser = user;
     }
   } else if (user.password.equals(new String(password))) {
     // plain-text password
     returnedUser = user;
   }
   return returnedUser;
 }
Beispiel #2
0
  private void setSizeAndPosition() {
    String sz = null;
    String pos = null;
    try {
      StoredConfig config = getConfig();
      sz = config.getString("ui", null, "size");
      pos = config.getString("ui", null, "position");
      defaultDuration = config.getInt("new", "duration", 365);
    } catch (Throwable t) {
      t.printStackTrace();
    }

    // try to restore saved window size
    if (StringUtils.isEmpty(sz)) {
      setSize(900, 600);
    } else {
      String[] chunks = sz.split("x");
      int width = Integer.parseInt(chunks[0]);
      int height = Integer.parseInt(chunks[1]);
      setSize(width, height);
    }

    // try to restore saved window position
    if (StringUtils.isEmpty(pos)) {
      setLocationRelativeTo(null);
    } else {
      String[] chunks = pos.split(",");
      int x = Integer.parseInt(chunks[0]);
      int y = Integer.parseInt(chunks[1]);
      setLocation(x, y);
    }
  }
Beispiel #3
0
 /**
  * Retrieve the user object for the specified username.
  *
  * @param username
  * @return a user object or null
  */
 @Override
 public UserModel getUserModel(String username) {
   if (StringUtils.isEmpty(username)) {
     return null;
   }
   String usernameDecoded = StringUtils.decodeUsername(username);
   UserModel user = userService.getUserModel(usernameDecoded);
   return user;
 }
Beispiel #4
0
  @Override
  public List<CommitInfo> log(
      String objectId,
      final String path,
      int limit,
      int pageOffset,
      boolean showRemoteRefs,
      int itemsPerPage) {

    try {
      if (itemsPerPage <= 1) {
        itemsPerPage = 50;
      }
      boolean pageResults = limit <= 0;
      Repository r = git.getRepository();

      // TODO not sure if this is the right String we should use for the sub module stuff...
      String repositoryName = getConfigDirectory().getPath();

      objectId = defaultObjectId(objectId);

      final Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(r, showRemoteRefs);
      List<RevCommit> commits;
      if (pageResults) {
        // Paging result set
        commits = JGitUtils.getRevLog(r, objectId, pageOffset * itemsPerPage, itemsPerPage);
      } else {
        // Fixed size result set
        commits = JGitUtils.getRevLog(r, objectId, 0, limit);
      }

      List<CommitInfo> answer = new ArrayList<CommitInfo>();
      for (RevCommit entry : commits) {
        final Date date = JGitUtils.getCommitDate(entry);
        String author = entry.getAuthorIdent().getName();
        boolean merge = entry.getParentCount() > 1;

        // short message
        String shortMessage = entry.getShortMessage();
        String trimmedMessage = shortMessage;
        if (allRefs.containsKey(entry.getId())) {
          trimmedMessage = StringUtils.trimString(shortMessage, Constants.LEN_SHORTLOG_REFS);
        } else {
          trimmedMessage = StringUtils.trimString(shortMessage, Constants.LEN_SHORTLOG);
        }

        String name = entry.getName();
        String commitHash = getShortCommitHash(name);
        answer.add(
            new CommitInfo(
                commitHash, name, "log", author, date, merge, trimmedMessage, shortMessage));
      }
      return answer;
    } catch (Exception e) {
      throw new RuntimeIOException(e);
    }
  }
Beispiel #5
0
 /**
  * Delete the user object with the specified username
  *
  * @param username
  * @return true if successful
  */
 @Override
 public boolean deleteUser(String username) {
   if (StringUtils.isEmpty(username)) {
     return false;
   }
   String usernameDecoded = StringUtils.decodeUsername(username);
   UserModel user = getUserModel(usernameDecoded);
   if (userService.deleteUser(usernameDecoded)) {
     callDeleteUserListeners(user);
     return true;
   }
   return false;
 }
Beispiel #6
0
 /**
  * Returns an long filesize from a string value such as 50m or 50mb
  *
  * @param n
  * @param defaultValue
  * @return a long filesize or defaultValue if the key does not exist or can not be parsed
  */
 public long getFilesize(String key, long defaultValue) {
   String val = getString(key, null);
   if (StringUtils.isEmpty(val)) {
     return defaultValue;
   }
   return com.gitblit.utils.FileUtils.convertSizeToLong(val, defaultValue);
 }
Beispiel #7
0
 private String readMarkdown(String messageSource, String resource) {
   String message = "";
   if (messageSource.equalsIgnoreCase("gitblit")) {
     // Read default message
     message = readDefaultMarkdown(resource);
   } else {
     // Read user-supplied message
     if (!StringUtils.isEmpty(messageSource)) {
       File file = GitBlit.getFileOrFolder(messageSource);
       if (file.exists()) {
         try {
           FileInputStream fis = new FileInputStream(file);
           InputStreamReader reader = new InputStreamReader(fis, Constants.CHARACTER_ENCODING);
           message = MarkdownUtils.transformMarkdown(reader);
           reader.close();
         } catch (Throwable t) {
           message = getString("gb.failedToRead") + " " + file;
           warn(message, t);
         }
       } else {
         message = messageSource + " " + getString("gb.isNotValidFile");
       }
     }
   }
   return message;
 }
 @Override
 public String toString() {
   if (displayName == null) {
     displayName = StringUtils.stripDotGit(name);
   }
   return displayName;
 }
Beispiel #9
0
 /**
  * Returns an int filesize from a string value such as 50m or 50mb
  *
  * @param name
  * @param defaultValue
  * @return an int filesize or defaultValue if the key does not exist or can not be parsed
  */
 public int getFilesize(String name, int defaultValue) {
   String val = getString(name, null);
   if (StringUtils.isEmpty(val)) {
     return defaultValue;
   }
   return com.gitblit.utils.FileUtils.convertSizeToInt(val, defaultValue);
 }
Beispiel #10
0
 public LinkPanel(
     String wicketId,
     String bootstrapIcon,
     String linkCssClass,
     IModel<String> model,
     Class<? extends WebPage> clazz,
     PageParameters parameters,
     boolean newWindow) {
   super(wicketId);
   this.labelModel = model;
   Link<Void> link = null;
   if (parameters == null) {
     link = new BookmarkablePageLink<Void>("link", clazz);
   } else {
     link = new BookmarkablePageLink<Void>("link", clazz, parameters);
   }
   if (newWindow) {
     link.add(new SimpleAttributeModifier("target", "_blank"));
   }
   if (linkCssClass != null) {
     link.add(new SimpleAttributeModifier("class", linkCssClass));
   }
   Label icon = new Label("icon");
   if (StringUtils.isEmpty(bootstrapIcon)) {
     link.add(icon.setVisible(false));
   } else {
     WicketUtils.setCssClass(icon, bootstrapIcon);
     link.add(icon);
   }
   link.add(new Label("label", labelModel).setRenderBodyOnly(true));
   add(link);
 }
Beispiel #11
0
 public void setUsers(String owner, List<String> all, List<String> selected) {
   ownerField.setModel(new DefaultComboBoxModel(all.toArray()));
   if (!StringUtils.isEmpty(owner)) {
     ownerField.setSelectedItem(owner);
   }
   usersPalette.setObjects(all, selected);
 }
Beispiel #12
0
 private void filterUsers(final String fragment) {
   table.clearSelection();
   userCertificatePanel.setUserCertificateModel(null);
   if (StringUtils.isEmpty(fragment)) {
     table.setRowSorter(defaultSorter);
     return;
   }
   RowFilter<UserCertificateTableModel, Object> containsFilter =
       new RowFilter<UserCertificateTableModel, Object>() {
         @Override
         public boolean include(
             Entry<? extends UserCertificateTableModel, ? extends Object> entry) {
           for (int i = entry.getValueCount() - 1; i >= 0; i--) {
             if (entry.getStringValue(i).toLowerCase().contains(fragment.toLowerCase())) {
               return true;
             }
           }
           return false;
         }
       };
   TableRowSorter<UserCertificateTableModel> sorter =
       new TableRowSorter<UserCertificateTableModel>(tableModel);
   sorter.setRowFilter(containsFilter);
   table.setRowSorter(sorter);
 }
Beispiel #13
0
 /**
  * Returns a list of strings from the specified key using the specified string separator.
  *
  * @param name
  * @param separator
  * @return list of strings
  */
 public List<String> getStrings(String name, String separator) {
   List<String> strings = new ArrayList<String>();
   Properties props = getSettings();
   if (props.containsKey(name)) {
     String value = props.getProperty(name);
     strings = StringUtils.getStringsFromValue(value, separator);
   }
   return strings;
 }
 public String getURL() throws IOException {
   String url = runtimeManager.getSettings().getString(Plugin.SETTING_URL, null);
   if (StringUtils.isEmpty(url)) {
     throw new IOException(
         String.format(
             "Could not send message to Slack because '%s' is not defined!", Plugin.SETTING_URL));
   }
   return url;
 }
Beispiel #15
0
 /**
  * Returns the cookie value for the specified user.
  *
  * @param model
  * @return cookie value
  */
 @Override
 public char[] getCookie(UserModel model) {
   Properties allUsers = super.read();
   String value = allUsers.getProperty(model.username);
   String[] roles = value.split(",");
   String password = roles[0];
   String cookie = StringUtils.getSHA1(model.username + password);
   return cookie.toCharArray();
 }
Beispiel #16
0
  /**
   * Construct the Gitblit Git daemon.
   *
   * @param bindInterface the ip address of the interface to bind
   * @param port the port to serve on
   * @param folder the folder to serve from
   */
  public GitDaemon(String bindInterface, int port, File folder) {
    this(
        StringUtils.isEmpty(bindInterface)
            ? new InetSocketAddress(port)
            : new InetSocketAddress(bindInterface, port));

    // set the repository resolver and pack factories
    repositoryResolver = new RepositoryResolver<GitDaemonClient>(folder);
  }
Beispiel #17
0
  private String readDefaultMarkdown(String file) {
    String base = file.substring(0, file.lastIndexOf('.'));
    String ext = file.substring(file.lastIndexOf('.'));
    String lc = getLanguageCode();
    String cc = getCountryCode();

    // try to read file_en-us.ext, file_en.ext, file.ext
    List<String> files = new ArrayList<String>();
    if (!StringUtils.isEmpty(lc)) {
      if (!StringUtils.isEmpty(cc)) {
        files.add(base + "_" + lc + "-" + cc + ext);
        files.add(base + "_" + lc + "_" + cc + ext);
      }
      files.add(base + "_" + lc + ext);
    }
    files.add(file);

    for (String name : files) {
      String message;
      InputStreamReader reader = null;
      try {
        InputStream is = getClass().getResourceAsStream("/" + name);
        if (is == null) {
          continue;
        }
        reader = new InputStreamReader(is, Constants.CHARACTER_ENCODING);
        message = MarkdownUtils.transformMarkdown(reader);
        reader.close();
        return message;
      } catch (Throwable t) {
        message = MessageFormat.format(getString("gb.failedToReadMessage"), file);
        error(message, t, false);
        return message;
      } finally {
        if (reader != null) {
          try {
            reader.close();
          } catch (Exception e) {
          }
        }
      }
    }
    return MessageFormat.format(getString("gb.failedToReadMessage"), file);
  }
Beispiel #18
0
 /**
  * Returns the boolean value for the specified key. If the key does not exist or the value for the
  * key can not be interpreted as a boolean, the defaultValue is returned.
  *
  * @param key
  * @param defaultValue
  * @return key value or defaultValue
  */
 public boolean getBoolean(String name, boolean defaultValue) {
   Properties props = getSettings();
   if (props.containsKey(name)) {
     String value = props.getProperty(name);
     if (!StringUtils.isEmpty(value)) {
       return Boolean.parseBoolean(value.trim());
     }
   }
   return defaultValue;
 }
  /**
   * Optionally sets the channel of the payload based on the repository.
   *
   * @param repository
   * @param payload
   */
  public void setChannel(RepositoryModel repository, Payload payload) {
    boolean useProjectChannels =
        runtimeManager.getSettings().getBoolean(Plugin.SETTING_USE_PROJECT_CHANNELS, false);
    if (!useProjectChannels) {
      return;
    }

    if (StringUtils.isEmpty(repository.projectPath)) {
      return;
    }

    String defaultChannel =
        runtimeManager.getSettings().getString(Plugin.SETTING_DEFAULT_CHANNEL, null);
    if (!StringUtils.isEmpty(defaultChannel)) {
      payload.setChannel(defaultChannel + "-" + repository.projectPath);
    } else {
      payload.setChannel(repository.projectPath);
    }
  }
Beispiel #20
0
 /**
  * Returns the char value for the specified key. If the key does not exist or the value for the
  * key can not be interpreted as a char, the defaultValue is returned.
  *
  * @param key
  * @param defaultValue
  * @return key value or defaultValue
  */
 public char getChar(String name, char defaultValue) {
   Properties props = getSettings();
   if (props.containsKey(name)) {
     String value = props.getProperty(name);
     if (!StringUtils.isEmpty(value)) {
       return value.trim().charAt(0);
     }
   }
   return defaultValue;
 }
Beispiel #21
0
 protected void setAccountType(UserModel user) {
   if (user != null) {
     if (!StringUtils.isEmpty(user.password)
         && !Constants.EXTERNAL_ACCOUNT.equalsIgnoreCase(user.password)
         && !"StoredInLDAP".equalsIgnoreCase(user.password)) {
       user.accountType = AccountType.LOCAL;
     } else {
       user.accountType = getAccountType();
     }
   }
 }
Beispiel #22
0
 protected String getPageTitle(String repositoryName) {
   String siteName = app().settings().getString(Keys.web.siteName, Constants.NAME);
   if (StringUtils.isEmpty(siteName)) {
     siteName = Constants.NAME;
   }
   if (repositoryName != null && repositoryName.trim().length() > 0) {
     return repositoryName + " - " + siteName;
   } else {
     return siteName;
   }
 }
 /**
  * Sends a status acknowledgment to the origin Gitblit instance. This includes the results of the
  * federated pull.
  *
  * @param registration
  * @throws Exception
  */
 private void sendStatusAcknowledgment(FederationModel registration) throws Exception {
   if (!registration.sendStatus) {
     // skip status acknowledgment
     return;
   }
   InetAddress addr = InetAddress.getLocalHost();
   String federationName = GitBlit.getString(Keys.federation.name, null);
   if (StringUtils.isEmpty(federationName)) {
     federationName = addr.getHostName();
   }
   FederationUtils.acknowledgeStatus(addr.getHostAddress(), registration);
   logger.info(MessageFormat.format("Pull status sent to {0}", registration.url));
 }
Beispiel #24
0
 private String transformMarkdown(String markdown) {
   String message = "";
   if (!StringUtils.isEmpty(markdown)) {
     // Read user-supplied message
     try {
       message = MarkdownUtils.transformMarkdown(markdown);
     } catch (Throwable t) {
       message = getString("gb.failedToRead") + " " + markdown;
       warn(message, t);
     }
   }
   return message;
 }
Beispiel #25
0
 /**
  * Returns the long value for the specified key. If the key does not exist or the value for the
  * key can not be interpreted as an long, the defaultValue is returned.
  *
  * @param key
  * @param defaultValue
  * @return key value or defaultValue
  */
 public long getLong(String name, long defaultValue) {
   Properties props = getSettings();
   if (props.containsKey(name)) {
     try {
       String value = props.getProperty(name);
       if (!StringUtils.isEmpty(value)) {
         return Long.parseLong(value.trim());
       }
     } catch (NumberFormatException e) {
       logger.warn("Failed to parse long for " + name + " using default of " + defaultValue);
     }
   }
   return defaultValue;
 }
Beispiel #26
0
 /**
  * Authenticate a user based on their cookie.
  *
  * @param cookie
  * @return a user object or null
  */
 @Override
 public UserModel authenticate(char[] cookie) {
   String hash = new String(cookie);
   if (StringUtils.isEmpty(hash)) {
     return null;
   }
   read();
   UserModel model = null;
   if (cookies.containsKey(hash)) {
     String username = cookies.get(hash);
     model = getUserModel(username);
   }
   return model;
 }
Beispiel #27
0
 /**
  * Returns the list of keys whose name starts with the specified prefix. If the prefix is null or
  * empty, all key names are returned.
  *
  * @param startingWith
  * @return list of keys
  */
 public List<String> getAllKeys(String startingWith) {
   List<String> keys = new ArrayList<String>();
   Properties props = getSettings();
   if (StringUtils.isEmpty(startingWith)) {
     keys.addAll(props.stringPropertyNames());
   } else {
     startingWith = startingWith.toLowerCase();
     for (Object o : props.keySet()) {
       String key = o.toString();
       if (key.toLowerCase().startsWith(startingWith)) {
         keys.add(key);
       }
     }
   }
   return keys;
 }
Beispiel #28
0
 /**
  * Returns a list of integers from the specified key using the specified string separator.
  *
  * @param name
  * @param separator
  * @return list of integers
  */
 public List<Integer> getIntegers(String name, String separator) {
   List<Integer> ints = new ArrayList<Integer>();
   Properties props = getSettings();
   if (props.containsKey(name)) {
     String value = props.getProperty(name);
     List<String> strings = StringUtils.getStringsFromValue(value, separator);
     for (String str : strings) {
       try {
         int i = Integer.parseInt(str);
         ints.add(i);
       } catch (NumberFormatException e) {
       }
     }
   }
   return ints;
 }
Beispiel #29
0
  /** Reads the properties file and rebuilds the in-memory cookie lookup table. */
  @Override
  protected synchronized Properties read() {
    long lastRead = lastModified();
    Properties allUsers = super.read();
    if (lastRead != lastModified()) {
      // reload hash cache
      cookies.clear();
      teams.clear();

      for (String username : allUsers.stringPropertyNames()) {
        String value = allUsers.getProperty(username);
        String[] roles = value.split(",");
        if (username.charAt(0) == '@') {
          // team definition
          TeamModel team = new TeamModel(username.substring(1));
          List<String> repositories = new ArrayList<String>();
          List<String> users = new ArrayList<String>();
          List<String> mailingLists = new ArrayList<String>();
          List<String> preReceive = new ArrayList<String>();
          List<String> postReceive = new ArrayList<String>();
          for (String role : roles) {
            if (role.charAt(0) == '!') {
              users.add(role.substring(1));
            } else if (role.charAt(0) == '&') {
              mailingLists.add(role.substring(1));
            } else if (role.charAt(0) == '^') {
              preReceive.add(role.substring(1));
            } else if (role.charAt(0) == '%') {
              postReceive.add(role.substring(1));
            } else {
              repositories.add(role);
            }
          }
          team.addRepositories(repositories);
          team.addUsers(users);
          team.addMailingLists(mailingLists);
          teams.put(team.name.toLowerCase(), team);
        } else {
          // user definition
          String password = roles[0];
          cookies.put(
              StringUtils.getSHA1(username.toLowerCase() + password), username.toLowerCase());
        }
      }
    }
    return allUsers;
  }
Beispiel #30
0
 /**
  * Analyze the url and returns the action of the request. Return values are either
  * "/git-receive-pack" or "/git-upload-pack".
  *
  * @param serverUrl
  * @return action of the request
  */
 @Override
 protected String getUrlRequestAction(String suffix) {
   if (!StringUtils.isEmpty(suffix)) {
     if (suffix.startsWith(gitReceivePack)) {
       return gitReceivePack;
     } else if (suffix.startsWith(gitUploadPack)) {
       return gitUploadPack;
     } else if (suffix.contains("?service=git-receive-pack")) {
       return gitReceivePack;
     } else if (suffix.contains("?service=git-upload-pack")) {
       return gitUploadPack;
     } else {
       return gitUploadPack;
     }
   }
   return null;
 }