diff options
Diffstat (limited to 'src/main/java/com/gitblit/utils')
29 files changed, 599 insertions, 593 deletions
diff --git a/src/main/java/com/gitblit/utils/ActivityUtils.java b/src/main/java/com/gitblit/utils/ActivityUtils.java index c4e95879..ddd7e371 100644 --- a/src/main/java/com/gitblit/utils/ActivityUtils.java +++ b/src/main/java/com/gitblit/utils/ActivityUtils.java @@ -45,16 +45,16 @@ import com.google.gson.reflect.TypeToken; /**
* Utility class for building activity information from repositories.
- *
+ *
* @author James Moger
- *
+ *
*/
public class ActivityUtils {
/**
* Gets the recent activity from the repositories for the last daysBack days
* on the specified branch.
- *
+ *
* @param models
* the list of repositories to query
* @param daysBack
@@ -79,7 +79,7 @@ public class ActivityUtils { df.setTimeZone(timezone);
Calendar cal = Calendar.getInstance();
cal.setTimeZone(timezone);
-
+
// aggregate author exclusions
Set<String> authorExclusions = new TreeSet<String>();
authorExclusions.addAll(GitBlit.getStrings(Keys.web.metricAuthorExclusions));
@@ -125,7 +125,7 @@ public class ActivityUtils { // trim commits to maximum count
commits = commits.subList(0, model.maxActivityCommits);
}
- for (RepositoryCommit commit : commits) {
+ for (RepositoryCommit commit : commits) {
Date date = commit.getCommitDate();
String dateStr = df.format(date);
if (!activity.containsKey(dateStr)) {
@@ -142,7 +142,7 @@ public class ActivityUtils { activity.get(dateStr).addCommit(commit);
}
}
-
+
// close the repository
repository.close();
}
@@ -155,7 +155,7 @@ public class ActivityUtils { /**
* Returns the Gravatar profile, if available, for the specified email
* address.
- *
+ *
* @param emailaddress
* @return a Gravatar Profile
* @throws IOException
@@ -167,7 +167,7 @@ public class ActivityUtils { /**
* Creates a Gravatar thumbnail url from the specified email address.
- *
+ *
* @param email
* address to query Gravatar
* @param width
@@ -183,10 +183,10 @@ public class ActivityUtils { "https://www.gravatar.com/avatar/{0}?s={1,number,0}&d=identicon", emailHash, width);
return url;
}
-
+
/**
* Creates a Gravatar thumbnail url from the specified email address.
- *
+ *
* @param email
* address to query Gravatar
* @param width
@@ -206,7 +206,7 @@ public class ActivityUtils { /**
* Returns the Gravatar profile, if available, for the specified hashcode.
* address.
- *
+ *
* @param hash
* the hash of the email address
* @return a Gravatar Profile
diff --git a/src/main/java/com/gitblit/utils/ArrayUtils.java b/src/main/java/com/gitblit/utils/ArrayUtils.java index 65834673..8387ef73 100644 --- a/src/main/java/com/gitblit/utils/ArrayUtils.java +++ b/src/main/java/com/gitblit/utils/ArrayUtils.java @@ -22,9 +22,9 @@ import java.util.List; /**
* Utility class for arrays and collections.
- *
+ *
* @author James Moger
- *
+ *
*/
public class ArrayUtils {
@@ -39,11 +39,11 @@ public class ArrayUtils { public static boolean isEmpty(Object [] array) {
return array == null || array.length == 0;
}
-
+
public static boolean isEmpty(Collection<?> collection) {
return collection == null || collection.size() == 0;
}
-
+
public static String toString(Collection<?> collection) {
if (isEmpty(collection)) {
return "";
@@ -56,7 +56,7 @@ public class ArrayUtils { sb.setLength(sb.length() - 2);
return sb.toString();
}
-
+
public static Collection<String> fromString(String value) {
if (StringUtils.isEmpty(value)) {
value = "";
diff --git a/src/main/java/com/gitblit/utils/Base64.java b/src/main/java/com/gitblit/utils/Base64.java index 6fd2daf1..735cbc28 100644 --- a/src/main/java/com/gitblit/utils/Base64.java +++ b/src/main/java/com/gitblit/utils/Base64.java @@ -19,7 +19,7 @@ import java.util.Arrays; * href="http://iharder.net/base64">http://iharder.net/base64</a> periodically
* to check for updates or to contribute improvements.
* </p>
- *
+ *
* @author Robert Harder
* @author rob@iharder.net
* @version 2.1, stripped to minimum feature set used by JGit.
@@ -89,7 +89,7 @@ public class Base64 { * <var>destOffset</var> + 4 for the <var>destination</var> array. The
* actual number of significant bytes in your array is given by
* <var>numSigBytes</var>.
- *
+ *
* @param source
* the array to convert
* @param srcOffset
@@ -146,7 +146,7 @@ public class Base64 { /**
* Encodes a byte array into Base64 notation.
- *
+ *
* @param source
* The data to convert
* @return encoded base64 representation of source.
@@ -157,7 +157,7 @@ public class Base64 { /**
* Encodes a byte array into Base64 notation.
- *
+ *
* @param source
* The data to convert
* @param off
@@ -199,7 +199,7 @@ public class Base64 { * <var>destOffset</var> + 3 for the <var>destination</var> array. This
* method returns the actual number of bytes that were converted from the
* Base64 encoding.
- *
+ *
* @param source
* the array to convert
* @param srcOffset
@@ -246,7 +246,7 @@ public class Base64 { /**
* Low-level decoding ASCII characters from a byte array.
- *
+ *
* @param source
* The Base64 encoded data
* @param off
@@ -294,7 +294,7 @@ public class Base64 { /**
* Decodes data from Base64 notation.
- *
+ *
* @param s
* the string to decode
* @return the decoded data
diff --git a/src/main/java/com/gitblit/utils/ByteFormat.java b/src/main/java/com/gitblit/utils/ByteFormat.java index cb7da885..d11ce9dc 100644 --- a/src/main/java/com/gitblit/utils/ByteFormat.java +++ b/src/main/java/com/gitblit/utils/ByteFormat.java @@ -23,9 +23,9 @@ import java.text.ParsePosition; /** * ByteFormat is a formatter which takes numbers and returns filesizes in bytes, * kilobytes, megabytes, or gigabytes. - * + * * @author James Moger - * + * */ public class ByteFormat extends Format { @@ -38,6 +38,7 @@ public class ByteFormat extends Format { return format(Long.valueOf(value)); } + @Override public StringBuffer format(Object obj, StringBuffer buf, FieldPosition pos) { if (obj instanceof Number) { long numBytes = ((Number) obj).longValue(); @@ -46,19 +47,20 @@ public class ByteFormat extends Format { buf.append(formatter.format((double) numBytes)).append(" b"); } else if (numBytes < 1024 * 1024) { DecimalFormat formatter = new DecimalFormat("#,##0"); - buf.append(formatter.format((double) numBytes / 1024.0)).append(" KB"); + buf.append(formatter.format(numBytes / 1024.0)).append(" KB"); } else if (numBytes < 1024 * 1024 * 1024) { DecimalFormat formatter = new DecimalFormat("#,##0.0"); - buf.append(formatter.format((double) numBytes / (1024.0 * 1024.0))).append(" MB"); + buf.append(formatter.format(numBytes / (1024.0 * 1024.0))).append(" MB"); } else { DecimalFormat formatter = new DecimalFormat("#,##0.0"); - buf.append(formatter.format((double) numBytes / (1024.0 * 1024.0 * 1024.0))) + buf.append(formatter.format(numBytes / (1024.0 * 1024.0 * 1024.0))) .append(" GB"); } } return buf; } + @Override public Object parseObject(String source, ParsePosition pos) { return null; } diff --git a/src/main/java/com/gitblit/utils/ClientLogger.java b/src/main/java/com/gitblit/utils/ClientLogger.java index 7d18f3d6..3570cbe9 100644 --- a/src/main/java/com/gitblit/utils/ClientLogger.java +++ b/src/main/java/com/gitblit/utils/ClientLogger.java @@ -26,9 +26,9 @@ import org.slf4j.LoggerFactory; /** * Class to log messages to the pushing Git client. Intended to be used by the * Groovy Hooks. - * + * * @author John Crygier - * + * */ public class ClientLogger { @@ -41,7 +41,7 @@ public class ClientLogger { /** * Sends an info/warning message to the git client. - * + * * @param message */ public void info(String message) { @@ -50,7 +50,7 @@ public class ClientLogger { /** * Sends an error message to the git client. - * + * * @param message */ public void error(String message) { @@ -59,7 +59,7 @@ public class ClientLogger { /** * Sends an error message to the git client with an exception. - * + * * @param message * @param t * an exception diff --git a/src/main/java/com/gitblit/utils/CommitCache.java b/src/main/java/com/gitblit/utils/CommitCache.java index e84506ea..fd3a6597 100644 --- a/src/main/java/com/gitblit/utils/CommitCache.java +++ b/src/main/java/com/gitblit/utils/CommitCache.java @@ -35,36 +35,36 @@ import com.gitblit.models.RepositoryCommit; /** * Caches repository commits for re-use in the dashboard and activity pages. - * + * * @author James Moger * */ public class CommitCache { - + private static final CommitCache instance; - + protected final Logger logger = LoggerFactory.getLogger(getClass()); - + protected final Map<String, ObjectCache<List<RepositoryCommit>>> cache; - + protected int cacheDays = -1; - + public static CommitCache instance() { return instance; } - + static { instance = new CommitCache(); } - + protected CommitCache() { cache = new ConcurrentHashMap<String, ObjectCache<List<RepositoryCommit>>>(); } - + /** * Returns the cutoff date for the cache. Commits after this date are cached. * Commits before this date are not cached. - * + * * @return */ public Date getCutoffDate() { @@ -77,28 +77,28 @@ public class CommitCache { cal.add(Calendar.DATE, -1*cacheDays); return cal.getTime(); } - + /** * Sets the number of days to cache. - * + * * @param days */ public synchronized void setCacheDays(int days) { this.cacheDays = days; clear(); } - + /** * Clears the entire commit cache. - * + * */ public void clear() { cache.clear(); } - + /** * Clears the commit cache for a specific repository. - * + * * @param repositoryName */ public void clear(String repositoryName) { @@ -108,10 +108,10 @@ public class CommitCache { logger.info(MessageFormat.format("{0} commit cache cleared", repositoryName)); } } - + /** * Clears the commit cache for a specific branch of a specific repository. - * + * * @param repositoryName * @param branch */ @@ -125,10 +125,10 @@ public class CommitCache { } } } - + /** * Get all commits for the specified repository:branch that are in the cache. - * + * * @param repositoryName * @param repository * @param branch @@ -137,12 +137,12 @@ public class CommitCache { public List<RepositoryCommit> getCommits(String repositoryName, Repository repository, String branch) { return getCommits(repositoryName, repository, branch, getCutoffDate()); } - + /** * Get all commits for the specified repository:branch since a specific date. * These commits may be retrieved from the cache if the sinceDate is after * the cacheCutoffDate. - * + * * @param repositoryName * @param repository * @param branch @@ -159,13 +159,13 @@ public class CommitCache { if (!cache.containsKey(repoKey)) { cache.put(repoKey, new ObjectCache<List<RepositoryCommit>>()); } - + ObjectCache<List<RepositoryCommit>> repoCache = cache.get(repoKey); String branchKey = branch.toLowerCase(); - + RevCommit tip = JGitUtils.getCommit(repository, branch); Date tipDate = JGitUtils.getCommitDate(tip); - + List<RepositoryCommit> commits; if (!repoCache.hasCurrent(branchKey, tipDate)) { commits = repoCache.getObject(branchKey); @@ -193,7 +193,7 @@ public class CommitCache { // update cache repoCache.updateObject(branchKey, tipDate, commits); } - + if (sinceDate.equals(cacheCutoffDate)) { list = commits; } else { @@ -210,10 +210,10 @@ public class CommitCache { } return list; } - + /** - * Returns a list of commits for the specified repository branch. - * + * Returns a list of commits for the specified repository branch. + * * @param repositoryName * @param repository * @param branch @@ -230,10 +230,10 @@ public class CommitCache { } return commits; } - + /** - * Returns a list of commits for the specified repository branch since the specified commit. - * + * Returns a list of commits for the specified repository branch since the specified commit. + * * @param repositoryName * @param repository * @param branch @@ -250,10 +250,10 @@ public class CommitCache { } return commits; } - + /** * Reduces the list of commits to those since the specified date. - * + * * @param commits * @param sinceDate * @return a list of commits diff --git a/src/main/java/com/gitblit/utils/CompressionUtils.java b/src/main/java/com/gitblit/utils/CompressionUtils.java index a8dcdd8f..2bf1f130 100644 --- a/src/main/java/com/gitblit/utils/CompressionUtils.java +++ b/src/main/java/com/gitblit/utils/CompressionUtils.java @@ -43,9 +43,9 @@ import org.slf4j.LoggerFactory; /**
* Collection of static methods for retrieving information from a repository.
- *
+ *
* @author James Moger
- *
+ *
*/
public class CompressionUtils {
@@ -53,7 +53,7 @@ public class CompressionUtils { /**
* Log an error message and exception.
- *
+ *
* @param t
* @param repository
* if repository is not null it MUST be the {0} parameter in the
@@ -77,7 +77,7 @@ public class CompressionUtils { /**
* Zips the contents of the tree at the (optionally) specified revision and
* the (optionally) specified basepath to the supplied outputstream.
- *
+ *
* @param repository
* @param basePath
* if unspecified, entire repository is assumed.
@@ -137,11 +137,11 @@ public class CompressionUtils { }
return success;
}
-
+
/**
* tar the contents of the tree at the (optionally) specified revision and
* the (optionally) specified basepath to the supplied outputstream.
- *
+ *
* @param repository
* @param basePath
* if unspecified, entire repository is assumed.
@@ -155,11 +155,11 @@ public class CompressionUtils { OutputStream os) {
return tar(null, repository, basePath, objectId, os);
}
-
+
/**
* tar.gz the contents of the tree at the (optionally) specified revision and
* the (optionally) specified basepath to the supplied outputstream.
- *
+ *
* @param repository
* @param basePath
* if unspecified, entire repository is assumed.
@@ -173,11 +173,11 @@ public class CompressionUtils { OutputStream os) {
return tar(CompressorStreamFactory.GZIP, repository, basePath, objectId, os);
}
-
+
/**
* tar.xz the contents of the tree at the (optionally) specified revision and
* the (optionally) specified basepath to the supplied outputstream.
- *
+ *
* @param repository
* @param basePath
* if unspecified, entire repository is assumed.
@@ -191,11 +191,11 @@ public class CompressionUtils { OutputStream os) {
return tar(CompressorStreamFactory.XZ, repository, basePath, objectId, os);
}
-
+
/**
* tar.bzip2 the contents of the tree at the (optionally) specified revision and
* the (optionally) specified basepath to the supplied outputstream.
- *
+ *
* @param repository
* @param basePath
* if unspecified, entire repository is assumed.
@@ -207,15 +207,15 @@ public class CompressionUtils { */
public static boolean bzip2(Repository repository, String basePath, String objectId,
OutputStream os) {
-
+
return tar(CompressorStreamFactory.BZIP2, repository, basePath, objectId, os);
}
-
+
/**
* Compresses/archives the contents of the tree at the (optionally)
* specified revision and the (optionally) specified basepath to the
* supplied outputstream.
- *
+ *
* @param algorithm
* compression algorithm for tar (optional)
* @param repository
@@ -233,7 +233,7 @@ public class CompressionUtils { if (commit == null) {
return false;
}
-
+
OutputStream cos = os;
if (!StringUtils.isEmpty(algorithm)) {
try {
@@ -264,7 +264,7 @@ public class CompressionUtils { continue;
}
tw.getObjectId(id, 0);
-
+
ObjectLoader loader = repository.open(id);
if (FileMode.SYMLINK == mode) {
TarArchiveEntry entry = new TarArchiveEntry(tw.getPathString(),TarArchiveEntry.LF_SYMLINK);
@@ -279,7 +279,7 @@ public class CompressionUtils { entry.setMode(mode.getBits());
entry.setModTime(modified);
entry.setSize(loader.getSize());
- tos.putArchiveEntry(entry);
+ tos.putArchiveEntry(entry);
loader.copyTo(tos);
tos.closeArchiveEntry();
}
diff --git a/src/main/java/com/gitblit/utils/ConnectionUtils.java b/src/main/java/com/gitblit/utils/ConnectionUtils.java index feeedd21..b2bd0601 100644 --- a/src/main/java/com/gitblit/utils/ConnectionUtils.java +++ b/src/main/java/com/gitblit/utils/ConnectionUtils.java @@ -38,9 +38,9 @@ import javax.net.ssl.X509TrustManager; /**
* Utility class for establishing HTTP/HTTPS connections.
- *
+ *
* @author James Moger
- *
+ *
*/
public class ConnectionUtils {
@@ -61,7 +61,7 @@ public class ConnectionUtils { SSL_CONTEXT = context;
HOSTNAME_VERIFIER = new DummyHostnameVerifier();
CHARSET = "UTF-8";
-
+
// Disable Java 7 SNI checks
// http://stackoverflow.com/questions/7615645/ssl-handshake-alert-unrecognized-name-error-since-upgrade-to-java-1-7-0
System.setProperty("jsse.enableSNIExtension", "false");
@@ -97,7 +97,7 @@ public class ConnectionUtils { }
return conn;
}
-
+
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -183,7 +183,7 @@ public class ConnectionUtils { /**
* DummyTrustManager trusts all certificates.
- *
+ *
* @author James Moger
*/
private static class DummyTrustManager implements X509TrustManager {
@@ -206,7 +206,7 @@ public class ConnectionUtils { /**
* Trusts all hostnames from a certificate, including self-signed certs.
- *
+ *
* @author James Moger
*/
private static class DummyHostnameVerifier implements HostnameVerifier {
diff --git a/src/main/java/com/gitblit/utils/ContainerUtils.java b/src/main/java/com/gitblit/utils/ContainerUtils.java index 919f99d6..613bf97a 100644 --- a/src/main/java/com/gitblit/utils/ContainerUtils.java +++ b/src/main/java/com/gitblit/utils/ContainerUtils.java @@ -27,7 +27,7 @@ import com.gitblit.Keys; /**
* This is the support class for all container specific code.
- *
+ *
* @author jpyeron
*/
public class ContainerUtils
@@ -37,7 +37,7 @@ public class ContainerUtils /**
* The support class for managing and evaluating the environment with
* regards to CVE-2007-0405.
- *
+ *
* @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2007-0450
* @author jpyeron
*/
@@ -80,7 +80,7 @@ public class ContainerUtils * blocked from use in certain URL s. It will emit a warning to the
* logger if the configuration of Tomcat causes the URL processing to
* fail on %2F.
- *
+ *
* @return true if it recognizes Tomcat, false if it does not recognize
* Tomcat
*/
@@ -96,7 +96,7 @@ public class ContainerUtils // mb.setBytes(test, 0, test.length);
Method mByteChunck_setBytes = cByteChunk.getMethod("setBytes", byte[].class, int.class, int.class);
- mByteChunck_setBytes.invoke(mb, test, (int) 0, test.length);
+ mByteChunck_setBytes.invoke(mb, test, 0, test.length);
// UDecoder ud=new UDecoder();
Class<?> cUDecoder = Class.forName("org.apache.tomcat.util.buf.UDecoder");
diff --git a/src/main/java/com/gitblit/utils/DeepCopier.java b/src/main/java/com/gitblit/utils/DeepCopier.java index 5df30623..5d89606c 100644 --- a/src/main/java/com/gitblit/utils/DeepCopier.java +++ b/src/main/java/com/gitblit/utils/DeepCopier.java @@ -57,7 +57,7 @@ public class DeepCopier { * very large objects. The current thread is used for serializing the
* original object in order to respect any synchronization the caller may
* have around it, and a new thread is used for deserializing the copy.
- *
+ *
*/
public static <T> T copyParallel(T original) {
try {
@@ -88,6 +88,7 @@ public class DeepCopier { start();
}
+ @Override
@SuppressWarnings("unchecked")
public void run() {
diff --git a/src/main/java/com/gitblit/utils/DiffUtils.java b/src/main/java/com/gitblit/utils/DiffUtils.java index 3c52cb03..107f6ab3 100644 --- a/src/main/java/com/gitblit/utils/DiffUtils.java +++ b/src/main/java/com/gitblit/utils/DiffUtils.java @@ -66,23 +66,23 @@ public class DiffUtils { return null;
}
}
-
+
/**
- * Encapsulates the output of a diff.
+ * Encapsulates the output of a diff.
*/
public static class DiffOutput implements Serializable {
private static final long serialVersionUID = 1L;
-
+
public final DiffOutputType type;
public final String content;
public final DiffStat stat;
-
+
DiffOutput(DiffOutputType type, String content, DiffStat stat) {
this.type = type;
this.content = content;
this.stat = stat;
}
-
+
public PathChangeModel getPath(String path) {
if (stat == null) {
return null;
@@ -98,15 +98,15 @@ public class DiffUtils { public static class DiffStat implements Serializable {
private static final long serialVersionUID = 1L;
-
+
public final List<PathChangeModel> paths = new ArrayList<PathChangeModel>();
-
+
private final String commitId;
-
+
public DiffStat(String commitId) {
this.commitId = commitId;
}
-
+
public PathChangeModel addPath(DiffEntry entry) {
PathChangeModel pcm = PathChangeModel.from(entry, commitId);
paths.add(pcm);
@@ -128,7 +128,7 @@ public class DiffUtils { }
return val;
}
-
+
public PathChangeModel getPath(String path) {
PathChangeModel stat = null;
for (PathChangeModel p : paths) {
@@ -138,7 +138,7 @@ public class DiffUtils { }
}
return stat;
- }
+ }
@Override
public String toString() {
@@ -150,15 +150,15 @@ public class DiffUtils { return sb.toString();
}
}
-
+
public static class NormalizedDiffStat implements Serializable {
-
+
private static final long serialVersionUID = 1L;
-
+
public final int insertions;
public final int deletions;
public final int blanks;
-
+
NormalizedDiffStat(int insertions, int deletions, int blanks) {
this.insertions = insertions;
this.deletions = deletions;
@@ -282,7 +282,7 @@ public class DiffUtils { } catch (Throwable t) {
LOGGER.error("failed to generate commit diff!", t);
}
-
+
return new DiffOutput(outputType, diff, stat);
}
@@ -442,10 +442,10 @@ public class DiffUtils { }
return lines;
}
-
+
/**
* Normalizes a diffstat to an N-segment display.
- *
+ *
* @params segments
* @param insertions
* @param deletions
@@ -482,7 +482,7 @@ public class DiffUtils { sd = segments - si;
sb = 0;
}
-
+
return new NormalizedDiffStat(si, sd, sb);
}
}
diff --git a/src/main/java/com/gitblit/utils/FederationUtils.java b/src/main/java/com/gitblit/utils/FederationUtils.java index 4d6060dd..e1a3d008 100644 --- a/src/main/java/com/gitblit/utils/FederationUtils.java +++ b/src/main/java/com/gitblit/utils/FederationUtils.java @@ -44,9 +44,9 @@ import com.google.gson.reflect.TypeToken; /**
* Utility methods for federation functions.
- *
+ *
* @author James Moger
- *
+ *
*/
public class FederationUtils {
@@ -66,7 +66,7 @@ public class FederationUtils { /**
* Returns an url to this servlet for the specified parameters.
- *
+ *
* @param sourceURL
* the url of the source gitblit instance
* @param token
@@ -79,7 +79,7 @@ public class FederationUtils { }
/**
- *
+ *
* @param remoteURL
* the url of the remote gitblit instance
* @param tokenType
@@ -109,7 +109,7 @@ public class FederationUtils { /**
* Returns the list of federated gitblit instances that this instance will
* try to pull.
- *
+ *
* @return list of registered gitblit instances
*/
public static List<FederationModel> getFederationRegistrations(IStoredSettings settings) {
@@ -194,7 +194,7 @@ public class FederationUtils { * sent by an pulling Gitblit instance to an origin Gitblit instance as part
* of the proposal process. This is to ensure that the pulling Gitblit
* instance has an IP route to the origin instance.
- *
+ *
* @param remoteUrl
* the remote Gitblit instance to send a federation proposal to
* @param proposal
@@ -210,7 +210,7 @@ public class FederationUtils { /**
* Sends a federation proposal to the Gitblit instance at remoteUrl
- *
+ *
* @param remoteUrl
* the remote Gitblit instance to send a federation proposal to
* @param proposal
@@ -246,7 +246,7 @@ public class FederationUtils { /**
* Retrieves a map of the repositories at the remote gitblit instance keyed
* by the repository clone url.
- *
+ *
* @param registration
* @param checkExclusions
* should returned repositories remove registration exclusions
@@ -272,7 +272,7 @@ public class FederationUtils { /**
* Tries to pull the gitblit user accounts from the remote gitblit instance.
- *
+ *
* @param registration
* @return a collection of UserModel objects
* @throws Exception
@@ -287,7 +287,7 @@ public class FederationUtils { /**
* Tries to pull the gitblit team definitions from the remote gitblit
* instance.
- *
+ *
* @param registration
* @return a collection of TeamModel objects
* @throws Exception
@@ -302,7 +302,7 @@ public class FederationUtils { /**
* Tries to pull the gitblit server settings from the remote gitblit
* instance.
- *
+ *
* @param registration
* @return a map of the remote gitblit settings
* @throws Exception
@@ -315,7 +315,7 @@ public class FederationUtils { /**
* Tries to pull the referenced scripts from the remote gitblit instance.
- *
+ *
* @param registration
* @return a map of the remote gitblit scripts by script name
* @throws Exception
@@ -328,7 +328,7 @@ public class FederationUtils { /**
* Send an status acknowledgment to the remote Gitblit server.
- *
+ *
* @param identification
* identification of this pulling instance
* @param registration
diff --git a/src/main/java/com/gitblit/utils/FileUtils.java b/src/main/java/com/gitblit/utils/FileUtils.java index f3a25987..a1eb5bba 100644 --- a/src/main/java/com/gitblit/utils/FileUtils.java +++ b/src/main/java/com/gitblit/utils/FileUtils.java @@ -29,12 +29,12 @@ import java.nio.charset.Charset; /**
* Common file utilities.
- *
+ *
* @author James Moger
- *
+ *
*/
public class FileUtils {
-
+
/** 1024 (number of bytes in one kilobyte) */
public static final int KB = 1024;
@@ -47,7 +47,7 @@ public class FileUtils { /**
* Returns an int from a string representation of a file size.
* e.g. 50m = 50 megabytes
- *
+ *
* @param aString
* @param defaultValue
* @return an int value or the defaultValue if aString can not be parsed
@@ -55,24 +55,24 @@ public class FileUtils { public static int convertSizeToInt(String aString, int defaultValue) {
return (int) convertSizeToLong(aString, defaultValue);
}
-
+
/**
* Returns a long from a string representation of a file size.
* e.g. 50m = 50 megabytes
- *
+ *
* @param aString
* @param defaultValue
* @return a long value or the defaultValue if aString can not be parsed
*/
public static long convertSizeToLong(String aString, long defaultValue) {
- // trim string and remove all spaces
+ // trim string and remove all spaces
aString = aString.toLowerCase().trim();
StringBuilder sb = new StringBuilder();
for (String a : aString.split(" ")) {
sb.append(a);
}
aString = sb.toString();
-
+
// identify value and unit
int idx = 0;
int len = aString.length();
@@ -99,10 +99,10 @@ public class FileUtils { }
return defaultValue;
}
-
+
/**
* Returns the byte [] content of the specified file.
- *
+ *
* @param file
* @return the byte content of the file
*/
@@ -130,7 +130,7 @@ public class FileUtils { /**
* Returns the string content of the specified file.
- *
+ *
* @param file
* @param lineEnding
* @return the string content of the file
@@ -166,7 +166,7 @@ public class FileUtils { /**
* Writes the string content to the file.
- *
+ *
* @param file
* @param content
*/
@@ -195,14 +195,14 @@ public class FileUtils { /**
* Recursively traverses a folder and its subfolders to calculate the total
* size in bytes.
- *
+ *
* @param directory
* @return folder size in bytes
*/
public static long folderSize(File directory) {
if (directory == null || !directory.exists()) {
return -1;
- }
+ }
if (directory.isDirectory()) {
long length = 0;
for (File file : directory.listFiles()) {
@@ -241,7 +241,7 @@ public class FileUtils { /**
* Copies a file or folder (recursively) to a destination folder.
- *
+ *
* @param destinationFolder
* @param filesOrFolders
* @return
@@ -281,11 +281,11 @@ public class FileUtils { }
}
}
-
+
/**
* Determine the relative path between two files. Takes into account
* canonical paths, if possible.
- *
+ *
* @param basePath
* @param path
* @return a relative path from basePath to path
@@ -309,11 +309,11 @@ public class FileUtils { // no relative relationship
return null;
}
-
+
/**
* Returns the exact path for a file. This path will be the canonical path
* unless an exception is thrown in which case it will be the absolute path.
- *
+ *
* @param path
* @return the exact file
*/
@@ -327,7 +327,7 @@ public class FileUtils { public static File resolveParameter(String parameter, File aFolder, String path) {
if (aFolder == null) {
- // strip any parameter reference
+ // strip any parameter reference
path = path.replace(parameter, "").trim();
if (path.length() > 0 && path.charAt(0) == '/') {
// strip leading /
diff --git a/src/main/java/com/gitblit/utils/GitBlitDiffFormatter.java b/src/main/java/com/gitblit/utils/GitBlitDiffFormatter.java index 8ca42854..47ff143a 100644 --- a/src/main/java/com/gitblit/utils/GitBlitDiffFormatter.java +++ b/src/main/java/com/gitblit/utils/GitBlitDiffFormatter.java @@ -34,9 +34,9 @@ import com.gitblit.utils.DiffUtils.DiffStat; /**
* Generates an html snippet of a diff in Gitblit's style, tracks changed paths,
* and calculates diff stats.
- *
+ *
* @author James Moger
- *
+ *
*/
public class GitBlitDiffFormatter extends DiffFormatter {
@@ -47,22 +47,22 @@ public class GitBlitDiffFormatter extends DiffFormatter { private PathChangeModel currentPath;
private int left, right;
-
+
public GitBlitDiffFormatter(OutputStream os, String commitId) {
super(os);
this.os = os;
this.diffStat = new DiffStat(commitId);
}
-
+
@Override
public void format(DiffEntry ent) throws IOException {
currentPath = diffStat.addPath(ent);
super.format(ent);
}
-
+
/**
* Output a hunk header
- *
+ *
* @param aStartLine
* within first source
* @param aEndLine
@@ -88,7 +88,7 @@ public class GitBlitDiffFormatter extends DiffFormatter { left = aStartLine + 1;
right = bStartLine + 1;
}
-
+
protected void writeRange(final char prefix, final int begin, final int cnt) throws IOException {
os.write(' ');
os.write(prefix);
@@ -127,7 +127,7 @@ public class GitBlitDiffFormatter extends DiffFormatter { throws IOException {
// update entry diffstat
currentPath.update(prefix);
-
+
// output diff
os.write("<tr>".getBytes());
switch (prefix) {
@@ -162,7 +162,7 @@ public class GitBlitDiffFormatter extends DiffFormatter { /**
* Workaround function for complex private methods in DiffFormatter. This
* sets the html for the diff headers.
- *
+ *
* @return
*/
public String getHtml() {
@@ -191,10 +191,10 @@ public class GitBlitDiffFormatter extends DiffFormatter { } else {
// use a
line = line.substring("diff --git ".length()).trim();
- line = line.substring(line.startsWith("\"a/") ? 3 : 2);
+ line = line.substring(line.startsWith("\"a/") ? 3 : 2);
line = line.substring(0, line.indexOf(" b/") > -1 ? line.indexOf(" b/") : line.indexOf("\"b/")).trim();
}
-
+
if (line.charAt(0) == '"') {
line = line.substring(1);
}
@@ -205,7 +205,7 @@ public class GitBlitDiffFormatter extends DiffFormatter { sb.append("</tbody></table></div>\n");
inFile = false;
}
-
+
sb.append(MessageFormat.format("<div class='header'><div class=\"diffHeader\" id=\"{0}\"><i class=\"icon-file\"></i> ", line)).append(line).append("</div></div>");
sb.append("<div class=\"diff\">");
sb.append("<table><tbody>");
@@ -229,7 +229,7 @@ public class GitBlitDiffFormatter extends DiffFormatter { sb.append("</table></div>");
return sb.toString();
}
-
+
public DiffStat getDiffStat() {
return diffStat;
}
diff --git a/src/main/java/com/gitblit/utils/HttpUtils.java b/src/main/java/com/gitblit/utils/HttpUtils.java index 86f53cfe..ffea81cd 100644 --- a/src/main/java/com/gitblit/utils/HttpUtils.java +++ b/src/main/java/com/gitblit/utils/HttpUtils.java @@ -30,15 +30,15 @@ import com.gitblit.utils.X509Utils.X509Metadata; /**
* Collection of utility methods for http requests.
- *
+ *
* @author James Moger
- *
+ *
*/
public class HttpUtils {
/**
* Returns the Gitblit URL based on the request.
- *
+ *
* @param request
* @return the host url
*/
@@ -59,7 +59,7 @@ public class HttpUtils { } catch (Throwable t) {
}
}
-
+
// try to use reverse-proxy server's scheme
String forwardedScheme = request.getHeader("X-Forwarded-Proto");
if (StringUtils.isEmpty(forwardedScheme)) {
@@ -68,7 +68,7 @@ public class HttpUtils { if (!StringUtils.isEmpty(forwardedScheme)) {
// reverse-proxy server has supplied the original scheme
scheme = forwardedScheme;
-
+
if ("https".equals(scheme) && port == 80) {
// proxy server is https, inside server is 80
// this is likely because the proxy server has not supplied
@@ -77,7 +77,7 @@ public class HttpUtils { port = 443;
}
}
-
+
String context = request.getContextPath();
String forwardedContext = request.getHeader("X-Forwarded-Context");
if (forwardedContext != null) {
@@ -86,12 +86,12 @@ public class HttpUtils { if (!StringUtils.isEmpty(forwardedContext)) {
context = forwardedContext;
}
-
+
// trim any trailing slash
if (context.length() > 0 && context.charAt(context.length() - 1) == '/') {
context = context.substring(1);
}
-
+
StringBuilder sb = new StringBuilder();
sb.append(scheme);
sb.append("://");
@@ -103,11 +103,11 @@ public class HttpUtils { sb.append(context);
return sb.toString();
}
-
+
/**
* Returns a user model object built from attributes in the SSL certificate.
* This model is not retrieved from the user service.
- *
+ *
* @param httpRequest
* @param checkValidity ensure certificate can be used now
* @param usernameOIDs if unspecified, CN is used as the username
@@ -136,7 +136,7 @@ public class HttpUtils { }
return null;
}
-
+
/**
* Creates a UserModel from a certificate
* @param cert
@@ -145,16 +145,16 @@ public class HttpUtils { */
public static UserModel getUserModelFromCertificate(X509Certificate cert, String... usernameOIDs) {
X509Metadata metadata = X509Utils.getMetadata(cert);
-
+
UserModel user = new UserModel(metadata.commonName);
user.emailAddress = metadata.emailAddress;
user.isAuthenticated = false;
-
+
if (usernameOIDs == null || usernameOIDs.length == 0) {
// use default usename<->CN mapping
usernameOIDs = new String [] { "CN" };
}
-
+
// determine username from OID fingerprint
StringBuilder an = new StringBuilder();
for (String oid : usernameOIDs) {
@@ -163,10 +163,10 @@ public class HttpUtils { an.append(val).append(' ');
}
}
- user.username = an.toString().trim();
+ user.username = an.toString().trim();
return user;
}
-
+
public static X509Metadata getCertificateMetadata(HttpServletRequest httpRequest) {
if (httpRequest.getAttribute("javax.servlet.request.X509Certificate") != null) {
X509Certificate[] certChain = (X509Certificate[]) httpRequest
@@ -178,7 +178,7 @@ public class HttpUtils { }
return null;
}
-
+
public static boolean isIpAddress(String address) {
if (StringUtils.isEmpty(address)) {
return false;
diff --git a/src/main/java/com/gitblit/utils/JGitUtils.java b/src/main/java/com/gitblit/utils/JGitUtils.java index c494ccc3..75a44058 100644 --- a/src/main/java/com/gitblit/utils/JGitUtils.java +++ b/src/main/java/com/gitblit/utils/JGitUtils.java @@ -92,9 +92,9 @@ import com.gitblit.models.SubmoduleModel; /**
* Collection of static methods for retrieving information from a repository.
- *
+ *
* @author James Moger
- *
+ *
*/
public class JGitUtils {
@@ -102,7 +102,7 @@ public class JGitUtils { /**
* Log an error message and exception.
- *
+ *
* @param t
* @param repository
* if repository is not null it MUST be the {0} parameter in the
@@ -126,7 +126,7 @@ public class JGitUtils { /**
* Returns the displayable name of the person in the form "Real Name <email
* address>". If the email address is empty, just "Real Name" is returned.
- *
+ *
* @param person
* @return "Real Name <email address>" or "Real Name"
*/
@@ -155,7 +155,7 @@ public class JGitUtils { * Clone or Fetch a repository. If the local repository does not exist,
* clone is called. If the repository does exist, fetch is called. By
* default the clone/fetch retrieves the remote heads, tags, and notes.
- *
+ *
* @param repositoriesFolder
* @param name
* @param fromUrl
@@ -171,7 +171,7 @@ public class JGitUtils { * Clone or Fetch a repository. If the local repository does not exist,
* clone is called. If the repository does exist, fetch is called. By
* default the clone/fetch retrieves the remote heads, tags, and notes.
- *
+ *
* @param repositoriesFolder
* @param name
* @param fromUrl
@@ -212,7 +212,7 @@ public class JGitUtils { clone.setCredentialsProvider(credentialsProvider);
}
Repository repository = clone.call().getRepository();
-
+
// Now we have to fetch because CloneCommand doesn't fetch
// refs/notes nor does it allow manual RefSpec.
result.createdRepository = true;
@@ -225,7 +225,7 @@ public class JGitUtils { /**
* Fetch updates from the remote repository. If refSpecs is unspecifed,
* remote heads, tags, and notes are retrieved.
- *
+ *
* @param credentialsProvider
* @param repository
* @param refSpecs
@@ -254,7 +254,7 @@ public class JGitUtils { /**
* Creates a bare repository.
- *
+ *
* @param repositoriesFolder
* @param name
* @return Repository
@@ -444,7 +444,7 @@ public class JGitUtils { /**
* Returns a list of repository names in the specified folder.
- *
+ *
* @param repositoriesFolder
* @param onlyBare
* if true, only bare repositories repositories are listed. If
@@ -478,7 +478,7 @@ public class JGitUtils { /**
* Recursive function to find git repositories.
- *
+ *
* @param basePath
* basePath is stripped from the repository name as repositories
* are relative to this path
@@ -501,7 +501,7 @@ public class JGitUtils { if (depth == 0) {
return list;
}
-
+
int nextDepth = (depth == -1) ? -1 : depth - 1;
for (File file : searchFolder.listFiles()) {
if (file.isDirectory()) {
@@ -546,7 +546,7 @@ public class JGitUtils { /**
* Returns the first commit on a branch. If the repository does not exist or
* is empty, null is returned.
- *
+ *
* @param repository
* @param branch
* if unspecified, HEAD is assumed.
@@ -582,7 +582,7 @@ public class JGitUtils { * Returns the date of the first commit on a branch. If the repository does
* not exist, Date(0) is returned. If the repository does exist bit is
* empty, the last modified date of the repository folder is returned.
- *
+ *
* @param repository
* @param branch
* if unspecified, HEAD is assumed.
@@ -603,7 +603,7 @@ public class JGitUtils { /**
* Determine if a repository has any commits. This is determined by checking
* the for loose and packed objects.
- *
+ *
* @param repository
* @return true if the repository has commits
*/
@@ -614,18 +614,18 @@ public class JGitUtils { }
return false;
}
-
+
/**
* Encapsulates the result of cloning or pulling from a repository.
*/
public static class LastChange {
public Date when;
public String who;
-
+
LastChange() {
- when = new Date(0);
+ when = new Date(0);
}
-
+
LastChange(long lastModified) {
this.when = new Date(lastModified);
}
@@ -635,7 +635,7 @@ public class JGitUtils { * Returns the date and author of the most recent commit on a branch. If the
* repository does not exist Date(0) is returned. If it does exist but is
* empty, the last modified date of the repository folder is returned.
- *
+ *
* @param repository
* @return a LastChange object
*/
@@ -652,7 +652,7 @@ public class JGitUtils { List<RefModel> branchModels = getLocalBranches(repository, true, -1);
if (branchModels.size() > 0) {
// find most recent branch update
- LastChange lastChange = new LastChange();
+ LastChange lastChange = new LastChange();
for (RefModel branchModel : branchModels) {
if (branchModel.getDate().after(lastChange.when)) {
lastChange.when = branchModel.getDate();
@@ -661,14 +661,14 @@ public class JGitUtils { }
return lastChange;
}
-
+
// default to the repository folder modification date
return new LastChange(repository.getDirectory().lastModified());
}
/**
* Retrieves a Java Date from a Git commit.
- *
+ *
* @param commit
* @return date of the commit or Date(0) if the commit is null
*/
@@ -681,7 +681,7 @@ public class JGitUtils { /**
* Retrieves a Java Date from a Git commit.
- *
+ *
* @param commit
* @return date of the commit or Date(0) if the commit is null
*/
@@ -695,7 +695,7 @@ public class JGitUtils { /**
* Returns the specified commit from the repository. If the repository does
* not exist or is empty, null is returned.
- *
+ *
* @param repository
* @param objectId
* if unspecified, HEAD is assumed.
@@ -726,7 +726,7 @@ public class JGitUtils { /**
* Retrieves the raw byte content of a file in the specified tree.
- *
+ *
* @param repository
* @param tree
* if null, the RevTree from HEAD is assumed.
@@ -782,7 +782,7 @@ public class JGitUtils { /**
* Returns the UTF-8 string content of a file in the specified tree.
- *
+ *
* @param repository
* @param tree
* if null, the RevTree from HEAD is assumed.
@@ -800,7 +800,7 @@ public class JGitUtils { /**
* Gets the raw byte content of the specified blob object.
- *
+ *
* @param repository
* @param objectId
* @return byte [] blob content
@@ -831,7 +831,7 @@ public class JGitUtils { /**
* Gets the UTF-8 string content of the blob specified by objectId.
- *
+ *
* @param repository
* @param objectId
* @param charsets optional
@@ -849,7 +849,7 @@ public class JGitUtils { * Returns the list of files in the specified folder at the specified
* commit. If the repository does not exist or is empty, an empty list is
* returned.
- *
+ *
* @param repository
* @param path
* if unspecified, root folder is assumed.
@@ -900,11 +900,11 @@ public class JGitUtils { Collections.sort(list);
return list;
}
-
+
/**
* Returns the list of files changed in a specified commit. If the
* repository does not exist or is empty, an empty list is returned.
- *
+ *
* @param repository
* @param commit
* if null, HEAD is assumed.
@@ -917,7 +917,7 @@ public class JGitUtils { /**
* Returns the list of files changed in a specified commit. If the
* repository does not exist or is empty, an empty list is returned.
- *
+ *
* @param repository
* @param commit
* if null, HEAD is assumed.
@@ -958,7 +958,7 @@ public class JGitUtils { for (DiffEntry diff : diffs) {
// create the path change model
PathChangeModel pcm = PathChangeModel.from(diff, commit.getName());
-
+
if (calculateDiffStat) {
// update file diffstats
df.format(diff);
@@ -982,7 +982,7 @@ public class JGitUtils { /**
* Returns the list of files changed in a specified commit. If the
* repository does not exist or is empty, an empty list is returned.
- *
+ *
* @param repository
* @param startCommit
* earliest commit
@@ -1005,7 +1005,7 @@ public class JGitUtils { for (DiffEntry diff : diffEntries) {
PathChangeModel pcm = PathChangeModel.from(diff, null);
list.add(pcm);
- }
+ }
Collections.sort(list);
} catch (Throwable t) {
error(t, repository, "{0} failed to determine files in range {1}..{2}!", startCommit, endCommit);
@@ -1016,7 +1016,7 @@ public class JGitUtils { * Returns the list of files in the repository on the default branch that
* match one of the specified extensions. This is a CASE-SENSITIVE search.
* If the repository does not exist or is empty, an empty list is returned.
- *
+ *
* @param repository
* @param extensions
* @return list of files in repository with a matching extension
@@ -1029,7 +1029,7 @@ public class JGitUtils { * Returns the list of files in the repository in the specified commit that
* match one of the specified extensions. This is a CASE-SENSITIVE search.
* If the repository does not exist or is empty, an empty list is returned.
- *
+ *
* @param repository
* @param extensions
* @param objectId
@@ -1078,7 +1078,7 @@ public class JGitUtils { /**
* Returns a path model of the current file in the treewalk.
- *
+ *
* @param tw
* @param basePath
* @param commit
@@ -1106,7 +1106,7 @@ public class JGitUtils { /**
* Returns a permissions representation of the mode bits.
- *
+ *
* @param mode
* @return string representation of the mode bits
*/
@@ -1128,7 +1128,7 @@ public class JGitUtils { /**
* Returns a list of commits since the minimum date starting from the
* specified object id.
- *
+ *
* @param repository
* @param objectId
* if unspecified, HEAD is assumed.
@@ -1166,7 +1166,7 @@ public class JGitUtils { /**
* Returns a list of commits starting from HEAD and working backwards.
- *
+ *
* @param repository
* @param maxCount
* if < 0, all commits for the repository are returned.
@@ -1181,7 +1181,7 @@ public class JGitUtils { * offset and maxCount for paging. This is similar to LIMIT n OFFSET p in
* SQL. If the repository does not exist or is empty, an empty list is
* returned.
- *
+ *
* @param repository
* @param objectId
* if unspecified, HEAD is assumed.
@@ -1200,7 +1200,7 @@ public class JGitUtils { * repository. Caller may specify ending revision with objectId. Caller may
* specify offset and maxCount to achieve pagination of results. If the
* repository does not exist or is empty, an empty list is returned.
- *
+ *
* @param repository
* @param objectId
* if unspecified, HEAD is assumed.
@@ -1245,7 +1245,7 @@ public class JGitUtils { RevWalk rw = new RevWalk(repository);
rw.markStart(rw.parseCommit(endRange));
if (startRange != null) {
- rw.markUninteresting(rw.parseCommit(startRange));
+ rw.markUninteresting(rw.parseCommit(startRange));
}
if (!StringUtils.isEmpty(path)) {
TreeFilter filter = AndTreeFilter.create(
@@ -1284,7 +1284,7 @@ public class JGitUtils { * Returns a list of commits for the repository within the range specified
* by startRangeId and endRangeId. If the repository does not exist or is
* empty, an empty list is returned.
- *
+ *
* @param repository
* @param startRangeId
* the first commit (not included in results)
@@ -1329,7 +1329,7 @@ public class JGitUtils { * Search results require a specified SearchType of AUTHOR, COMMITTER, or
* COMMIT. Results may be paginated using offset and maxCount. If the
* repository does not exist or is empty, an empty list is returned.
- *
+ *
* @param repository
* @param objectId
* if unspecified, HEAD is assumed.
@@ -1429,7 +1429,7 @@ public class JGitUtils { * Returns the default branch to use for a repository. Normally returns
* whatever branch HEAD points to, but if HEAD points to nothing it returns
* the most recently updated branch.
- *
+ *
* @param repository
* @return the objectid of a branch
* @throws Exception
@@ -1492,7 +1492,7 @@ public class JGitUtils { }
return target;
}
-
+
/**
* Sets the symbolic ref HEAD to the specified target ref. The
* HEAD will be detached if the target ref is not a branch.
@@ -1519,7 +1519,7 @@ public class JGitUtils { case FORCED:
case NO_CHANGE:
case FAST_FORWARD:
- return true;
+ return true;
default:
LOGGER.error(MessageFormat.format("{0} HEAD update to {1} returned result {2}",
repository.getDirectory().getAbsolutePath(), targetRef, result));
@@ -1529,7 +1529,7 @@ public class JGitUtils { }
return false;
}
-
+
/**
* Sets the local branch ref to point to the specified commit id.
*
@@ -1554,7 +1554,7 @@ public class JGitUtils { case FORCED:
case NO_CHANGE:
case FAST_FORWARD:
- return true;
+ return true;
default:
LOGGER.error(MessageFormat.format("{0} {1} update to {2} returned result {3}",
repository.getDirectory().getAbsolutePath(), branchName, commitId, result));
@@ -1564,10 +1564,10 @@ public class JGitUtils { }
return false;
}
-
+
/**
* Deletes the specified branch ref.
- *
+ *
* @param repository
* @param branch
* @return true if successful
@@ -1587,7 +1587,7 @@ public class JGitUtils { case FORCED:
case NO_CHANGE:
case FAST_FORWARD:
- return true;
+ return true;
default:
LOGGER.error(MessageFormat.format("{0} failed to delete to {1} returned result {2}",
repository.getDirectory().getAbsolutePath(), branchName, result));
@@ -1597,7 +1597,7 @@ public class JGitUtils { }
return false;
}
-
+
/**
* Get the full branch and tag ref names for any potential HEAD targets.
*
@@ -1618,17 +1618,17 @@ public class JGitUtils { /**
* Returns all refs grouped by their associated object id.
- *
+ *
* @param repository
* @return all refs grouped by their referenced object id
*/
public static Map<ObjectId, List<RefModel>> getAllRefs(Repository repository) {
return getAllRefs(repository, true);
}
-
+
/**
* Returns all refs grouped by their associated object id.
- *
+ *
* @param repository
* @param includeRemoteRefs
* @return all refs grouped by their referenced object id
@@ -1652,7 +1652,7 @@ public class JGitUtils { /**
* Returns the list of tags in the repository. If repository does not exist
* or is empty, an empty list is returned.
- *
+ *
* @param repository
* @param fullName
* if true, /refs/tags/yadayadayada is returned. If false,
@@ -1668,7 +1668,7 @@ public class JGitUtils { /**
* Returns the list of local branches in the repository. If repository does
* not exist or is empty, an empty list is returned.
- *
+ *
* @param repository
* @param fullName
* if true, /refs/heads/yadayadayada is returned. If false,
@@ -1685,7 +1685,7 @@ public class JGitUtils { /**
* Returns the list of remote branches in the repository. If repository does
* not exist or is empty, an empty list is returned.
- *
+ *
* @param repository
* @param fullName
* if true, /refs/remotes/yadayadayada is returned. If false,
@@ -1702,7 +1702,7 @@ public class JGitUtils { /**
* Returns the list of note branches. If repository does not exist or is
* empty, an empty list is returned.
- *
+ *
* @param repository
* @param fullName
* if true, /refs/notes/yadayadayada is returned. If false,
@@ -1715,11 +1715,11 @@ public class JGitUtils { int maxCount) {
return getRefs(repository, Constants.R_NOTES, fullName, maxCount);
}
-
+
/**
- * Returns the list of refs in the specified base ref. If repository does
+ * Returns the list of refs in the specified base ref. If repository does
* not exist or is empty, an empty list is returned.
- *
+ *
* @param repository
* @param fullName
* if true, /refs/yadayadayada is returned. If false,
@@ -1733,7 +1733,7 @@ public class JGitUtils { /**
* Returns a list of references in the repository matching "refs". If the
* repository is null or empty, an empty list is returned.
- *
+ *
* @param repository
* @param refs
* if unspecified, all refs are returned
@@ -1780,7 +1780,7 @@ public class JGitUtils { /**
* Returns a RefModel for the gh-pages branch in the repository. If the
* branch can not be found, null is returned.
- *
+ *
* @param repository
* @return a refmodel for the gh-pages branch or null
*/
@@ -1791,7 +1791,7 @@ public class JGitUtils { /**
* Returns a RefModel for a specific branch name in the repository. If the
* branch can not be found, null is returned.
- *
+ *
* @param repository
* @return a refmodel for the branch or null
*/
@@ -1820,10 +1820,10 @@ public class JGitUtils { }
return branch;
}
-
+
/**
* Returns the list of submodules for this repository.
- *
+ *
* @param repository
* @param commit
* @return list of submodules
@@ -1832,10 +1832,10 @@ public class JGitUtils { RevCommit commit = getCommit(repository, commitId);
return getSubmodules(repository, commit.getTree());
}
-
+
/**
* Returns the list of submodules for this repository.
- *
+ *
* @param repository
* @param commit
* @return list of submodules
@@ -1858,11 +1858,11 @@ public class JGitUtils { }
return list;
}
-
+
/**
* Returns the submodule definition for the specified path at the specified
* commit. If no module is defined for the path, null is returned.
- *
+ *
* @param repository
* @param commit
* @param path
@@ -1876,7 +1876,7 @@ public class JGitUtils { }
return null;
}
-
+
public static String getSubmoduleCommitId(Repository repository, String path, RevCommit commit) {
String commitId = null;
RevWalk rw = new RevWalk(repository);
@@ -1907,7 +1907,7 @@ public class JGitUtils { * Returns the list of notes entered about the commit from the refs/notes
* namespace. If the repository does not exist or is empty, an empty list is
* returned.
- *
+ *
* @param repository
* @param commit
* @return list of notes
@@ -1931,7 +1931,7 @@ public class JGitUtils { list.add(gitNote);
continue;
}
-
+
// folder structure
StringBuilder sb = new StringBuilder(commit.getName());
sb.insert(2, '/');
@@ -1951,7 +1951,7 @@ public class JGitUtils { /**
* this method creates an incremental revision number as a tag according to
* the amount of already existing tags, which start with a defined prefix.
- *
+ *
* @param repository
* @param objectId
* @param tagger
@@ -1985,7 +1985,7 @@ public class JGitUtils { /**
* creates a tag in a repository
- *
+ *
* @param repository
* @param objectId, the ref the tag points towards
* @param tagger, the person tagging the object
@@ -1994,7 +1994,7 @@ public class JGitUtils { * @return boolean, true if operation was successful, otherwise false
*/
public static boolean createTag(Repository repository, String objectId, PersonIdent tagger, String tag, String message) {
- try {
+ try {
Git gitClient = Git.open(repository.getDirectory());
TagCommand tagCommand = gitClient.tag();
tagCommand.setTagger(tagger);
@@ -2004,17 +2004,17 @@ public class JGitUtils { tagCommand.setObjectId(revObj);
}
tagCommand.setName(tag);
- Ref call = tagCommand.call();
+ Ref call = tagCommand.call();
return call != null ? true : false;
} catch (Exception e) {
error(e, repository, "Failed to create tag {1} in repository {0}", objectId, tag);
}
return false;
}
-
+
/**
* Create an orphaned branch in a repository.
- *
+ *
* @param repository
* @param branchName
* @param author
@@ -2082,10 +2082,10 @@ public class JGitUtils { }
return success;
}
-
+
/**
* Reads the sparkleshare id, if present, from the repository.
- *
+ *
* @param repository
* @return an id or null
*/
diff --git a/src/main/java/com/gitblit/utils/JnaUtils.java b/src/main/java/com/gitblit/utils/JnaUtils.java index 4009342a..2b807196 100644 --- a/src/main/java/com/gitblit/utils/JnaUtils.java +++ b/src/main/java/com/gitblit/utils/JnaUtils.java @@ -15,9 +15,6 @@ */ package com.gitblit.utils; -import com.sun.jna.Library; -import com.sun.jna.Native; - import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -28,6 +25,9 @@ import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.sun.jna.Library; +import com.sun.jna.Native; + /** * Collection of static methods to access native OS library functionality. * diff --git a/src/main/java/com/gitblit/utils/JsonUtils.java b/src/main/java/com/gitblit/utils/JsonUtils.java index e9241827..fdf68e52 100644 --- a/src/main/java/com/gitblit/utils/JsonUtils.java +++ b/src/main/java/com/gitblit/utils/JsonUtils.java @@ -54,9 +54,9 @@ import com.google.gson.reflect.TypeToken; /**
* Utility methods for json calls to a Gitblit server.
- *
+ *
* @author James Moger
- *
+ *
*/
public class JsonUtils {
@@ -68,7 +68,7 @@ public class JsonUtils { /**
* Creates JSON from the specified object.
- *
+ *
* @param o
* @return json
*/
@@ -79,7 +79,7 @@ public class JsonUtils { /**
* Convert a json string to an object of the specified type.
- *
+ *
* @param json
* @param clazz
* @return an object
@@ -90,7 +90,7 @@ public class JsonUtils { /**
* Convert a json string to an object of the specified type.
- *
+ *
* @param json
* @param clazz
* @return an object
@@ -101,7 +101,7 @@ public class JsonUtils { /**
* Reads a gson object from the specified url.
- *
+ *
* @param url
* @param type
* @return the deserialized object
@@ -114,7 +114,7 @@ public class JsonUtils { /**
* Reads a gson object from the specified url.
- *
+ *
* @param url
* @param type
* @return the deserialized object
@@ -127,7 +127,7 @@ public class JsonUtils { /**
* Reads a gson object from the specified url.
- *
+ *
* @param url
* @param type
* @param username
@@ -146,7 +146,7 @@ public class JsonUtils { /**
* Reads a gson object from the specified url.
- *
+ *
* @param url
* @param clazz
* @param username
@@ -165,7 +165,7 @@ public class JsonUtils { /**
* Retrieves a JSON message.
- *
+ *
* @param url
* @return the JSON message as a string
* @throws {@link IOException}
@@ -205,7 +205,7 @@ public class JsonUtils { /**
* Sends a JSON message.
- *
+ *
* @param url
* the url to write to
* @param json
@@ -219,7 +219,7 @@ public class JsonUtils { /**
* Sends a JSON message.
- *
+ *
* @param url
* the url to write to
* @param json
@@ -296,7 +296,7 @@ public class JsonUtils { JsonDeserializationContext jsonDeserializationContext) {
try {
synchronized (dateFormat) {
- Date date = dateFormat.parse(jsonElement.getAsString());
+ Date date = dateFormat.parse(jsonElement.getAsString());
return new Date((date.getTime() / 1000) * 1000);
}
} catch (ParseException e) {
@@ -304,7 +304,7 @@ public class JsonUtils { }
}
}
-
+
private static class AccessPermissionTypeAdapter implements JsonSerializer<AccessPermission>, JsonDeserializer<AccessPermission> {
private AccessPermissionTypeAdapter() {
@@ -319,7 +319,7 @@ public class JsonUtils { @Override
public synchronized AccessPermission deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) {
- return AccessPermission.fromCode(jsonElement.getAsString());
+ return AccessPermission.fromCode(jsonElement.getAsString());
}
}
@@ -334,10 +334,12 @@ public class JsonUtils { this.fieldName = fqfn.substring(fqfn.lastIndexOf(".") + 1);
}
+ @Override
public boolean shouldSkipClass(Class<?> arg0) {
return false;
}
+ @Override
public boolean shouldSkipField(FieldAttributes f) {
return (f.getDeclaringClass() == c && f.getName().equals(fieldName));
}
diff --git a/src/main/java/com/gitblit/utils/MarkdownUtils.java b/src/main/java/com/gitblit/utils/MarkdownUtils.java index 0b8c9c57..15242364 100644 --- a/src/main/java/com/gitblit/utils/MarkdownUtils.java +++ b/src/main/java/com/gitblit/utils/MarkdownUtils.java @@ -26,15 +26,15 @@ import org.tautua.markdownpapers.parser.ParseException; /**
* Utility methods for transforming raw markdown text to html.
- *
+ *
* @author James Moger
- *
+ *
*/
public class MarkdownUtils {
/**
* Returns the html version of the markdown source text.
- *
+ *
* @param markdown
* @return html version of markdown text
* @throws java.text.ParseException
@@ -55,7 +55,7 @@ public class MarkdownUtils { /**
* Returns the html version of the markdown source reader. The reader is
* closed regardless of success or failure.
- *
+ *
* @param markdownReader
* @return html version of the markdown text
* @throws java.text.ParseException
diff --git a/src/main/java/com/gitblit/utils/MetricUtils.java b/src/main/java/com/gitblit/utils/MetricUtils.java index 26e4581c..47031021 100644 --- a/src/main/java/com/gitblit/utils/MetricUtils.java +++ b/src/main/java/com/gitblit/utils/MetricUtils.java @@ -39,9 +39,9 @@ import com.gitblit.models.RefModel; /**
* Utility class for collecting metrics on a branch, tag, or other ref within
* the repository.
- *
+ *
* @author James Moger
- *
+ *
*/
public class MetricUtils {
@@ -49,7 +49,7 @@ public class MetricUtils { /**
* Log an error message and exception.
- *
+ *
* @param t
* @param repository
* if repository is not null it MUST be the {0} parameter in the
@@ -74,12 +74,12 @@ public class MetricUtils { * Returns the list of metrics for the specified commit reference, branch,
* or tag within the repository. If includeTotal is true, the total of all
* the metrics will be included as the first element in the returned list.
- *
+ *
* If the dateformat is unspecified an attempt is made to determine an
* appropriate date format by determining the time difference between the
* first commit on the branch and the most recent commit. This assumes that
* the commits are linear.
- *
+ *
* @param repository
* @param objectId
* if null or empty, HEAD is assumed.
@@ -172,7 +172,7 @@ public class MetricUtils { /**
* Returns a list of author metrics for the specified repository.
- *
+ *
* @param repository
* @param objectId
* if null or empty, HEAD is assumed.
diff --git a/src/main/java/com/gitblit/utils/ModelUtils.java b/src/main/java/com/gitblit/utils/ModelUtils.java index d053db65..6fb4c0ac 100644 --- a/src/main/java/com/gitblit/utils/ModelUtils.java +++ b/src/main/java/com/gitblit/utils/ModelUtils.java @@ -38,7 +38,7 @@ public class ModelUtils userRepoPrefix = Constants.DEFAULT_USER_REPOSITORY_PREFIX; return; } - + String newPrefix = prefix.replace('\\', '/'); if (prefix.charAt(0) == '/') { newPrefix = prefix.substring(1); diff --git a/src/main/java/com/gitblit/utils/ObjectCache.java b/src/main/java/com/gitblit/utils/ObjectCache.java index 692669f4..48a9668d 100644 --- a/src/main/java/com/gitblit/utils/ObjectCache.java +++ b/src/main/java/com/gitblit/utils/ObjectCache.java @@ -25,9 +25,9 @@ import java.util.concurrent.ConcurrentHashMap; * milliseconds and in fast, concurrent systems this cache is too simplistic.
* However, for the cases where its being used in Gitblit this cache technique
* is just fine.
- *
+ *
* @author James Moger
- *
+ *
*/
public class ObjectCache<X> implements Serializable {
@@ -91,7 +91,7 @@ public class ObjectCache<X> implements Serializable { }
return null;
}
-
+
public int size() {
return cache.size();
}
diff --git a/src/main/java/com/gitblit/utils/PatchFormatter.java b/src/main/java/com/gitblit/utils/PatchFormatter.java index 90b3fb16..c7d2cef4 100644 --- a/src/main/java/com/gitblit/utils/PatchFormatter.java +++ b/src/main/java/com/gitblit/utils/PatchFormatter.java @@ -32,9 +32,9 @@ import com.gitblit.Constants; /**
* A diff formatter that outputs standard patch content.
- *
+ *
* @author James Moger
- *
+ *
*/
public class PatchFormatter extends DiffFormatter {
@@ -49,6 +49,7 @@ public class PatchFormatter extends DiffFormatter { this.os = os;
}
+ @Override
public void format(DiffEntry entry) throws IOException {
currentTouple = new PatchTouple();
changes.put(entry.getNewPath(), currentTouple);
diff --git a/src/main/java/com/gitblit/utils/RefLogUtils.java b/src/main/java/com/gitblit/utils/RefLogUtils.java index df09a76f..af247733 100644 --- a/src/main/java/com/gitblit/utils/RefLogUtils.java +++ b/src/main/java/com/gitblit/utils/RefLogUtils.java @@ -66,19 +66,19 @@ import com.gitblit.models.UserModel; /** * Utility class for maintaining a reflog within a git repository on an * orphan branch. - * + * * @author James Moger * */ public class RefLogUtils { - + private static final String GB_REFLOG = "refs/gitblit/reflog"; private static final Logger LOGGER = LoggerFactory.getLogger(RefLogUtils.class); /** * Log an error message and exception. - * + * * @param t * @param repository * if repository is not null it MUST be the {0} parameter in the @@ -98,10 +98,10 @@ public class RefLogUtils { } LOGGER.error(MessageFormat.format(pattern, parameters.toArray()), t); } - + /** * Returns true if the repository has a reflog branch. - * + * * @param repository * @return true if the repository has a reflog branch */ @@ -117,7 +117,7 @@ public class RefLogUtils { /** * Returns a RefModel for the reflog branch in the repository. If the * branch can not be found, null is returned. - * + * * @param repository * @return a refmodel for the reflog branch or null */ @@ -152,7 +152,7 @@ public class RefLogUtils { } return null; } - + private static UserModel newUserModelFrom(PersonIdent ident) { String name = ident.getName(); String username; @@ -165,16 +165,16 @@ public class RefLogUtils { displayname = name; username = ident.getEmailAddress(); } - + UserModel user = new UserModel(username); user.displayName = displayname; user.emailAddress = ident.getEmailAddress(); return user; } - + /** * Logs a ref deletion. - * + * * @param user * @param repository * @param ref @@ -189,7 +189,7 @@ public class RefLogUtils { if (reflogBranch == null) { return false; } - + List<RevCommit> log = JGitUtils.getRevLog(repository, reflogBranch.getName(), ref.getName(), 0, 1); if (log.isEmpty()) { // this ref is not in the reflog branch @@ -202,10 +202,10 @@ public class RefLogUtils { } return false; } - + /** * Updates the reflog with the received commands. - * + * * @param user * @param repository * @param commands @@ -217,10 +217,10 @@ public class RefLogUtils { if (reflogBranch == null) { JGitUtils.createOrphanBranch(repository, GB_REFLOG, null); } - + boolean success = false; String message = "push"; - + try { ObjectId headId = repository.resolve(GB_REFLOG + "^{commit}"); ObjectInserter odi = repository.newObjectInserter(); @@ -286,17 +286,17 @@ public class RefLogUtils { } return success; } - + /** * Creates an in-memory index of the push log entry. - * + * * @param repo * @param headId * @param commands * @return an in-memory index * @throws IOException */ - private static DirCache createIndex(Repository repo, ObjectId headId, + private static DirCache createIndex(Repository repo, ObjectId headId, Collection<ReceiveCommand> commands) throws IOException { DirCache inCoreIndex = DirCache.newInCore(); @@ -335,7 +335,7 @@ public class RefLogUtils { continue; } String content = change.toString(); - + // create an index entry for this attachment final DirCacheEntry dcEntry = new DirCacheEntry(path); dcEntry.setLength(content.length()); @@ -386,7 +386,7 @@ public class RefLogUtils { } return inCoreIndex; } - + public static List<RefLogEntry> getRefLog(String repositoryName, Repository repository) { return getRefLog(repositoryName, repository, null, 0, -1); } @@ -402,11 +402,11 @@ public class RefLogUtils { public static List<RefLogEntry> getRefLog(String repositoryName, Repository repository, Date minimumDate) { return getRefLog(repositoryName, repository, minimumDate, 0, -1); } - + /** * Returns the list of reflog entries as they were recorded by Gitblit. * Each RefLogEntry may represent multiple ref updates. - * + * * @param repositoryName * @param repository * @param minimumDate @@ -425,7 +425,7 @@ public class RefLogUtils { if (maxCount == 0) { return list; } - + Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(repository); List<RevCommit> pushes; if (minimumDate == null) { @@ -441,8 +441,8 @@ public class RefLogUtils { UserModel user = newUserModelFrom(push.getAuthorIdent()); Date date = push.getAuthorIdent().getWhen(); - - RefLogEntry log = new RefLogEntry(repositoryName, date, user); + + RefLogEntry log = new RefLogEntry(repositoryName, date, user); List<PathChangeModel> changedRefs = JGitUtils.getFilesInCommit(repository, push); if (changedRefs.isEmpty()) { // skip empty commits @@ -483,7 +483,7 @@ public class RefLogUtils { /** * Returns the list of pushes separated by ref (e.g. each ref has it's own * PushLogEntry object). - * + * * @param repositoryName * @param repository * @param maxCount @@ -492,11 +492,11 @@ public class RefLogUtils { public static List<RefLogEntry> getLogByRef(String repositoryName, Repository repository, int maxCount) { return getLogByRef(repositoryName, repository, 0, maxCount); } - + /** * Returns the list of pushes separated by ref (e.g. each ref has it's own * PushLogEntry object). - * + * * @param repositoryName * @param repository * @param offset @@ -513,7 +513,7 @@ public class RefLogUtils { if (!refMap.containsKey(ref)) { refMap.put(ref, new ArrayList<RefLogEntry>()); } - + // construct new ref-specific ref change entry RefLogEntry refChange; if (entry instanceof DailyLogEntry) { @@ -528,23 +528,23 @@ public class RefLogUtils { refMap.get(ref).add(refChange); } } - + // merge individual ref changes into master list List<RefLogEntry> mergedRefLog = new ArrayList<RefLogEntry>(); for (List<RefLogEntry> refPush : refMap.values()) { mergedRefLog.addAll(refPush); } - + // sort ref log Collections.sort(mergedRefLog); - + return mergedRefLog; } - + /** * Returns the list of ref changes separated by ref (e.g. each ref has it's own * RefLogEntry object). - * + * * @param repositoryName * @param repository * @param minimumDate @@ -567,16 +567,16 @@ public class RefLogUtils { refMap.get(ref).add(refPush); } } - + // merge individual ref pushes into master list List<RefLogEntry> refPushLog = new ArrayList<RefLogEntry>(); for (List<RefLogEntry> refPush : refMap.values()) { refPushLog.addAll(refPush); } - + // sort ref push log Collections.sort(refPushLog); - + return refPushLog; } @@ -631,12 +631,12 @@ public class RefLogUtils { linearParent = commit.getParents()[0].getId().getName(); digest.updateRef(branch, ReceiveCommand.Type.UPDATE, linearParent, commit.getName()); } - + RepositoryCommit repoCommit = digest.addCommit(commit); if (repoCommit != null) { List<RefModel> matchedRefs = allRefs.get(commit.getId()); repoCommit.setRefs(matchedRefs); - + if (!ArrayUtils.isEmpty(matchedRefs)) { for (RefModel ref : matchedRefs) { if (ref.getName().startsWith(Constants.R_TAGS)) { diff --git a/src/main/java/com/gitblit/utils/RpcUtils.java b/src/main/java/com/gitblit/utils/RpcUtils.java index 290be49e..24e07dcd 100644 --- a/src/main/java/com/gitblit/utils/RpcUtils.java +++ b/src/main/java/com/gitblit/utils/RpcUtils.java @@ -39,9 +39,9 @@ import com.google.gson.reflect.TypeToken; /**
* Utility methods for rpc calls.
- *
+ *
* @author James Moger
- *
+ *
*/
public class RpcUtils {
@@ -76,7 +76,7 @@ public class RpcUtils { }.getType();
/**
- *
+ *
* @param remoteURL
* the url of the remote gitblit instance
* @param req
@@ -88,7 +88,7 @@ public class RpcUtils { }
/**
- *
+ *
* @param remoteURL
* the url of the remote gitblit instance
* @param req
@@ -110,7 +110,7 @@ public class RpcUtils { /**
* Returns the version of the RPC protocol on the server.
- *
+ *
* @param serverUrl
* @param account
* @param password
@@ -124,7 +124,7 @@ public class RpcUtils { try {
protocol = JsonUtils.retrieveJson(url, Integer.class, account, password);
} catch (UnknownRequestException e) {
- // v0.7.0 (protocol 1) did not have this request type
+ // v0.7.0 (protocol 1) did not have this request type
}
return protocol;
}
@@ -132,7 +132,7 @@ public class RpcUtils { /**
* Retrieves a map of the repositories at the remote gitblit instance keyed
* by the repository clone url.
- *
+ *
* @param serverUrl
* @param account
* @param password
@@ -149,7 +149,7 @@ public class RpcUtils { /**
* Tries to pull the gitblit user accounts from the remote gitblit instance.
- *
+ *
* @param serverUrl
* @param account
* @param password
@@ -167,7 +167,7 @@ public class RpcUtils { /**
* Tries to pull the gitblit team definitions from the remote gitblit
* instance.
- *
+ *
* @param serverUrl
* @param account
* @param password
@@ -184,7 +184,7 @@ public class RpcUtils { /**
* Create a repository on the Gitblit server.
- *
+ *
* @param repository
* @param serverUrl
* @param account
@@ -205,7 +205,7 @@ public class RpcUtils { /**
* Send a revised version of the repository model to the Gitblit server.
- *
+ *
* @param repository
* @param serverUrl
* @param account
@@ -221,7 +221,7 @@ public class RpcUtils { /**
* Delete a repository from the Gitblit server.
- *
+ *
* @param repository
* @param serverUrl
* @param account
@@ -235,17 +235,17 @@ public class RpcUtils { password);
}
-
+
/**
* Clears the repository cache on the Gitblit server.
- *
+ *
* @param serverUrl
* @param account
* @param password
* @return true if the action succeeded
* @throws IOException
*/
- public static boolean clearRepositoryCache(String serverUrl, String account,
+ public static boolean clearRepositoryCache(String serverUrl, String account,
char[] password) throws IOException {
return doAction(RpcRequest.CLEAR_REPOSITORY_CACHE, null, null, serverUrl, account,
password);
@@ -253,7 +253,7 @@ public class RpcUtils { /**
* Create a user on the Gitblit server.
- *
+ *
* @param user
* @param serverUrl
* @param account
@@ -269,7 +269,7 @@ public class RpcUtils { /**
* Send a revised version of the user model to the Gitblit server.
- *
+ *
* @param user
* @param serverUrl
* @param account
@@ -285,7 +285,7 @@ public class RpcUtils { /**
* Deletes a user from the Gitblit server.
- *
+ *
* @param user
* @param serverUrl
* @param account
@@ -297,11 +297,11 @@ public class RpcUtils { char[] password) throws IOException {
return doAction(RpcRequest.DELETE_USER, null, user, serverUrl, account, password);
}
-
+
/**
* Tries to get the specified gitblit user account from the remote gitblit instance.
* If the username is null or empty, the current user is returned.
- *
+ *
* @param username
* @param serverUrl
* @param account
@@ -318,7 +318,7 @@ public class RpcUtils { /**
* Create a team on the Gitblit server.
- *
+ *
* @param team
* @param serverUrl
* @param account
@@ -334,7 +334,7 @@ public class RpcUtils { /**
* Send a revised version of the team model to the Gitblit server.
- *
+ *
* @param team
* @param serverUrl
* @param account
@@ -350,7 +350,7 @@ public class RpcUtils { /**
* Deletes a team from the Gitblit server.
- *
+ *
* @param team
* @param serverUrl
* @param account
@@ -365,7 +365,7 @@ public class RpcUtils { /**
* Retrieves the list of users that can access the specified repository.
- *
+ *
* @param repository
* @param serverUrl
* @param account
@@ -379,10 +379,10 @@ public class RpcUtils { Collection<String> list = JsonUtils.retrieveJson(url, NAMES_TYPE, account, password);
return new ArrayList<String>(list);
}
-
+
/**
* Retrieves the list of user access permissions for the specified repository.
- *
+ *
* @param repository
* @param serverUrl
* @param account
@@ -390,7 +390,7 @@ public class RpcUtils { * @return list of User-AccessPermission tuples
* @throws IOException
*/
- public static List<RegistrantAccessPermission> getRepositoryMemberPermissions(RepositoryModel repository,
+ public static List<RegistrantAccessPermission> getRepositoryMemberPermissions(RepositoryModel repository,
String serverUrl, String account, char [] password) throws IOException {
String url = asLink(serverUrl, RpcRequest.LIST_REPOSITORY_MEMBER_PERMISSIONS, repository.name);
Collection<RegistrantAccessPermission> list = JsonUtils.retrieveJson(url, REGISTRANT_PERMISSIONS_TYPE, account, password);
@@ -399,7 +399,7 @@ public class RpcUtils { /**
* Sets the repository user access permissions
- *
+ *
* @param repository
* @param permissions
* @param serverUrl
@@ -414,10 +414,10 @@ public class RpcUtils { return doAction(RpcRequest.SET_REPOSITORY_MEMBER_PERMISSIONS, repository.name, permissions, serverUrl,
account, password);
}
-
+
/**
* Retrieves the list of teams that can access the specified repository.
- *
+ *
* @param repository
* @param serverUrl
* @param account
@@ -431,10 +431,10 @@ public class RpcUtils { Collection<String> list = JsonUtils.retrieveJson(url, NAMES_TYPE, account, password);
return new ArrayList<String>(list);
}
-
+
/**
* Retrieves the list of team access permissions for the specified repository.
- *
+ *
* @param repository
* @param serverUrl
* @param account
@@ -442,7 +442,7 @@ public class RpcUtils { * @return list of Team-AccessPermission tuples
* @throws IOException
*/
- public static List<RegistrantAccessPermission> getRepositoryTeamPermissions(RepositoryModel repository,
+ public static List<RegistrantAccessPermission> getRepositoryTeamPermissions(RepositoryModel repository,
String serverUrl, String account, char [] password) throws IOException {
String url = asLink(serverUrl, RpcRequest.LIST_REPOSITORY_TEAM_PERMISSIONS, repository.name);
Collection<RegistrantAccessPermission> list = JsonUtils.retrieveJson(url, REGISTRANT_PERMISSIONS_TYPE, account, password);
@@ -451,7 +451,7 @@ public class RpcUtils { /**
* Sets the repository team access permissions
- *
+ *
* @param repository
* @param permissions
* @param serverUrl
@@ -466,11 +466,11 @@ public class RpcUtils { return doAction(RpcRequest.SET_REPOSITORY_TEAM_PERMISSIONS, repository.name, permissions, serverUrl,
account, password);
}
-
+
/**
* Retrieves the list of federation registrations. These are the list of
* registrations that this Gitblit instance is pulling from.
- *
+ *
* @param serverUrl
* @param account
* @param password
@@ -489,7 +489,7 @@ public class RpcUtils { /**
* Retrieves the list of federation result registrations. These are the
* results reported back to this Gitblit instance from a federation client.
- *
+ *
* @param serverUrl
* @param account
* @param password
@@ -507,7 +507,7 @@ public class RpcUtils { /**
* Retrieves the list of federation proposals.
- *
+ *
* @param serverUrl
* @param account
* @param password
@@ -525,7 +525,7 @@ public class RpcUtils { /**
* Retrieves the list of federation repository sets.
- *
+ *
* @param serverUrl
* @param account
* @param password
@@ -542,7 +542,7 @@ public class RpcUtils { /**
* Retrieves the settings of the Gitblit server.
- *
+ *
* @param serverUrl
* @param account
* @param password
@@ -559,7 +559,7 @@ public class RpcUtils { /**
* Update the settings on the Gitblit server.
- *
+ *
* @param settings
* the settings to update
* @param serverUrl
@@ -576,7 +576,7 @@ public class RpcUtils { /**
* Retrieves the server status object.
- *
+ *
* @param serverUrl
* @param account
* @param password
@@ -593,7 +593,7 @@ public class RpcUtils { /**
* Retrieves a map of local branches in the Gitblit server keyed by
* repository.
- *
+ *
* @param serverUrl
* @param account
* @param password
@@ -610,7 +610,7 @@ public class RpcUtils { /**
* Retrieves a list of available branch feeds in the Gitblit server.
- *
+ *
* @param serverUrl
* @param account
* @param password
@@ -634,7 +634,7 @@ public class RpcUtils { /**
* Do the specified administrative action on the Gitblit server.
- *
+ *
* @param request
* @param name
* the name of the object (may be null)
diff --git a/src/main/java/com/gitblit/utils/StringUtils.java b/src/main/java/com/gitblit/utils/StringUtils.java index cff3577d..5e627781 100644 --- a/src/main/java/com/gitblit/utils/StringUtils.java +++ b/src/main/java/com/gitblit/utils/StringUtils.java @@ -40,9 +40,9 @@ import java.util.regex.PatternSyntaxException; /**
* Utility class of string functions.
- *
+ *
* @author James Moger
- *
+ *
*/
public class StringUtils {
@@ -52,7 +52,7 @@ public class StringUtils { /**
* Returns true if the string is null or empty.
- *
+ *
* @param value
* @return true if string is null or empty
*/
@@ -62,7 +62,7 @@ public class StringUtils { /**
* Replaces carriage returns and line feeds with html line breaks.
- *
+ *
* @param string
* @return plain text with html line breaks
*/
@@ -73,7 +73,7 @@ public class StringUtils { /**
* Prepare text for html presentation. Replace sensitive characters with
* html entities.
- *
+ *
* @param inStr
* @param changeSpace
* @return plain text escaped for html
@@ -104,7 +104,7 @@ public class StringUtils { /**
* Decode html entities back into plain text characters.
- *
+ *
* @param inStr
* @return returns plain text from html
*/
@@ -115,7 +115,7 @@ public class StringUtils { /**
* Encodes a url parameter by escaping troublesome characters.
- *
+ *
* @param inStr
* @return properly escaped url
*/
@@ -137,7 +137,7 @@ public class StringUtils { /**
* Flatten the list of strings into a single string with a space separator.
- *
+ *
* @param values
* @return flattened list
*/
@@ -148,7 +148,7 @@ public class StringUtils { /**
* Flatten the list of strings into a single string with the specified
* separator.
- *
+ *
* @param values
* @param separator
* @return flattened list
@@ -169,7 +169,7 @@ public class StringUtils { * Returns a string trimmed to a maximum length with trailing ellipses. If
* the string length is shorter than the max, the original string is
* returned.
- *
+ *
* @param value
* @param max
* @return trimmed string
@@ -184,7 +184,7 @@ public class StringUtils { /**
* Left pad a string with the specified character, if the string length is
* less than the specified length.
- *
+ *
* @param input
* @param length
* @param pad
@@ -205,7 +205,7 @@ public class StringUtils { /**
* Right pad a string with the specified character, if the string length is
* less then the specified length.
- *
+ *
* @param input
* @param length
* @param pad
@@ -225,7 +225,7 @@ public class StringUtils { /**
* Calculates the SHA1 of the string.
- *
+ *
* @param text
* @return sha1 of the string
*/
@@ -240,7 +240,7 @@ public class StringUtils { /**
* Calculates the SHA1 of the byte array.
- *
+ *
* @param bytes
* @return sha1 of the byte array
*/
@@ -257,7 +257,7 @@ public class StringUtils { /**
* Calculates the MD5 of the string.
- *
+ *
* @param string
* @return md5 of the string
*/
@@ -268,10 +268,10 @@ public class StringUtils { throw new RuntimeException(u);
}
}
-
+
/**
* Calculates the MD5 of the string.
- *
+ *
* @param string
* @return md5 of the string
*/
@@ -289,17 +289,17 @@ public class StringUtils { /**
* Returns the hex representation of the byte array.
- *
+ *
* @param bytes
* @return byte array as hex string
*/
private static String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
- if (((int) bytes[i] & 0xff) < 0x10) {
+ if ((bytes[i] & 0xff) < 0x10) {
sb.append('0');
}
- sb.append(Long.toString((int) bytes[i] & 0xff, 16));
+ sb.append(Long.toString(bytes[i] & 0xff, 16));
}
return sb.toString();
}
@@ -307,7 +307,7 @@ public class StringUtils { /**
* Returns the root path of the specified path. Returns a blank string if
* there is no root path.
- *
+ *
* @param path
* @return root path or blank
*/
@@ -321,7 +321,7 @@ public class StringUtils { /**
* Returns the path remainder after subtracting the basePath from the
* fullPath.
- *
+ *
* @param basePath
* @param fullPath
* @return the relative path
@@ -341,7 +341,7 @@ public class StringUtils { /**
* Splits the space-separated string into a list of strings.
- *
+ *
* @param value
* @return list of strings
*/
@@ -351,7 +351,7 @@ public class StringUtils { /**
* Splits the string into a list of string by the specified separator.
- *
+ *
* @param value
* @param separator
* @return list of strings
@@ -359,7 +359,7 @@ public class StringUtils { public static List<String> getStringsFromValue(String value, String separator) {
List<String> strings = new ArrayList<String>();
try {
- String[] chunks = value.split(separator + "(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
+ String[] chunks = value.split(separator + "(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for (String chunk : chunks) {
chunk = chunk.trim();
if (chunk.length() > 0) {
@@ -379,7 +379,7 @@ public class StringUtils { /**
* Validates that a name is composed of letters, digits, or limited other
* characters.
- *
+ *
* @param name
* @return the first invalid character found or null if string is acceptable
*/
@@ -402,7 +402,7 @@ public class StringUtils { /**
* Simple fuzzy string comparison. This is a case-insensitive check. A
* single wildcard * value is supported.
- *
+ *
* @param value
* @param pattern
* @return true if the value matches the pattern
@@ -431,7 +431,7 @@ public class StringUtils { /**
* Compare two repository names for proper group sorting.
- *
+ *
* @param r1
* @param r2
* @return
@@ -459,7 +459,7 @@ public class StringUtils { /**
* Sort grouped repository names.
- *
+ *
* @param list
*/
public static void sortRepositorynames(List<String> list) {
@@ -476,7 +476,7 @@ public class StringUtils { for (char c : getMD5(value.toLowerCase()).toCharArray()) {
cs += c;
}
- int n = (cs % 360);
+ int n = (cs % 360);
float hue = ((float) n) / 360;
return hsvToRgb(hue, 0.90f, 0.65f);
}
@@ -514,10 +514,10 @@ public class StringUtils { String bs = Integer.toHexString((int) (b * 256));
return "#" + rs + gs + bs;
}
-
+
/**
* Strips a trailing ".git" from the value.
- *
+ *
* @param value
* @return a stripped value or the original value if .git is not found
*/
@@ -527,10 +527,10 @@ public class StringUtils { }
return value;
}
-
+
/**
* Count the number of lines in a string.
- *
+ *
* @param value
* @return the line count
*/
@@ -540,10 +540,10 @@ public class StringUtils { }
return value.split("\n").length;
}
-
+
/**
* Returns the file extension of a path.
- *
+ *
* @param path
* @return a blank string or a file extension
*/
@@ -554,13 +554,13 @@ public class StringUtils { }
return "";
}
-
+
/**
* Replace all occurences of a substring within a string with
* another string.
- *
+ *
* From Spring StringUtils.
- *
+ *
* @param inString String to examine
* @param oldPattern String to replace
* @param newPattern String to insert
@@ -582,12 +582,12 @@ public class StringUtils { // remember to append any characters to the right of a match
return sb.toString();
}
-
+
/**
* Decodes a string by trying several charsets until one does not throw a
* coding exception. Last resort is to interpret as UTF-8 with illegal
* character substitution.
- *
+ *
* @param content
* @param charsets optional
* @return a string
@@ -620,12 +620,12 @@ public class StringUtils { }
return value;
}
-
+
/**
* Attempt to extract a repository name from a given url using regular
* expressions. If no match is made, then return whatever trails after
* the final / character.
- *
+ *
* @param regexUrls
* @return a repository path
*/
@@ -644,7 +644,7 @@ public class StringUtils { }
return url;
}
-
+
/**
* Converts a string with \nnn sequences into a UTF-8 encoded string.
* @param input
@@ -662,7 +662,7 @@ public class StringUtils { // strip leading \ character
String oct = m.group().substring(1);
bytes.write(Integer.parseInt(oct, 8));
- i = m.end();
+ i = m.end();
}
if (bytes.size() == 0) {
// no octal matches
@@ -679,11 +679,11 @@ public class StringUtils { }
return input;
}
-
+
/**
* Returns the first path element of a path string. If no path separator is
- * found in the path, an empty string is returned.
- *
+ * found in the path, an empty string is returned.
+ *
* @param path
* @return the first element in the path
*/
@@ -693,10 +693,10 @@ public class StringUtils { }
return "";
}
-
+
/**
* Returns the last path element of a path string
- *
+ *
* @param path
* @return the last element in the path
*/
@@ -706,10 +706,10 @@ public class StringUtils { }
return path;
}
-
+
/**
* Variation of String.matches() which disregards case issues.
- *
+ *
* @param regex
* @param input
* @return true if the pattern matches
@@ -719,11 +719,11 @@ public class StringUtils { Matcher m = p.matcher(input);
return m.matches();
}
-
+
/**
* Removes new line and carriage return chars from a string.
* If input value is null an empty string is returned.
- *
+ *
* @param input
* @return a sanitized or empty string
*/
diff --git a/src/main/java/com/gitblit/utils/SyndicationUtils.java b/src/main/java/com/gitblit/utils/SyndicationUtils.java index d01d4691..2ee1cf69 100644 --- a/src/main/java/com/gitblit/utils/SyndicationUtils.java +++ b/src/main/java/com/gitblit/utils/SyndicationUtils.java @@ -43,15 +43,15 @@ import com.sun.syndication.io.XmlReader; /**
* Utility class for RSS feeds.
- *
+ *
* @author James Moger
- *
+ *
*/
public class SyndicationUtils {
/**
* Outputs an RSS feed of the list of entries to the outputstream.
- *
+ *
* @param hostUrl
* @param feedLink
* @param title
@@ -118,7 +118,7 @@ public class SyndicationUtils { /**
* Reads a Gitblit RSS feed.
- *
+ *
* @param url
* the url of the Gitblit server
* @param repository
@@ -153,7 +153,7 @@ public class SyndicationUtils { /**
* Reads a Gitblit RSS search feed.
- *
+ *
* @param url
* the url of the Gitblit server
* @param repository
@@ -195,7 +195,7 @@ public class SyndicationUtils { /**
* Reads a Gitblit RSS feed.
- *
+ *
* @param url
* the url of the Gitblit server
* @param parameters
diff --git a/src/main/java/com/gitblit/utils/TimeUtils.java b/src/main/java/com/gitblit/utils/TimeUtils.java index 9b5927c0..4b113be2 100644 --- a/src/main/java/com/gitblit/utils/TimeUtils.java +++ b/src/main/java/com/gitblit/utils/TimeUtils.java @@ -24,9 +24,9 @@ import java.util.TimeZone; /**
* Utility class of time functions.
- *
+ *
* @author James Moger
- *
+ *
*/
public class TimeUtils {
public static final long MIN = 1000 * 60L;
@@ -38,15 +38,15 @@ public class TimeUtils { public static final long ONEDAY = ONEHOUR * 24L;
public static final long ONEYEAR = ONEDAY * 365L;
-
+
private final ResourceBundle translation;
-
+
private final TimeZone timezone;
-
+
public TimeUtils() {
this(null, null);
}
-
+
public TimeUtils(ResourceBundle translation, TimeZone timezone) {
this.translation = translation;
this.timezone = timezone;
@@ -54,7 +54,7 @@ public class TimeUtils { /**
* Returns true if date is today.
- *
+ *
* @param date
* @return true if date is today
*/
@@ -69,7 +69,7 @@ public class TimeUtils { /**
* Returns true if date is yesterday.
- *
+ *
* @param date
* @return true if date is yesterday
*/
@@ -87,7 +87,7 @@ public class TimeUtils { /**
* Returns the string representation of the duration as days, months and/or
* years.
- *
+ *
* @param days
* @return duration as string in days, months, and/or years
*/
@@ -123,7 +123,7 @@ public class TimeUtils { /**
* Returns the number of minutes ago between the start time and the end
* time.
- *
+ *
* @param date
* @param endTime
* @param roundup
@@ -140,7 +140,7 @@ public class TimeUtils { /**
* Return the difference in minutes between now and the date.
- *
+ *
* @param date
* @param roundup
* @return minutes ago
@@ -151,7 +151,7 @@ public class TimeUtils { /**
* Return the difference in hours between now and the date.
- *
+ *
* @param date
* @param roundup
* @return hours ago
@@ -167,7 +167,7 @@ public class TimeUtils { /**
* Return the difference in days between now and the date.
- *
+ *
* @param date
* @return days ago
*/
@@ -190,7 +190,7 @@ public class TimeUtils { /**
* Returns the string representation of the duration between now and the
* date.
- *
+ *
* @param date
* @return duration as a string
*/
@@ -200,7 +200,7 @@ public class TimeUtils { /**
* Returns the CSS class for the date based on its age from Now.
- *
+ *
* @param date
* @return the css class
*/
@@ -211,7 +211,7 @@ public class TimeUtils { /**
* Returns the string representation of the duration OR the css class for
* the duration.
- *
+ *
* @param date
* @param css
* @return the string representation of the duration OR the css class
@@ -279,7 +279,7 @@ public class TimeUtils { }
}
}
-
+
public String inFuture(Date date) {
long diff = date.getTime() - System.currentTimeMillis();
if (diff > ONEDAY) {
@@ -295,7 +295,7 @@ public class TimeUtils { }
}
}
-
+
private String translate(String key, String defaultValue) {
String value = defaultValue;
if (translation != null && translation.containsKey(key)) {
@@ -306,7 +306,7 @@ public class TimeUtils { }
return value;
}
-
+
private String translate(int val, String key, String defaultPattern) {
String pattern = defaultPattern;
if (translation != null && translation.containsKey(key)) {
@@ -320,7 +320,7 @@ public class TimeUtils { /**
* Convert a frequency string into minutes.
- *
+ *
* @param frequency
* @return minutes
*/
diff --git a/src/main/java/com/gitblit/utils/X509Utils.java b/src/main/java/com/gitblit/utils/X509Utils.java index 237c8dad..d3d5b46f 100644 --- a/src/main/java/com/gitblit/utils/X509Utils.java +++ b/src/main/java/com/gitblit/utils/X509Utils.java @@ -89,43 +89,43 @@ import com.gitblit.Constants; /**
* Utility class to generate X509 certificates, keystores, and truststores.
- *
+ *
* @author James Moger
- *
+ *
*/
public class X509Utils {
-
+
public static final String SERVER_KEY_STORE = "serverKeyStore.jks";
-
+
public static final String SERVER_TRUST_STORE = "serverTrustStore.jks";
public static final String CERTS = "certs";
-
+
public static final String CA_KEY_STORE = "certs/caKeyStore.p12";
public static final String CA_REVOCATION_LIST = "certs/caRevocationList.crl";
-
+
public static final String CA_CONFIG = "certs/authority.conf";
public static final String CA_CN = "Gitblit Certificate Authority";
-
+
public static final String CA_ALIAS = CA_CN;
private static final String BC = org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME;
-
+
private static final int KEY_LENGTH = 2048;
-
+
private static final String KEY_ALGORITHM = "RSA";
-
+
private static final String SIGNING_ALGORITHM = "SHA512withRSA";
-
+
public static final boolean unlimitedStrength;
-
+
private static final Logger logger = LoggerFactory.getLogger(X509Utils.class);
-
+
static {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
-
+
// check for JCE Unlimited Strength
int maxKeyLen = 0;
try {
@@ -140,28 +140,28 @@ public class X509Utils { logger.info("Using JCE Standard Encryption Policy files, encryption key lengths will be limited");
}
}
-
+
public static enum RevocationReason {
// https://en.wikipedia.org/wiki/Revocation_list
unspecified, keyCompromise, caCompromise, affiliationChanged, superseded,
cessationOfOperation, certificateHold, unused, removeFromCRL, privilegeWithdrawn,
ACompromise;
-
+
public static RevocationReason [] reasons = {
- unspecified, keyCompromise, caCompromise,
- affiliationChanged, superseded, cessationOfOperation,
+ unspecified, keyCompromise, caCompromise,
+ affiliationChanged, superseded, cessationOfOperation,
privilegeWithdrawn };
-
+
@Override
public String toString() {
return name() + " (" + ordinal() + ")";
}
}
-
+
public interface X509Log {
void log(String message);
}
-
+
public static class X509Metadata {
// map for distinguished name OIDs
@@ -169,10 +169,10 @@ public class X509Utils { // CN in distingiushed name
public final String commonName;
-
+
// password for store
public final String password;
-
+
// password hint for README in bundle
public String passwordHint;
@@ -181,13 +181,13 @@ public class X509Utils { // start date of generated certificate
public Date notBefore;
-
+
// expiraiton date of generated certificate
public Date notAfter;
-
+
// hostname of server for which certificate is generated
public String serverHostname;
-
+
// displayname of user for README in bundle
public String userDisplayname;
@@ -213,7 +213,7 @@ public class X509Utils { notAfter = c.getTime();
oids = new HashMap<String, String>();
}
-
+
public X509Metadata clone(String commonName, String password) {
X509Metadata clone = new X509Metadata(commonName, password);
clone.emailAddress = emailAddress;
@@ -225,14 +225,14 @@ public class X509Utils { clone.userDisplayname = userDisplayname;
return clone;
}
-
+
public String getOID(String oid, String defaultValue) {
if (oids.containsKey(oid)) {
return oids.get(oid);
}
return defaultValue;
}
-
+
public void setOID(String oid, String value) {
if (StringUtils.isEmpty(value)) {
oids.remove(oid);
@@ -241,10 +241,10 @@ public class X509Utils { }
}
}
-
+
/**
* Prepare all the certificates and stores necessary for a Gitblit GO server.
- *
+ *
* @param metadata
* @param folder
* @param x509log
@@ -252,9 +252,9 @@ public class X509Utils { public static void prepareX509Infrastructure(X509Metadata metadata, File folder, X509Log x509log) {
// make the specified folder, if necessary
folder.mkdirs();
-
+
// Gitblit CA certificate
- File caKeyStore = new File(folder, CA_KEY_STORE);
+ File caKeyStore = new File(folder, CA_KEY_STORE);
if (!caKeyStore.exists()) {
logger.info(MessageFormat.format("Generating {0} ({1})", CA_CN, caKeyStore.getAbsolutePath()));
X509Certificate caCert = newCertificateAuthority(metadata, caKeyStore, x509log);
@@ -262,7 +262,7 @@ public class X509Utils { }
// Gitblit CRL
- File caRevocationList = new File(folder, CA_REVOCATION_LIST);
+ File caRevocationList = new File(folder, CA_REVOCATION_LIST);
if (!caRevocationList.exists()) {
logger.info(MessageFormat.format("Generating {0} CRL ({1})", CA_CN, caRevocationList.getAbsolutePath()));
newCertificateRevocationList(caRevocationList, caKeyStore, metadata.password);
@@ -273,7 +273,7 @@ public class X509Utils { File oldKeyStore = new File(folder, "keystore");
if (oldKeyStore.exists()) {
oldKeyStore.renameTo(new File(folder, SERVER_KEY_STORE));
- logger.info(MessageFormat.format("Renaming {0} to {1}", oldKeyStore.getName(), SERVER_KEY_STORE));
+ logger.info(MessageFormat.format("Renaming {0} to {1}", oldKeyStore.getName(), SERVER_KEY_STORE));
}
// create web SSL certificate signed by CA
@@ -282,7 +282,7 @@ public class X509Utils { logger.info(MessageFormat.format("Generating SSL certificate for {0} signed by {1} ({2})", metadata.commonName, CA_CN, serverKeyStore.getAbsolutePath()));
PrivateKey caPrivateKey = getPrivateKey(CA_ALIAS, caKeyStore, metadata.password);
X509Certificate caCert = getCertificate(CA_ALIAS, caKeyStore, metadata.password);
- newSSLCertificate(metadata, caPrivateKey, caCert, serverKeyStore, x509log);
+ newSSLCertificate(metadata, caPrivateKey, caCert, serverKeyStore, x509log);
}
// server certificate trust store holds trusted public certificates
@@ -293,11 +293,11 @@ public class X509Utils { addTrustedCertificate(CA_ALIAS, caCert, serverTrustStore, metadata.password);
}
}
-
+
/**
* Open a keystore. Store type is determined by file extension of name. If
* undetermined, JKS is assumed. The keystore does not need to exist.
- *
+ *
* @param storeFile
* @param storePassword
* @return a KeyStore
@@ -336,10 +336,10 @@ public class X509Utils { throw new RuntimeException("Could not open keystore " + storeFile, e);
}
}
-
+
/**
* Saves the keystore to the specified file.
- *
+ *
* @param targetStoreFile
* @param store
* @param password
@@ -376,17 +376,17 @@ public class X509Utils { } catch (IOException e) {
}
}
-
+
if (tmpFile.exists()) {
tmpFile.delete();
}
}
- }
+ }
/**
* Retrieves the X509 certificate with the specified alias from the certificate
* store.
- *
+ *
* @param alias
* @param storeFile
* @param storePassword
@@ -401,11 +401,11 @@ public class X509Utils { throw new RuntimeException(e);
}
}
-
+
/**
* Retrieves the private key for the specified alias from the certificate
* store.
- *
+ *
* @param alias
* @param storeFile
* @param storePassword
@@ -425,7 +425,7 @@ public class X509Utils { * Saves the certificate to the file system. If the destination filename
* ends with the pem extension, the certificate is written in the PEM format,
* otherwise the certificate is written in the DER format.
- *
+ *
* @param cert
* @param targetFile
*/
@@ -443,7 +443,7 @@ public class X509Utils { try {
pemWriter = new PEMWriter(new FileWriter(tmpFile));
pemWriter.writeObject(cert);
- pemWriter.flush();
+ pemWriter.flush();
} finally {
if (pemWriter != null) {
pemWriter.close();
@@ -462,9 +462,9 @@ public class X509Utils { }
}
}
-
+
// rename tmp file to target
- if (targetFile.exists()) {
+ if (targetFile.exists()) {
targetFile.delete();
}
tmpFile.renameTo(targetFile);
@@ -475,10 +475,10 @@ public class X509Utils { throw new RuntimeException("Failed to save certificate " + cert.getSubjectX500Principal().getName(), e);
}
}
-
+
/**
* Generate a new keypair.
- *
+ *
* @return a keypair
* @throws Exception
*/
@@ -487,10 +487,10 @@ public class X509Utils { kpGen.initialize(KEY_LENGTH, new SecureRandom());
return kpGen.generateKeyPair();
}
-
+
/**
* Builds a distinguished name from the X509Metadata.
- *
+ *
* @return a DN
*/
private static X500Name buildDistinguishedName(X509Metadata metadata) {
@@ -501,14 +501,14 @@ public class X509Utils { setOID(dnBuilder, metadata, "O", Constants.NAME);
setOID(dnBuilder, metadata, "OU", Constants.NAME);
setOID(dnBuilder, metadata, "E", metadata.emailAddress);
- setOID(dnBuilder, metadata, "CN", metadata.commonName);
+ setOID(dnBuilder, metadata, "CN", metadata.commonName);
X500Name dn = dnBuilder.build();
return dn;
}
-
+
private static void setOID(X500NameBuilder dnBuilder, X509Metadata metadata,
String oid, String defaultValue) {
-
+
String value = null;
if (metadata.oids != null && metadata.oids.containsKey(oid)) {
value = metadata.oids.get(oid);
@@ -516,7 +516,7 @@ public class X509Utils { if (StringUtils.isEmpty(value)) {
value = defaultValue;
}
-
+
if (!StringUtils.isEmpty(value)) {
try {
Field field = BCStyle.class.getField(oid);
@@ -531,7 +531,7 @@ public class X509Utils { /**
* Creates a new SSL certificate signed by the CA private key and stored in
* keyStore.
- *
+ *
* @param sslMetadata
* @param caPrivateKey
* @param caCert
@@ -544,15 +544,15 @@ public class X509Utils { X500Name webDN = buildDistinguishedName(sslMetadata);
X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
-
+
X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
issuerDN,
- BigInteger.valueOf(System.currentTimeMillis()),
+ BigInteger.valueOf(System.currentTimeMillis()),
sslMetadata.notBefore,
sslMetadata.notAfter,
webDN,
pair.getPublic());
-
+
JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
@@ -561,7 +561,7 @@ public class X509Utils { // support alternateSubjectNames for SSL certificates
List<GeneralName> altNames = new ArrayList<GeneralName>();
if (HttpUtils.isIpAddress(sslMetadata.commonName)) {
- altNames.add(new GeneralName(GeneralName.iPAddress, sslMetadata.commonName));
+ altNames.add(new GeneralName(GeneralName.iPAddress, sslMetadata.commonName));
}
if (altNames.size() > 0) {
GeneralNames subjectAltName = new GeneralNames(altNames.toArray(new GeneralName [altNames.size()]));
@@ -572,7 +572,7 @@ public class X509Utils { .setProvider(BC).build(caPrivateKey);
X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC)
.getCertificate(certBuilder.build(caSigner));
-
+
cert.checkValidity(new Date());
cert.verify(caCert.getPublicKey());
@@ -581,9 +581,9 @@ public class X509Utils { serverStore.setKeyEntry(sslMetadata.commonName, pair.getPrivate(), sslMetadata.password.toCharArray(),
new Certificate[] { cert, caCert });
saveKeyStore(targetStoreFile, serverStore, sslMetadata.password);
-
+
x509log.log(MessageFormat.format("New SSL certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getSubjectDN().getName()));
-
+
// update serial number in metadata object
sslMetadata.serialNumber = cert.getSerialNumber().toString();
@@ -596,7 +596,7 @@ public class X509Utils { /**
* Creates a new certificate authority PKCS#12 store. This function will
* destroy any existing CA store.
- *
+ *
* @param metadata
* @param storeFile
* @param keystorePassword
@@ -606,13 +606,13 @@ public class X509Utils { public static X509Certificate newCertificateAuthority(X509Metadata metadata, File storeFile, X509Log x509log) {
try {
KeyPair caPair = newKeyPair();
-
+
ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPair.getPrivate());
-
+
// clone metadata
X509Metadata caMetadata = metadata.clone(CA_CN, metadata.password);
X500Name issuerDN = buildDistinguishedName(caMetadata);
-
+
// Generate self-signed certificate
X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(
issuerDN,
@@ -621,16 +621,16 @@ public class X509Utils { caMetadata.notAfter,
issuerDN,
caPair.getPublic());
-
+
JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
caBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(caPair.getPublic()));
caBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caPair.getPublic()));
caBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(true));
caBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
-
+
JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC);
X509Certificate cert = converter.getCertificate(caBuilder.build(caSigner));
-
+
// confirm the validity of the CA certificate
cert.checkValidity(new Date());
cert.verify(cert.getPublicKey());
@@ -639,13 +639,13 @@ public class X509Utils { if (storeFile.exists()) {
storeFile.delete();
}
-
+
// Save private key and certificate to new keystore
KeyStore store = openKeyStore(storeFile, caMetadata.password);
store.setKeyEntry(CA_ALIAS, caPair.getPrivate(), caMetadata.password.toCharArray(),
new Certificate[] { cert });
saveKeyStore(storeFile, store, caMetadata.password);
-
+
x509log.log(MessageFormat.format("New CA certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getIssuerDN().getName()));
// update serial number in metadata object
@@ -656,11 +656,11 @@ public class X509Utils { throw new RuntimeException("Failed to generate Gitblit CA certificate!", t);
}
}
-
+
/**
* Creates a new certificate revocation list (CRL). This function will
* destroy any existing CRL file.
- *
+ *
* @param caRevocationList
* @param storeFile
* @param keystorePassword
@@ -675,7 +675,7 @@ public class X509Utils { X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuerDN, new Date());
-
+
// build and sign CRL with CA private key
ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
X509CRLHolder crl = crlBuilder.build(signer);
@@ -703,10 +703,10 @@ public class X509Utils { throw new RuntimeException("Failed to create new certificate revocation list " + caRevocationList, e);
}
}
-
+
/**
* Imports a certificate into the trust store.
- *
+ *
* @param alias
* @param cert
* @param storeFile
@@ -716,33 +716,33 @@ public class X509Utils { try {
KeyStore store = openKeyStore(storeFile, storePassword);
store.setCertificateEntry(alias, cert);
- saveKeyStore(storeFile, store, storePassword);
+ saveKeyStore(storeFile, store, storePassword);
} catch (Exception e) {
throw new RuntimeException("Failed to import certificate into trust store " + storeFile, e);
}
}
-
+
/**
* Creates a new client certificate PKCS#12 and PEM store. Any existing
* stores are destroyed. After generation, the certificates are bundled
* into a zip file with a personalized README file.
- *
- * The zip file reference is returned.
- *
+ *
+ * The zip file reference is returned.
+ *
* @param clientMetadata a container for dynamic parameters needed for generation
* @param caKeystoreFile
* @param caKeystorePassword
* @param x509log
* @return a zip file containing the P12, PEM, and personalized README
*/
- public static File newClientBundle(X509Metadata clientMetadata, File caKeystoreFile,
+ public static File newClientBundle(X509Metadata clientMetadata, File caKeystoreFile,
String caKeystorePassword, X509Log x509log) {
try {
// read the Gitblit CA key and certificate
KeyStore store = openKeyStore(caKeystoreFile, caKeystorePassword);
PrivateKey caPrivateKey = (PrivateKey) store.getKey(CA_ALIAS, caKeystorePassword.toCharArray());
X509Certificate caCert = (X509Certificate) store.getCertificate(CA_ALIAS);
-
+
// generate the P12 and PEM files
File targetFolder = new File(caKeystoreFile.getParentFile(), clientMetadata.commonName);
X509Certificate cert = newClientCertificate(clientMetadata, caPrivateKey, caCert, targetFolder);
@@ -750,7 +750,7 @@ public class X509Utils { // process template message
String readme = processTemplate(new File(caKeystoreFile.getParentFile(), "instructions.tmpl"), clientMetadata);
-
+
// Create a zip bundle with the p12, pem, and a personalized readme
File zipFile = new File(targetFolder, clientMetadata.commonName + ".zip");
if (zipFile.exists()) {
@@ -764,24 +764,24 @@ public class X509Utils { zos.putNextEntry(new ZipEntry(p12File.getName()));
zos.write(FileUtils.readContent(p12File));
zos.closeEntry();
- }
+ }
File pemFile = new File(targetFolder, clientMetadata.commonName + ".pem");
if (pemFile.exists()) {
zos.putNextEntry(new ZipEntry(pemFile.getName()));
zos.write(FileUtils.readContent(pemFile));
zos.closeEntry();
}
-
+
// include user's public certificate
zos.putNextEntry(new ZipEntry(clientMetadata.commonName + ".cer"));
zos.write(cert.getEncoded());
zos.closeEntry();
-
+
// include CA public certificate
zos.putNextEntry(new ZipEntry("ca.cer"));
zos.write(caCert.getEncoded());
zos.closeEntry();
-
+
if (readme != null) {
zos.putNextEntry(new ZipEntry("README.TXT"));
zos.write(readme.getBytes("UTF-8"));
@@ -793,17 +793,17 @@ public class X509Utils { zos.close();
}
}
-
+
return zipFile;
} catch (Throwable t) {
throw new RuntimeException("Failed to generate client bundle!", t);
}
}
-
+
/**
* Creates a new client certificate PKCS#12 and PEM store. Any existing
* stores are destroyed.
- *
+ *
* @param clientMetadata a container for dynamic parameters needed for generation
* @param caKeystoreFile
* @param caKeystorePassword
@@ -814,10 +814,10 @@ public class X509Utils { PrivateKey caPrivateKey, X509Certificate caCert, File targetFolder) {
try {
KeyPair pair = newKeyPair();
-
- X500Name userDN = buildDistinguishedName(clientMetadata);
+
+ X500Name userDN = buildDistinguishedName(clientMetadata);
X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
-
+
// create a new certificate signed by the Gitblit CA certificate
X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
issuerDN,
@@ -826,7 +826,7 @@ public class X509Utils { clientMetadata.notAfter,
userDN,
pair.getPublic());
-
+
JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
@@ -844,7 +844,7 @@ public class X509Utils { PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)pair.getPrivate();
bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
extUtils.createSubjectKeyIdentifier(pair.getPublic()));
-
+
// confirm the validity of the user certificate
userCert.checkValidity();
userCert.verify(caCert.getPublicKey());
@@ -854,7 +854,7 @@ public class X509Utils { verifyChain(userCert, caCert);
targetFolder.mkdirs();
-
+
// save certificate, stamped with unique name
String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
String id = date;
@@ -865,7 +865,7 @@ public class X509Utils { certFile = new File(targetFolder, id + ".cer");
count++;
}
-
+
// save user private key, user certificate and CA certificate to a PKCS#12 store
File p12File = new File(targetFolder, clientMetadata.commonName + ".p12");
if (p12File.exists()) {
@@ -873,9 +873,9 @@ public class X509Utils { }
KeyStore userStore = openKeyStore(p12File, clientMetadata.password);
userStore.setKeyEntry(MessageFormat.format("Gitblit ({0}) {1} {2}", clientMetadata.serverHostname, clientMetadata.userDisplayname, id), pair.getPrivate(), null, new Certificate [] { userCert });
- userStore.setCertificateEntry(MessageFormat.format("Gitblit ({0}) Certificate Authority", clientMetadata.serverHostname), caCert);
+ userStore.setCertificateEntry(MessageFormat.format("Gitblit ({0}) Certificate Authority", clientMetadata.serverHostname), caCert);
saveKeyStore(p12File, userStore, clientMetadata.password);
-
+
// save user private key, user certificate, and CA certificate to a PEM store
File pemFile = new File(targetFolder, clientMetadata.commonName + ".pem");
if (pemFile.exists()) {
@@ -887,22 +887,22 @@ public class X509Utils { pemWriter.writeObject(caCert);
pemWriter.flush();
pemWriter.close();
-
+
// save certificate after successfully creating the key stores
saveCertificate(userCert, certFile);
-
+
// update serial number in metadata object
clientMetadata.serialNumber = userCert.getSerialNumber().toString();
-
+
return userCert;
} catch (Throwable t) {
throw new RuntimeException("Failed to generate client certificate!", t);
}
}
-
+
/**
* Verifies a certificate's chain to ensure that it will function properly.
- *
+ *
* @param testCert
* @param additionalCerts
* @return
@@ -913,19 +913,19 @@ public class X509Utils { if (isSelfSigned(testCert)) {
throw new RuntimeException("The certificate is self-signed. Nothing to verify.");
}
-
+
// Prepare a set of all certificates
// chain builder must have all certs, including cert to validate
// http://stackoverflow.com/a/10788392
Set<X509Certificate> certs = new HashSet<X509Certificate>();
certs.add(testCert);
certs.addAll(Arrays.asList(additionalCerts));
-
+
// Attempt to build the certification chain and verify it
// Create the selector that specifies the starting certificate
- X509CertSelector selector = new X509CertSelector();
+ X509CertSelector selector = new X509CertSelector();
selector.setCertificate(testCert);
-
+
// Create the trust anchors (set of root CA certificates)
Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
for (X509Certificate cert : additionalCerts) {
@@ -933,16 +933,16 @@ public class X509Utils { trustAnchors.add(new TrustAnchor(cert, null));
}
}
-
+
// Configure the PKIX certificate builder
PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);
pkixParams.setRevocationEnabled(false);
pkixParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs), BC));
-
+
// Build and verify the certification chain
CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BC);
PKIXCertPathBuilderResult verifiedCertChain = (PKIXCertPathBuilderResult) builder.build(pkixParams);
-
+
// The chain is built and verified
return verifiedCertChain;
} catch (CertPathBuilderException e) {
@@ -951,10 +951,10 @@ public class X509Utils { throw new RuntimeException("Error verifying the certificate: " + testCert.getSubjectX500Principal(), e);
}
}
-
+
/**
* Checks whether given X.509 certificate is self-signed.
- *
+ *
* @param cert
* @return true if the certificate is self-signed
*/
@@ -970,7 +970,7 @@ public class X509Utils { throw new RuntimeException(e);
}
}
-
+
public static String processTemplate(File template, X509Metadata metadata) {
String content = null;
if (template.exists()) {
@@ -993,10 +993,10 @@ public class X509Utils { }
return content;
}
-
+
/**
* Revoke a certificate.
- *
+ *
* @param cert
* @param reason
* @param caRevocationList
@@ -1019,10 +1019,10 @@ public class X509Utils { }
return false;
}
-
+
/**
* Revoke a certificate.
- *
+ *
* @param cert
* @param reason
* @param caRevocationList
@@ -1036,16 +1036,16 @@ public class X509Utils { X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(cert).getName());
X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuerDN, new Date());
if (caRevocationList.exists()) {
- byte [] data = FileUtils.readContent(caRevocationList);
+ byte [] data = FileUtils.readContent(caRevocationList);
X509CRLHolder crl = new X509CRLHolder(data);
crlBuilder.addCRL(crl);
}
crlBuilder.addCRLEntry(cert.getSerialNumber(), new Date(), reason.ordinal());
-
+
// build and sign CRL with CA private key
ContentSigner signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider(BC).build(caPrivateKey);
X509CRLHolder crl = crlBuilder.build(signer);
-
+
File tmpFile = new File(caRevocationList.getParentFile(), Long.toHexString(System.currentTimeMillis()) + ".tmp");
FileOutputStream fos = null;
try {
@@ -1057,7 +1057,7 @@ public class X509Utils { caRevocationList.delete();
}
tmpFile.renameTo(caRevocationList);
-
+
} finally {
if (fos != null) {
fos.close();
@@ -1066,7 +1066,7 @@ public class X509Utils { tmpFile.delete();
}
}
-
+
x509log.log(MessageFormat.format("Revoked certificate {0,number,0} reason: {1} [{2}]",
cert.getSerialNumber(), reason.toString(), cert.getSubjectDN().getName()));
return true;
@@ -1076,10 +1076,10 @@ public class X509Utils { }
return false;
}
-
+
/**
* Returns true if the certificate has been revoked.
- *
+ *
* @param cert
* @param caRevocationList
* @return true if the certificate is revoked
@@ -1107,7 +1107,7 @@ public class X509Utils { }
return false;
}
-
+
public static X509Metadata getMetadata(X509Certificate cert) {
// manually split DN into OID components
// this is instead of parsing with LdapName which:
@@ -1121,7 +1121,7 @@ public class X509Utils { String data = val[1].trim();
oids.put(oid, data);
}
-
+
X509Metadata metadata = new X509Metadata(oids.get("CN"), "whocares");
metadata.oids.putAll(oids);
metadata.serialNumber = cert.getSerialNumber().toString();
|