Example usage for org.eclipse.jgit.lib Constants CHARACTER_ENCODING

List of usage examples for org.eclipse.jgit.lib Constants CHARACTER_ENCODING

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Constants CHARACTER_ENCODING.

Prototype

String CHARACTER_ENCODING

To view the source code for org.eclipse.jgit.lib Constants CHARACTER_ENCODING.

Click Source Link

Document

Native character encoding for commit messages, file names...

Usage

From source file:com.gitblit.build.BuildGhPages.java

License:Apache License

public static void main(String[] args) {
    Params params = new Params();
    JCommander jc = new JCommander(params);
    try {/*  w  ww . j  av a 2 s. c o m*/
        jc.parse(args);
    } catch (ParameterException t) {
        System.err.println(t.getMessage());
        jc.usage();
    }

    File source = new File(params.sourceFolder);
    String ghpages = "refs/heads/gh-pages";
    try {
        File gitDir = FileKey.resolve(new File(params.repositoryFolder), FS.DETECTED);
        Repository repository = new FileRepository(gitDir);

        RefModel issuesBranch = JGitUtils.getPagesBranch(repository);
        if (issuesBranch == null) {
            JGitUtils.createOrphanBranch(repository, "gh-pages", null);
        }

        System.out.println("Updating gh-pages branch...");
        ObjectId headId = repository.resolve(ghpages + "^{commit}");
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create the in-memory index of the new/updated issue.
            DirCache index = createIndex(repository, headId, source, params.obliterate);
            ObjectId indexTreeId = index.writeTree(odi);

            // Create a commit object
            PersonIdent author = new PersonIdent("Gitblit", "gitblit@localhost");
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(author);
            commit.setCommitter(author);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage("updated pages");
            commit.setParentId(headId);
            commit.setTreeId(indexTreeId);

            // Insert the commit into the repository
            ObjectId commitId = odi.insert(commit);
            odi.flush();

            RevWalk revWalk = new RevWalk(repository);
            try {
                RevCommit revCommit = revWalk.parseCommit(commitId);
                RefUpdate ru = repository.updateRef(ghpages);
                ru.setNewObjectId(commitId);
                ru.setExpectedOldObjectId(headId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result rc = ru.forceUpdate();
                switch (rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    break;
                case REJECTED:
                case LOCK_FAILURE:
                    throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
                default:
                    throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            ghpages, commitId.toString(), rc));
                }
            } finally {
                revWalk.release();
            }
        } finally {
            odi.release();
        }
        System.out.println("gh-pages updated.");
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:com.gitblit.utils.IssueUtils.java

License:Apache License

/**
 * Deletes an issue from the repository.
 * /*from   w ww .j  ava  2s  .  c o  m*/
 * @param repository
 * @param issueId
 * @return true if successful
 */
public static boolean deleteIssue(Repository repository, String issueId, String author) {
    boolean success = false;
    RefModel issuesBranch = getIssuesBranch(repository);

    if (issuesBranch == null) {
        throw new RuntimeException("gb-issues branch does not exist!");
    }

    if (StringUtils.isEmpty(issueId)) {
        throw new RuntimeException("must specify an issue id!");
    }

    String issuePath = getIssuePath(issueId);

    String message = "- " + issueId;
    try {
        ObjectId headId = repository.resolve(GB_ISSUES + "^{commit}");
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create the in-memory index of the new/updated issue
            DirCache index = DirCache.newInCore();
            DirCacheBuilder dcBuilder = index.builder();
            // Traverse HEAD to add all other paths
            TreeWalk treeWalk = new TreeWalk(repository);
            int hIdx = -1;
            if (headId != null)
                hIdx = treeWalk.addTree(new RevWalk(repository).parseTree(headId));
            treeWalk.setRecursive(true);
            while (treeWalk.next()) {
                String path = treeWalk.getPathString();
                CanonicalTreeParser hTree = null;
                if (hIdx != -1)
                    hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
                if (!path.startsWith(issuePath)) {
                    // add entries from HEAD for all other paths
                    if (hTree != null) {
                        // create a new DirCacheEntry with data retrieved
                        // from HEAD
                        final DirCacheEntry dcEntry = new DirCacheEntry(path);
                        dcEntry.setObjectId(hTree.getEntryObjectId());
                        dcEntry.setFileMode(hTree.getEntryFileMode());

                        // add to temporary in-core index
                        dcBuilder.add(dcEntry);
                    }
                }
            }

            // release the treewalk
            treeWalk.release();

            // finish temporary in-core index used for this commit
            dcBuilder.finish();

            ObjectId indexTreeId = index.writeTree(odi);

            // Create a commit object
            PersonIdent ident = new PersonIdent(author, "gitblit@localhost");
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(ident);
            commit.setCommitter(ident);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage(message);
            commit.setParentId(headId);
            commit.setTreeId(indexTreeId);

            // Insert the commit into the repository
            ObjectId commitId = odi.insert(commit);
            odi.flush();

            RevWalk revWalk = new RevWalk(repository);
            try {
                RevCommit revCommit = revWalk.parseCommit(commitId);
                RefUpdate ru = repository.updateRef(GB_ISSUES);
                ru.setNewObjectId(commitId);
                ru.setExpectedOldObjectId(headId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result rc = ru.forceUpdate();
                switch (rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    success = true;
                    break;
                case REJECTED:
                case LOCK_FAILURE:
                    throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
                default:
                    throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            GB_ISSUES, commitId.toString(), rc));
                }
            } finally {
                revWalk.release();
            }
        } finally {
            odi.release();
        }
    } catch (Throwable t) {
        error(t, repository, "Failed to delete issue {1} to {0}", issueId);
    }
    return success;
}

