org.eclipse.jgit.util.StringUtils Java Examples

The following examples show how to use org.eclipse.jgit.util.StringUtils. 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: LfsAuthServlet.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
private Link createToken(
    @NotNull HttpServletRequest req,
    @Nullable URI uri,
    @Nullable String secretToken,
    @Nullable String userId,
    @Nullable String mode
) throws ServerError {
  // Check secretToken
  if (StringUtils.isEmptyOrNull(secretToken))
    throw new ServerError(HttpServletResponse.SC_BAD_REQUEST, "Parameter \"secretToken\" not specified");

  if (!this.secretToken.equals(secretToken))
    throw new ServerError(HttpServletResponse.SC_FORBIDDEN, "Invalid secretToken");

  final LfsAuthHelper.AuthMode authMode = LfsAuthHelper.AuthMode.find(mode);
  if (authMode == null)
    throw new ServerError(HttpServletResponse.SC_BAD_REQUEST, String.format("Unsupported mode: %s", mode));

  return LfsAuthHelper.createToken(context.getShared(), uri != null ? uri : getWebServer().getUrl(req).resolve(baseLfsUrl), userId, authMode, tokenExpireSec, tokenExpireTime);
}
 
Example #2
Source File: GitLabMapping.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void ready(@NotNull SharedContext context) throws IOException {
  final GitlabAPI api = gitLabContext.connect();

  // Web hook for repository list update.
  final WebServer webServer = context.sure(WebServer.class);
  final URL hookUrl = webServer.toUrl(gitLabContext.getHookPath());
  final String path = hookUrl.getPath();
  webServer.addServlet(StringUtils.isEmptyOrNull(path) ? "/" : path, new GitLabHookServlet());

  try {
    if (!isHookInstalled(api, hookUrl.toString())) {
      api.addSystemHook(hookUrl.toString());
    }
  } catch (GitlabAPIException e) {
    if (e.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
      log.warn("Unable to install gitlab hook {}: {}", hookUrl, e.getMessage());
    } else {
      throw e;
    }
  }

}
 
Example #3
Source File: PushHookTriggerHandlerImpl.java    From gitlab-plugin with GNU General Public License v2.0 6 votes vote down vote up
private String retrievePushedBy(final PushHook hook) {
    final String userName = hook.getUserName();
    if (!StringUtils.isEmptyOrNull(userName)) {
        return userName;
    }

    final String userUsername = hook.getUserUsername();
    if (!StringUtils.isEmptyOrNull(userUsername)) {
        return userUsername;
    }

    final List<Commit> commits = hook.getCommits();
    if (commits != null && !commits.isEmpty()) {
        return commits.get(commits.size() - 1).getAuthor().getName();
    }

    return null;
}
 