From source file:com.gitblit.utils.IssueUtils.java

License:Apache License

/**
 * Commit a change to the repository. Each issue is composed on changes.
 * Issues are built from applying the changes in the order they were
 * committed to the repository. The changes are actually specified in the
 * commit messages and not in the RevTrees which allows for clean,
 * distributed merging./*from   w  w w  .jav  a  2s.c om*/
 * 
 * @param repository
 * @param issueId
 * @param change
 * @return true, if the change was committed
 */
private static boolean commit(Repository repository, String issueId, Change change) {
    boolean success = false;

    try {
        // assign ids to new attachments
        // attachments are stored by an SHA1 id
        if (change.hasAttachments()) {
            for (Attachment attachment : change.attachments) {
                if (!ArrayUtils.isEmpty(attachment.content)) {
                    byte[] prefix = (change.created.toString() + change.author).getBytes();
                    byte[] bytes = new byte[prefix.length + attachment.content.length];
                    System.arraycopy(prefix, 0, bytes, 0, prefix.length);
                    System.arraycopy(attachment.content, 0, bytes, prefix.length, attachment.content.length);
                    attachment.id = "attachment-" + StringUtils.getSHA1(bytes);
                }
            }
        }

        // serialize the change as json
        // exclude any attachment from json serialization
        Gson gson = JsonUtils.gson(new ExcludeField("com.gitblit.models.IssueModel$Attachment.content"));
        String json = gson.toJson(change);

        // include the json change in the commit message
        String issuePath = getIssuePath(issueId);
        String message = change.code + " " + issueId + "\n\n" + json;

        // Create a commit file. This is required for a proper commit and
        // ensures we can retrieve the commit log of the issue path.
        //
        // This file is NOT serialized as part of the Change object.
        switch (change.code) {
        case '+': {
            // New Issue.
            Attachment placeholder = new Attachment("issue");
            placeholder.id = placeholder.name;
            placeholder.content = "DO NOT REMOVE".getBytes(Constants.CHARACTER_ENCODING);
            change.addAttachment(placeholder);
            break;
        }
        default: {
            // Update Issue.
            String changeId = StringUtils.getSHA1(json);
            Attachment placeholder = new Attachment("change-" + changeId);
            placeholder.id = placeholder.name;
            placeholder.content = "REMOVABLE".getBytes(Constants.CHARACTER_ENCODING);
            change.addAttachment(placeholder);
            break;
        }
        }

        ObjectId headId = repository.resolve(GB_ISSUES + "^{commit}");
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create the in-memory index of the new/updated issue
            DirCache index = createIndex(repository, headId, issuePath, change);
            ObjectId indexTreeId = index.writeTree(odi);

            // Create a commit object
            PersonIdent ident = new PersonIdent(change.author, "gitblit@localhost");
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(ident);
            commit.setCommitter(ident);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage(message);
            commit.setParentId(headId);
            commit.setTreeId(indexTreeId);

            // Insert the commit into the repository
            ObjectId commitId = odi.insert(commit);
            odi.flush();

            RevWalk revWalk = new RevWalk(repository);
            try {
                RevCommit revCommit = revWalk.parseCommit(commitId);
                RefUpdate ru = repository.updateRef(GB_ISSUES);
                ru.setNewObjectId(commitId);
                ru.setExpectedOldObjectId(headId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result rc = ru.forceUpdate();
                switch (rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    success = true;
                    break;
                case REJECTED:
                case LOCK_FAILURE:
                    throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
                default:
                    throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            GB_ISSUES, commitId.toString(), rc));
                }
            } finally {
                revWalk.release();
            }
        } finally {
            odi.release();
        }
    } catch (Throwable t) {
        error(t, repository, "Failed to commit issue {1} to {0}", issueId);
    }
    return success;
}

From source file:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Create an orphaned branch in a repository.
 *
 * @param repository/*from w  w w . j  av a2  s .c o  m*/
 * @param branchName
 * @param author
 *            if unspecified, Gitblit will be the author of this new branch
 * @return true if successful
 */
public static boolean createOrphanBranch(Repository repository, String branchName, PersonIdent author) {
    boolean success = false;
    String message = "Created branch " + branchName;
    if (author == null) {
        author = new PersonIdent("Gitblit", "gitblit@localhost");
    }
    try {
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create a blob object to insert into a tree
            ObjectId blobId = odi.insert(Constants.OBJ_BLOB, message.getBytes(Constants.CHARACTER_ENCODING));

            // Create a tree object to reference from a commit
            TreeFormatter tree = new TreeFormatter();
            tree.append(".branch", FileMode.REGULAR_FILE, blobId);
            ObjectId treeId = odi.insert(tree);

            // Create a commit object
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(author);
            commit.setCommitter(author);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage(message);
            commit.setTreeId(treeId);

            // Insert the commit into the repository
            ObjectId commitId = odi.insert(commit);
            odi.flush();

            RevWalk revWalk = new RevWalk(repository);
            try {
                RevCommit revCommit = revWalk.parseCommit(commitId);
                if (!branchName.startsWith("refs/")) {
                    branchName = "refs/heads/" + branchName;
                }
                RefUpdate ru = repository.updateRef(branchName);
                ru.setNewObjectId(commitId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result rc = ru.forceUpdate();
                switch (rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    success = true;
                    break;
                default:
                    success = false;
                }
            } finally {
                revWalk.close();
            }
        } finally {
            odi.close();
        }
    } catch (Throwable t) {
        error(t, repository, "Failed to create orphan branch {1} in repository {0}", branchName);
    }
    return success;
}

From source file:com.gitblit.utils.PushLogUtils.java

License:Apache License

/**
 * Updates a push log.//from ww  w.  j a  v  a  2s  .c om
 * 
 * @param user
 * @param repository
 * @param commands
 * @return true, if the update was successful
 */
public static boolean updatePushLog(UserModel user, Repository repository,
        Collection<ReceiveCommand> commands) {
    RefModel pushlogBranch = getPushLogBranch(repository);
    if (pushlogBranch == null) {
        JGitUtils.createOrphanBranch(repository, GB_PUSHES, null);
    }

    boolean success = false;
    String message = "push";

    try {
        ObjectId headId = repository.resolve(GB_PUSHES + "^{commit}");
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create the in-memory index of the push log entry
            DirCache index = createIndex(repository, headId, commands);
            ObjectId indexTreeId = index.writeTree(odi);

            PersonIdent ident = new PersonIdent(user.getDisplayName(),
                    user.emailAddress == null ? user.username : user.emailAddress);

            // Create a commit object
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(ident);
            commit.setCommitter(ident);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage(message);
            commit.setParentId(headId);
            commit.setTreeId(indexTreeId);

            // Insert the commit into the repository
            ObjectId commitId = odi.insert(commit);
            odi.flush();

            RevWalk revWalk = new RevWalk(repository);
            try {
                RevCommit revCommit = revWalk.parseCommit(commitId);
                RefUpdate ru = repository.updateRef(GB_PUSHES);
                ru.setNewObjectId(commitId);
                ru.setExpectedOldObjectId(headId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result rc = ru.forceUpdate();
                switch (rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    success = true;
                    break;
                case REJECTED:
                case LOCK_FAILURE:
                    throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
                default:
                    throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            GB_PUSHES, commitId.toString(), rc));
                }
            } finally {
                revWalk.release();
            }
        } finally {
            odi.release();
        }
    } catch (Throwable t) {
        error(t, repository, "Failed to commit pushlog entry to {0}");
    }
    return success;
}

From source file:com.gitblit.wicket.pages.MyDashboardPage.java

License:Apache License