Example #4
Source File: GitUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Compare the two given git remote URIs. This method is a reimplementation of {@link URIish#equals(Object)} with
 * one difference. The scheme of the URIs is only considered if both URIs have a non-null and non-empty scheme part.
 *
 * @param lhs
 *            the left hand side
 * @param rhs
 *            the right hand side
 * @return <code>true</code> if the two URIs are to be considered equal and <code>false</code> otherwise
 */
private static boolean equals(URIish lhs, URIish rhs) {
	// We only consider the scheme if both URIs have one
	if (!StringUtils.isEmptyOrNull(lhs.getScheme()) && !StringUtils.isEmptyOrNull(rhs.getScheme())) {
		if (!Objects.equals(lhs.getScheme(), rhs.getScheme()))
			return false;
	}
	if (!equals(lhs.getUser(), rhs.getUser()))
		return false;
	if (!equals(lhs.getPass(), rhs.getPass()))
		return false;
	if (!equals(lhs.getHost(), rhs.getHost()))
		return false;
	if (lhs.getPort() != rhs.getPort())
		return false;
	if (!pathEquals(lhs.getPath(), rhs.getPath()))
		return false;
	return true;
}
 
Example #5
Source File: GitUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean pathEquals(String lhs, String rhs) {
	if (StringUtils.isEmptyOrNull(lhs) && StringUtils.isEmptyOrNull(rhs))
		return true;

	// Skip leading slashes in both paths.
	int lhsIndex = 0;
	while (lhsIndex < lhs.length() && lhs.charAt(lhsIndex) == '/')
		++lhsIndex;

	int rhsIndex = 0;
	while (rhsIndex < rhs.length() && rhs.charAt(rhsIndex) == '/')
		++rhsIndex;

	String lhsRel = lhs.substring(lhsIndex);
	String rhsRel = rhs.substring(rhsIndex);
	return lhsRel.equals(rhsRel);
}
 
Example #6
Source File: MergeMessageFormatter.java    From onedev with MIT License 5 votes vote down vote up
private static String joinNames(List<String> names, String singular,
		String plural) {
	if (names.size() == 1) {
		return singular + " " + names.get(0); //$NON-NLS-1$
	}
	return plural + " " + StringUtils.join(names, ", ", " and "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
 
Example #7
Source File: GitLabConnection.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
public FormValidation doCheckApiTokenId(@QueryParameter String value) {
    if (StringUtils.isEmptyOrNull(value)) {
        return FormValidation.error(Messages.apiToken_required());
    } else {
        return FormValidation.ok();
    }
}
 
Example #8
Source File: Main.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static List<File> getGitDiffFilesToProcess(List<Pattern> patternsToExclude, CommandLine commandLine) {
    String gitDirPath = commandLine.getOptionValue(OPTION_GIT_DIR_NAME);
    File repoDir = new File(gitDirPath);
    if (!repoDir.isDirectory()) {
        System.out.println("git directory " + gitDirPath + " is not a directory!");
        System.exit(1);
    }
    String oldRev = commandLine.getOptionValue(OPTION_GIT_BASE_REV_NAME);
    boolean includeStagedCodes = commandLine.hasOption(OPTION_GIT_INCLUDE_STAGED_CODES_NAME);
    if (StringUtils.isEmptyOrNull(oldRev)) {
        oldRev = includeStagedCodes ? "HEAD" : "HEAD~";
    }
    String newRev = "HEAD";
    DiffCalculator calculator = DiffCalculator.builder().diffAlgorithm(new HistogramDiff()).build();
    try {
        List<DiffEntryWrapper> diffEntryList = calculator.calculateDiff(repoDir, oldRev, newRev, includeStagedCodes)
                .stream()
                .filter(diffEntry -> !diffEntry.isDeleted())
                .filter(diffEntry -> patternsToExclude.stream()
                        .noneMatch(p -> p.matcher(diffEntry.getNewPath()).matches()))
                .collect(Collectors.toList());

        DIFF_ENTRY_LIST.addAll(diffEntryList);

        return diffEntryList.stream()
                .map(DiffEntryWrapper::getNewFile)
                .collect(Collectors.toList());

    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("error happened when calculate git diff");
        return Collections.emptyList();
    }
}
 
Example #9
Source File: CauseDataHelper.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
private static String retrievePushedBy(final PushHook hook) {
    String userName = hook.getUserName();
    if (!StringUtils.isEmptyOrNull(userName)) {
        return userName;
    }

    final List<Commit> commits = hook.getCommits();
    if (commits != null && !commits.isEmpty()) {
        return commits.get(commits.size() - 1).getAuthor().getName();
    }

    return null;
}
 
Example #10
Source File: GitLabConnection.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
public FormValidation doCheckUrl(@QueryParameter String value) {
    if (StringUtils.isEmptyOrNull(value)) {
        return FormValidation.error(Messages.url_required());
    } else {
        return FormValidation.ok();
    }
}
 
Example #11
Source File: GitLabConnection.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
public FormValidation doCheckName(@QueryParameter String id, @QueryParameter String value) {
    if (StringUtils.isEmptyOrNull(value)) {
        return FormValidation.error(Messages.name_required());
    } else {
        return FormValidation.ok();
    }
}
 
Example #12
Source File: TestConfiguration.java    From smart-testing with Apache License 2.0 4 votes vote down vote up
public TestConfiguration.Builder withStrategies(Collection<String> strategies) {
    this.strategies = StringUtils.join(strategies, ",");
    return this;
}
 
Example #13
Source File: GitHub.java    From Stringlate with MIT License 4 votes vote down vote up
public static String getAuthRequestUrl() {
    return String.format(GITHUB_AUTH_URL,
            StringUtils.join(Arrays.asList(GITHUB_WANTED_SCOPES), "%20"), SlAppSettings.GITHUB_CLIENT_ID);
}
 
Example #14
Source File: MergeMessageFormatter.java    From onedev with MIT License 4 votes vote down vote up
/**
 * Construct the merge commit message.
 *
 * @param refsToMerge
 *            the refs which will be merged
 * @param target
 *            the branch ref which will be merged into
 * @return merge commit message
 */
public String format(List<Ref> refsToMerge, Ref target) {
	StringBuilder sb = new StringBuilder();
	sb.append("Merge "); //$NON-NLS-1$

	List<String> branches = new ArrayList<>();
	List<String> remoteBranches = new ArrayList<>();
	List<String> tags = new ArrayList<>();
	List<String> commits = new ArrayList<>();
	List<String> others = new ArrayList<>();
	for (Ref ref : refsToMerge) {
		if (ref.getName().startsWith(Constants.R_HEADS)) {
			branches.add("'" + Repository.shortenRefName(ref.getName()) //$NON-NLS-1$
					+ "'"); //$NON-NLS-1$
		} else if (ref.getName().startsWith(Constants.R_REMOTES)) {
			remoteBranches.add("'" //$NON-NLS-1$
					+ Repository.shortenRefName(ref.getName()) + "'"); //$NON-NLS-1$
		} else if (ref.getName().startsWith(Constants.R_TAGS)) {
			tags.add("'" + Repository.shortenRefName(ref.getName()) + "'"); //$NON-NLS-1$ //$NON-NLS-2$
		} else {
			ObjectId objectId = ref.getObjectId();
			if (objectId != null && ref.getName().equals(objectId.getName())) {
				commits.add("'" + ref.getName() + "'"); //$NON-NLS-1$ //$NON-NLS-2$
			} else {
				others.add(ref.getName());
			}
		}
	}

	List<String> listings = new ArrayList<>();

	if (!branches.isEmpty())
		listings.add(joinNames(branches, "branch", "branches")); //$NON-NLS-1$//$NON-NLS-2$

	if (!remoteBranches.isEmpty())
		listings.add(joinNames(remoteBranches, "remote-tracking branch", //$NON-NLS-1$
				"remote-tracking branches")); //$NON-NLS-1$

	if (!tags.isEmpty())
		listings.add(joinNames(tags, "tag", "tags")); //$NON-NLS-1$ //$NON-NLS-2$

	if (!commits.isEmpty())
		listings.add(joinNames(commits, "commit", "commits")); //$NON-NLS-1$ //$NON-NLS-2$

	if (!others.isEmpty())
		listings.add(StringUtils.join(others, ", ", " and ")); //$NON-NLS-1$ //$NON-NLS-2$

	sb.append(StringUtils.join(listings, ", ")); //$NON-NLS-1$

	String targetName = target.getLeaf().getName();
	if (!targetName.equals(Constants.R_HEADS + Constants.MASTER)) {
		String targetShortName = Repository.shortenRefName(targetName);
		sb.append(" into " + targetShortName); //$NON-NLS-1$
	}

	return sb.toString();
}
 
Example #15
Source File: RevCommit.java    From onedev with MIT License 3 votes vote down vote up
/**
 * Parse the commit message and return the first "line" of it.
 * <p>
 * The first line is everything up to the first pair of LFs. This is the
 * "oneline" format, suitable for output in a single line display.
 * <p>
 * This method parses and returns the message portion of the commit buffer,
 * after taking the commit's character set into account and decoding the
 * buffer using that character set. This method is a fairly expensive
 * operation and produces a new string on each invocation.
 *
 * @return decoded commit message as a string. Never null. The returned
 *         string does not contain any LFs, even if the first paragraph
 *         spanned multiple lines. Embedded LFs are converted to spaces.
 */
public final String getShortMessage() {
	byte[] raw = buffer;
	int msgB = RawParseUtils.commitMessage(raw, 0);
	if (msgB < 0) {
		return ""; //$NON-NLS-1$
	}

	int msgE = RawParseUtils.endOfParagraph(raw, msgB);
	String str = RawParseUtils.decode(guessEncoding(), raw, msgB, msgE);
	if (hasLF(raw, msgB, msgE)) {
		str = StringUtils.replaceLineBreaksWithSpace(str);
	}
	return str;
}
 
Example #16
Source File: RevTag.java    From onedev with MIT License 3 votes vote down vote up
/**
 * Parse the tag message and return the first "line" of it.
 * <p>
 * The first line is everything up to the first pair of LFs. This is the
 * "oneline" format, suitable for output in a single line display.
 * <p>
 * This method parses and returns the message portion of the tag buffer,
 * after taking the tag's character set into account and decoding the buffer
 * using that character set. This method is a fairly expensive operation and
 * produces a new string on each invocation.
 *
 * @return decoded tag message as a string. Never null. The returned string
 *         does not contain any LFs, even if the first paragraph spanned
 *         multiple lines. Embedded LFs are converted to spaces.
 */
public final String getShortMessage() {
	byte[] raw = buffer;
	int msgB = RawParseUtils.tagMessage(raw, 0);
	if (msgB < 0) {
		return ""; //$NON-NLS-1$
	}

	int msgE = RawParseUtils.endOfParagraph(raw, msgB);
	String str = RawParseUtils.decode(guessEncoding(), raw, msgB, msgE);
	if (RevCommit.hasLF(raw, msgB, msgE)) {
		str = StringUtils.replaceLineBreaksWithSpace(str);
	}
	return str;
}
 
Example #17
Source File: GitUtils.java    From n4js with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * A helper method for comparing strings. If both of the given strings are empty or <code>null</code>, they are
 * considered equal.
 *
 * @param lhs
 *            the left hand side
 * @param rhs
 *            the right hand side
 * @return <code>true</code> if the two strings are to be considered equal and <code>false</code> otherwise
 */
private static boolean equals(String lhs, String rhs) {
	if (StringUtils.isEmptyOrNull(lhs) && StringUtils.isEmptyOrNull(rhs))
		return true;
	return Objects.equals(lhs, rhs);
}