private String readMarkdown(String messageSource, String resource) {
    String message = "";
    if (messageSource.equalsIgnoreCase("gitblit")) {
        // Read default message
        message = readDefaultMarkdown(resource);
    } else {//from   w w  w .  j  ava2s  . c om
        // Read user-supplied message
        if (!StringUtils.isEmpty(messageSource)) {
            File file = app().runtime().getFileOrFolder(messageSource);
            if (file.exists()) {
                try {
                    FileInputStream fis = new FileInputStream(file);
                    InputStreamReader reader = new InputStreamReader(fis, Constants.CHARACTER_ENCODING);
                    message = MarkdownUtils.transformMarkdown(reader);
                    reader.close();
                } catch (Throwable t) {
                    message = getString("gb.failedToRead") + " " + file;
                    warn(message, t);
                }
            } else {
                message = messageSource + " " + getString("gb.isNotValidFile");
            }
        }
    }
    return message;
}

From source file:com.gitblit.wicket.pages.MyDashboardPage.java

License:Apache License

private String readDefaultMarkdown(String file) {
    String base = file.substring(0, file.lastIndexOf('.'));
    String ext = file.substring(file.lastIndexOf('.'));
    String lc = getLanguageCode();
    String cc = getCountryCode();

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

    for (String name : files) {
        String message;
        InputStreamReader reader = null;
        try {
            InputStream is = getClass().getResourceAsStream("/" + name);
            if (is == null) {
                continue;
            }
            reader = new InputStreamReader(is, Constants.CHARACTER_ENCODING);
            message = MarkdownUtils.transformMarkdown(reader);
            reader.close();
            return message;
        } catch (Throwable t) {
            message = MessageFormat.format(getString("gb.failedToReadMessage"), file);
            error(message, t, false);
            return message;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                }
            }
        }
    }
    return MessageFormat.format(getString("gb.failedToReadMessage"), file);
}

From source file:com.gitblit.wicket.pages.ProjectPage.java

License:Apache License

private String readMarkdown(String projectName, File projectMessage) {
    String message = "";
    if (projectMessage.exists()) {
        // Read user-supplied message
        try {/*ww w .j  a v  a  2  s.  c o m*/
            FileInputStream fis = new FileInputStream(projectMessage);
            InputStreamReader reader = new InputStreamReader(fis, Constants.CHARACTER_ENCODING);
            message = MarkdownUtils.transformMarkdown(reader);
            reader.close();
        } catch (Throwable t) {
            message = getString("gb.failedToRead") + " " + projectMessage;
            warn(message, t);
        }
    }
    return message;
}

From source file:com.gitblit.wicket.pages.ProjectsPage.java

License:Apache License

private String readMarkdown(String messageSource, String resource) {
    String message = "";
    if (messageSource.equalsIgnoreCase("gitblit")) {
        // Read default message
        message = readDefaultMarkdown(resource);
    } else {//from  w  ww  .ja v  a 2  s. com
        // Read user-supplied message
        if (!StringUtils.isEmpty(messageSource)) {
            File file = new File(messageSource);
            if (file.exists()) {
                try {
                    FileInputStream fis = new FileInputStream(file);
                    InputStreamReader reader = new InputStreamReader(fis, Constants.CHARACTER_ENCODING);
                    message = MarkdownUtils.transformMarkdown(reader);
                    reader.close();
                } catch (Throwable t) {
                    message = getString("gb.failedToRead") + " " + file;
                    warn(message, t);
                }
            } else {
                message = messageSource + " " + getString("gb.isNotValidFile");
            }
        }
    }
    return message;
}

From source file:com.gitblit.wicket.pages.ProjectsPage.java

License:Apache License

private String readDefaultMarkdown(String file, String lc) {
    if (!StringUtils.isEmpty(lc)) {
        // convert to file_lc.mkd
        file = file.substring(0, file.lastIndexOf('.')) + "_" + lc + file.substring(file.lastIndexOf('.'));
    }// w w  w  .j  a  v a 2  s .c  o  m
    String message;
    try {
        ContextRelativeResource res = WicketUtils.getResource(file);
        InputStream is = res.getResourceStream().getInputStream();
        InputStreamReader reader = new InputStreamReader(is, Constants.CHARACTER_ENCODING);
        message = MarkdownUtils.transformMarkdown(reader);
        reader.close();
    } catch (ResourceStreamNotFoundException t) {
        if (lc == null) {
            // could not find default language resource
            message = MessageFormat.format(getString("gb.failedToReadMessage"), file);
            error(message, t, false);
        } else {
            // ignore so we can try default language resource
            message = null;
        }
    } catch (Throwable t) {
        message = MessageFormat.format(getString("gb.failedToReadMessage"), file);
        error(message, t, false);
    }
    return message;
}