List of usage examples for org.eclipse.jgit.lib ObjectLoader getBytes
public final byte[] getBytes() throws LargeObjectException
From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java
License:Open Source License
/** * loads all patches of from the given list of {@link DiffEntry}s. * // ww w . j av a 2 s.com * @param patchSet * the patchSet to add the patches to. * @param ref * the ref to the commit of the patch set. * @param repository * the git repository instance * @throws RepositoryIOException */ private void loadPatches(PatchSet patchSet, Ref ref, Git git) throws RepositoryIOException { EList<Patch> patches = patchSet.getPatches(); Repository repository = git.getRepository(); try { RevWalk revWalk = new RevWalk(repository); RevCommit newCommit = revWalk.parseCommit(ref.getObjectId()); RevCommit oldCommit = newCommit.getParent(0); revWalk.parseHeaders(oldCommit); ObjectReader objectReader = repository.newObjectReader(); revWalk.close(); CanonicalTreeParser newTreeIterator = new CanonicalTreeParser(); newTreeIterator.reset(objectReader, newCommit.getTree().getId()); CanonicalTreeParser oldTreeIterator = new CanonicalTreeParser(); oldTreeIterator.reset(objectReader, oldCommit.getTree().getId()); List<DiffEntry> diffs = git.diff().setOldTree(oldTreeIterator).setNewTree(newTreeIterator).call(); for (DiffEntry diff : diffs) { String newPath = diff.getNewPath(); String oldPath = diff.getOldPath(); Patch patch = null; /* * only papyrus diagrams are supported for now, so models are in * .uml files, diagrams in .notation files */ if (diff.getChangeType() != ChangeType.DELETE) { if (newPath.endsWith(".uml")) { patch = modelReviewFactory.createModelPatch(); } else if (newPath.endsWith(".notation")) { patch = modelReviewFactory.createDiagramPatch(); } else { patch = modelReviewFactory.createPatch(); } } else { if (oldPath.endsWith(".uml")) { patch = modelReviewFactory.createModelPatch(); } else if (oldPath.endsWith(".notation")) { patch = modelReviewFactory.createDiagramPatch(); } else { patch = modelReviewFactory.createPatch(); } } switch (diff.getChangeType()) { case ADD: patch.setChangeType(PatchChangeType.ADD); break; case COPY: patch.setChangeType(PatchChangeType.COPY); break; case DELETE: patch.setChangeType(PatchChangeType.DELETE); break; case MODIFY: patch.setChangeType(PatchChangeType.MODIFY); break; case RENAME: patch.setChangeType(PatchChangeType.RENAME); break; } patch.setNewPath(newPath); patch.setOldPath(oldPath); if (diff.getChangeType() != ChangeType.DELETE) { ObjectLoader objectLoader = repository.open(diff.getNewId().toObjectId()); patch.setNewContent(objectLoader.getBytes()); } if (diff.getChangeType() != ChangeType.ADD) { ObjectLoader objectLoader = repository.open(diff.getOldId().toObjectId()); patch.setOldContent(objectLoader.getBytes()); } patches.add(patch); } } catch (IOException e) { throw new RepositoryIOException(MessageFormat.format( "An IO error occured during loading the patches for patch set #{0}", patchSet.getId()), e); } catch (GitAPIException e) { throw new RepositoryIOException( MessageFormat.format("An JGit API error occured during loading the patches for patch set #{0}", patchSet.getId()), e); } }
From source file:ch.uzh.ifi.seal.permo.history.git.core.model.jgit.JGitDiff.java
License:Apache License
private String getContent(final ObjectId id) { try {/*from w ww . j av a2s . c om*/ final ObjectLoader loader = repository.open(id); return new String(loader.getBytes()); } catch (final IOException e) { return EMPTY; } }
From source file:com.bacoder.scmtools.git.internal.CloneAndProcessDirCacheCheckout.java
License:Apache License
@Override protected boolean checkoutEntries() throws IOException { Map<String, ObjectId> updated = getUpdated(); List<String> paths = Lists.newArrayList(updated.keySet()); Collections.sort(paths);/*www. j a v a 2 s .co m*/ ObjectReader objectReader = repository.getObjectDatabase().newReader(); try { for (String path : paths) { DirCacheEntry entry = dirCache.getEntry(path); if (FileMode.GITLINK.equals(entry.getRawMode())) continue; boolean isSubmoduleConfig = path.equals(Constants.DOT_GIT_MODULES); ObjectId objectId = updated.get(path); if (isSubmoduleConfig) { ObjectLoader loader = objectReader.open(objectId); byte[] data = loader.getBytes(); submodulesConfig = data; } if (processor != null) { GitEntry gitEntry = new GitEntry(repository, objectId, pathPrefix, path); try { processor.process(gitEntry); } catch (Exception e) { throw new InternalRuntimeException(e); } } } // commit the index builder - a new index is persisted if (!getBuilder().commit()) throw new IndexWriteException(); } finally { objectReader.release(); } return true; }
From source file:com.github.kaitoy.goslings.server.dao.jgit.ObjectDaoImpl.java
License:Open Source License
@Cacheable private RawContents getRawContents(String token, String objectId) { try {// w w w .j av a 2 s . c om ObjectLoader loader = resolver.getRepository(token).open(ObjectId.fromString(objectId)); return new RawContents(loader.getType(), loader.getBytes()); } catch (MissingObjectException e) { String message = new StringBuilder().append("The specified object ").append(objectId) .append(" doesn't exist in the repository ").append(token).append(".").toString(); LOG.error(message, e); throw new DaoException(message, e); } catch (IOException e) { String message = new StringBuilder().append("Failed to get contents of the specified object ") .append(objectId).append(" in the repository ").append(token).append(".").toString(); LOG.error(message, e); throw new DaoException(message, e); } }
From source file:com.mangosolutions.rcloud.rawgist.repository.git.ReadGistOperation.java
private FileContent readContent(Repository repository, TreeWalk treeWalk) { ObjectId objectId = treeWalk.getObjectId(0); String fileName = treeWalk.getPathString(); FileContent content = fileContentCache.load(objectId.getName(), fileName); if (content == null) { content = new FileContent(); try {//from ww w . ja va2 s . c om content.setFilename(fileName); ObjectLoader loader = repository.open(objectId); content.setContent(new String(loader.getBytes(), Charsets.UTF_8)); content.setSize(loader.getSize()); content.setTruncated(false); String language = FilenameUtils.getExtension(fileName); if (!GitGistRepository.B64_BINARY_EXTENSION.equals(language) && !StringUtils.isEmpty(language)) { content.setLanguage(language); } content.setType(MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(fileName)); fileContentCache.save(objectId.getName(), fileName, content); } catch (IOException e) { GistError error = new GistError(GistErrorCode.ERR_GIST_CONTENT_NOT_READABLE, "Could not read content of {} for gist {}", fileName, gistId); logger.error(error.getFormattedMessage() + " with path {}", this.layout.getRootFolder(), e); throw new GistRepositoryError(error, e); } } return content; }
From source file:com.smartitengineering.version.impl.jgit.JGitImpl.java
License:Open Source License
public byte[] readObject(final String objectIdStr) throws IOException, IllegalArgumentException { if (StringUtils.isBlank(objectIdStr)) { throw new IllegalArgumentException("Invalid Object id!"); }/* w ww . jav a2 s . c o m*/ ObjectId objectId = ObjectId.fromString(objectIdStr); ObjectLoader objectLoader = getReadRepository().openObject(objectId); if (objectLoader.getType() != Constants.OBJ_BLOB) { throw new IllegalArgumentException("Not a blob: " + objectIdStr); } return objectLoader.getBytes(); }
From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java
License:Open Source License
public static Blob getBlob(Repository r, String revision, String path) throws IOException, EntityNotFoundException { if (path.startsWith("/")) { path = path.substring(1);/*from ww w . ja v a2 s. co m*/ } String id = resolve(r, r.resolve(revision), path); if (id == null) { throw new EntityNotFoundException(); } ObjectId objectId = ObjectId.fromString(id); ObjectLoader loader = r.getObjectDatabase().open(objectId, Constants.OBJ_BLOB); Blob b = new Blob(id); if (loader.isLarge()) { b.setLarge(true); InputStream is = null; IOException ioex = null; try { is = loader.openStream(); b.setBinary(RawText.isBinary(is)); } catch (IOException ex) { ioex = ex; } finally { if (is != null) { is.close(); } if (ioex != null) { throw ioex; } } } else { byte[] raw = loader.getBytes(); boolean binary = RawText.isBinary(raw); if (binary) { b.setBinary(true); b.setLines(Collections.<String>emptyList()); } else { RawText rt = new RawText(raw); List<String> lines = new ArrayList<String>(rt.size()); for (int i = 0; i < rt.size(); i++) { lines.add(rt.getString(i)); } b.setLines(lines); } } return b; }
From source file:com.thoughtworks.go.service.ConfigRepository.java
License:Apache License
private byte[] contentFromTree(RevTree tree) { try {/*from w w w . j a va 2 s . co m*/ final ObjectReader reader = gitRepo.newObjectReader(); CanonicalTreeParser parser = new CanonicalTreeParser(); parser.reset(reader, tree); String lastPath = null; while (true) { final String path = parser.getEntryPathString(); parser = parser.next(); if (path.equals(lastPath)) { break; } lastPath = path; if (path.equals(CRUISE_CONFIG_XML)) { final ObjectId id = parser.getEntryObjectId(); final ObjectLoader loader = reader.open(id); return loader.getBytes(); } } return null; } catch (IOException e) { LOGGER.error("Could not fetch content from the config repository found at path '{}'", workingDir.getAbsolutePath(), e); throw new RuntimeException("Error while fetching content from the config repository.", e); } }
From source file:de.codesourcery.gittimelapse.GitHelper.java
License:Apache License
protected void readFile(String path, PathFilter filter, RevCommit current, final ByteArrayOutputStream buffer) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { final String strippedPath = stripRepoBaseDir(path); final ITreeVisitor visitor = new ITreeVisitor() { @Override/*from w w w.ja va2 s . c o m*/ public boolean visit(TreeWalk treeWalk) throws MissingObjectException, IOException { final CanonicalTreeParser parser = treeWalk.getTree(0, CanonicalTreeParser.class); while (!parser.eof()) { if (parser.getEntryPathString().equals(strippedPath)) { ObjectLoader loader = repository.open(parser.getEntryObjectId()); buffer.write(loader.getBytes()); } parser.next(1); } return true; } }; visitCommitTree(path, filter, current, visitor); }
From source file:i5.las2peer.services.codeGenerationService.generators.MicroserviceGenerator.java
/** * /*from www . ja va 2s . c o m*/ * Creates source code from a CAE microservice model and pushes it to GitHub. * * @param microservice the microservice model * @param templateRepositoryName the name of the template repository on GitHub * @param gitHubOrganization the organization that is used in the CAE * @param gitHubUser the CAE user * @param gitHubUserMail the mail of the CAE user * @param gitHubPassword the password of the CAE user * * @throws GitHubException thrown if anything goes wrong during this process. Wraps around all * other exceptions and prints their message. * */ public static void createSourceCode(Microservice microservice, String templateRepositoryName, String gitHubOrganization, String gitHubUser, String gitHubUserMail, String gitHubPassword) throws GitHubException { // variables to be closed in the final block Repository microserviceRepository = null; TreeWalk treeWalk = null; // helper variables String packageName = microservice.getResourceName().substring(0, 1).toLowerCase() + microservice.getResourceName().substring(1); // get the port: skip first 6 characters for search (http: / https:) String port = microservice.getPath().substring(microservice.getPath().indexOf(":", 6) + 1, microservice.getPath().indexOf("/", microservice.getPath().indexOf(":", 6))); // variables holding content to be modified and added to repository later String projectFile = null; BufferedImage logo = null; String readMe = null; String license = null; String buildFile = null; String startScriptWindows = null; String startScriptUnix = null; String userAgentGeneratorWindows = null; String userAgentGeneratorUnix = null; String nodeInfo = null; String antServiceProperties = null; String antUserProperties = null; String ivy = null; String ivySettings = null; String serviceProperties = null; String webConnectorConfig = null; String gitignore = null; String classpath = null; String databaseManager = null; String serviceClass = null; String serviceTest = null; String genericHttpMethod = null; String genericApiResponse = null; String genericHttpResponse = null; String genericTestCase = null; String databaseConfig = null; String databaseInstantiation = null; String serviceInvocation = null; String databaseScript = null; String genericTable = null; try { PersonIdent caeUser = new PersonIdent(gitHubUser, gitHubUserMail); String repositoryName = "microservice-" + microservice.getName().replace(" ", "-"); microserviceRepository = generateNewRepository(repositoryName, gitHubOrganization, gitHubUser, gitHubPassword); try { // now load the TreeWalk containing the template repository content treeWalk = getTemplateRepositoryContent(templateRepositoryName, gitHubOrganization); treeWalk.setFilter(PathFilter.create("backend/")); ObjectReader reader = treeWalk.getObjectReader(); // walk through the tree and retrieve the needed templates while (treeWalk.next()) { ObjectId objectId = treeWalk.getObjectId(0); ObjectLoader loader = reader.open(objectId); switch (treeWalk.getNameString()) { // start with the "easy" replacements, and store the other template files for later case ".project": projectFile = new String(loader.getBytes(), "UTF-8"); projectFile = projectFile.replace("$Microservice_Name$", microservice.getName()); break; case "logo_services.png": logo = ImageIO.read(loader.openStream()); break; case "README.md": readMe = new String(loader.getBytes(), "UTF-8"); readMe = readMe.replace("$Repository_Name$", repositoryName); readMe = readMe.replace("$Organization_Name$", gitHubOrganization); readMe = readMe.replace("$Microservice_Name$", microservice.getName()); break; case "LICENSE.txt": license = new String(loader.getBytes(), "UTF-8"); break; case "build.xml": buildFile = new String(loader.getBytes(), "UTF-8"); buildFile = buildFile.replace("$Microservice_Name$", microservice.getName()); break; case "start_network.bat": startScriptWindows = new String(loader.getBytes(), "UTF-8"); startScriptWindows = startScriptWindows.replace("$Resource_Name$", microservice.getResourceName()); startScriptWindows = startScriptWindows.replace("$Lower_Resource_Name$", packageName); startScriptWindows = startScriptWindows.replace("$Microservice_Version$", microservice.getVersion() + ""); break; case "start_network.sh": startScriptUnix = new String(loader.getBytes(), "UTF-8"); startScriptUnix = startScriptUnix.replace("$Resource_Name$", microservice.getResourceName()); startScriptUnix = startScriptUnix.replace("$Lower_Resource_Name$", packageName); startScriptUnix = startScriptUnix.replace("$Microservice_Version$", microservice.getVersion() + ""); break; case "start_UserAgentGenerator.bat": userAgentGeneratorWindows = new String(loader.getBytes(), "UTF-8"); break; case "start_UserAgentGenerator.sh": userAgentGeneratorUnix = new String(loader.getBytes(), "UTF-8"); break; case "nodeInfo.xml": nodeInfo = new String(loader.getBytes(), "UTF-8"); nodeInfo = nodeInfo.replace("$Developer$", microservice.getDeveloper()); nodeInfo = nodeInfo.replace("$Resource_Name$", microservice.getResourceName()); break; case "service.properties": antServiceProperties = new String(loader.getBytes(), "UTF-8"); antServiceProperties = antServiceProperties.replace("$Microservice_Version$", microservice.getVersion() + ""); antServiceProperties = antServiceProperties.replace("$Lower_Resource_Name$", packageName); antServiceProperties = antServiceProperties.replace("$Resource_Name$", microservice.getResourceName()); antServiceProperties = antServiceProperties.replace("$Microservice_Version$", microservice.getVersion() + ""); break; case "user.properties": antUserProperties = new String(loader.getBytes(), "UTF-8"); break; case "ivy.xml": ivy = new String(loader.getBytes(), "UTF-8"); // add mysql dependency only if a database exists if (microservice.getDatabase() != null) { ivy = ivy.replace("$MySQL_Dependencies$", "<dependency org=\"mysql\" name=\"mysql-connector-java\" rev=\"5.1.6\" />\n" + " <dependency org=\"org.apache.commons\" name=\"commons-pool2\" rev=\"2.2\" />\n" + " <dependency org=\"org.apache.commons\" name=\"commons-dbcp2\" rev=\"2.0\" />"); } else { ivy = ivy.replace(" $MySQL_Dependencies$\n", ""); } break; case "ivysettings.xml": ivySettings = new String(loader.getBytes(), "UTF-8"); break; case "i5.las2peer.services.servicePackage.ServiceClass.properties": serviceProperties = new String(loader.getBytes(), "UTF-8"); // if database does not exist, clear the file if (microservice.getDatabase() == null) { serviceProperties = ""; } else { serviceProperties = serviceProperties.replace("$Database_Address$", microservice.getDatabase().getAddress()); serviceProperties = serviceProperties.replace("$Database_Schema$", microservice.getDatabase().getSchema()); serviceProperties = serviceProperties.replace("$Database_User$", microservice.getDatabase().getLoginName()); serviceProperties = serviceProperties.replace("$Database_Password$", microservice.getDatabase().getLoginPassword()); } case "i5.las2peer.webConnector.WebConnector.properties": webConnectorConfig = new String(loader.getBytes(), "UTF-8"); webConnectorConfig = webConnectorConfig.replace("$HTTP_Port$", port); break; case ".gitignore": gitignore = new String(loader.getBytes(), "UTF-8"); break; case ".classpath": classpath = new String(loader.getBytes(), "UTF-8"); if (microservice.getDatabase() != null) { classpath = classpath.replace("$Database_Libraries$", "<classpathentry kind=\"lib\" path=\"lib/mysql-connector-java-5.1.6.jar\"/>\n" + " <classpathentry kind=\"lib\" path=\"lib/commons-dbcp2-2.0.jar\"/>"); } else { classpath = classpath.replace("$Database_Libraries$\n", ""); } break; case "DatabaseManager.java": if (microservice.getDatabase() != null) { databaseManager = new String(loader.getBytes(), "UTF-8"); databaseManager = databaseManager.replace("$Lower_Resource_Name$", packageName); } break; case "ServiceClass.java": serviceClass = new String(loader.getBytes(), "UTF-8"); break; case "genericHTTPMethod.txt": genericHttpMethod = new String(loader.getBytes(), "UTF-8"); break; case "genericHTTPResponse.txt": genericHttpResponse = new String(loader.getBytes(), "UTF-8"); break; case "genericApiResponse.txt": genericApiResponse = new String(loader.getBytes(), "UTF-8"); break; case "ServiceTest.java": serviceTest = new String(loader.getBytes(), "UTF-8"); break; case "genericTestMethod.txt": genericTestCase = new String(loader.getBytes(), "UTF-8"); break; case "databaseConfig.txt": databaseConfig = new String(loader.getBytes(), "UTF-8"); break; case "databaseInstantiation.txt": databaseInstantiation = new String(loader.getBytes(), "UTF-8"); break; case "genericServiceInvocation.txt": serviceInvocation = new String(loader.getBytes(), "UTF-8"); break; case "database.sql": databaseScript = new String(loader.getBytes(), "UTF-8"); break; case "genericTable.txt": genericTable = new String(loader.getBytes(), "UTF-8"); break; } } } catch (Exception e) { logger.printStackTrace(e); throw new GitHubException(e.getMessage()); } // generate service class and test String repositoryLocation = "https://github.com/" + gitHubOrganization + "/" + repositoryName; serviceClass = generateNewServiceClass(serviceClass, microservice, repositoryLocation, genericHttpMethod, genericApiResponse, genericHttpResponse, databaseConfig, databaseInstantiation, serviceInvocation); serviceTest = generateNewServiceTest(serviceTest, microservice, genericTestCase); if (microservice.getDatabase() != null) { databaseScript = generateDatabaseScript(databaseScript, genericTable, microservice); } // add files to new repository // configuration and build stuff microserviceRepository = createTextFileInRepository(microserviceRepository, "etc/ivy/", "ivy.xml", ivy); microserviceRepository = createTextFileInRepository(microserviceRepository, "etc/ivy/", "ivysettings.xml", ivySettings); microserviceRepository = createTextFileInRepository(microserviceRepository, "", "build.xml", buildFile); microserviceRepository = createTextFileInRepository(microserviceRepository, "etc/ant_configuration/", "user.properties", antUserProperties); microserviceRepository = createTextFileInRepository(microserviceRepository, "etc/ant_configuration/", "service.properties", antServiceProperties); microserviceRepository = createTextFileInRepository(microserviceRepository, "etc/", "nodeInfo.xml", nodeInfo); microserviceRepository = createTextFileInRepository(microserviceRepository, "", ".project", projectFile); microserviceRepository = createTextFileInRepository(microserviceRepository, "", ".gitignore", gitignore); microserviceRepository = createTextFileInRepository(microserviceRepository, "", ".classpath", classpath); // property files microserviceRepository = createTextFileInRepository(microserviceRepository, "etc/", "i5.las2peer.services." + packageName + "." + microservice.getResourceName() + ".properties", serviceProperties); microserviceRepository = createTextFileInRepository(microserviceRepository, "etc/", "i5.las2peer.webConnector.WebConnector.properties", webConnectorConfig); // scripts microserviceRepository = createTextFileInRepository(microserviceRepository, "bin/", "start_network.bat", startScriptWindows); microserviceRepository = createTextFileInRepository(microserviceRepository, "bin/", "start_network.sh", startScriptUnix); microserviceRepository = createTextFileInRepository(microserviceRepository, "bin/", "start_UserAgentGenerator.bat", userAgentGeneratorWindows); microserviceRepository = createTextFileInRepository(microserviceRepository, "bin/", "start_UserAgentGenerator.sh", userAgentGeneratorUnix); // doc microserviceRepository = createTextFileInRepository(microserviceRepository, "", "README.md", readMe); microserviceRepository = createTextFileInRepository(microserviceRepository, "", "LICENSE.txt", license); microserviceRepository = createImageFileInRepository(microserviceRepository, "img/", "logo.png", logo); // source code if (databaseManager != null) { microserviceRepository = createTextFileInRepository(microserviceRepository, "src/main/i5/las2peer/services/" + packageName + "/database/", "DatabaseManager.java", databaseManager); // database script (replace spaces in filename for better usability later on) microserviceRepository = createTextFileInRepository(microserviceRepository, "db/", microservice.getName().replace(" ", "_") + "_create_tables.sql", databaseScript); } microserviceRepository = createTextFileInRepository(microserviceRepository, "src/main/i5/las2peer/services/" + packageName + "/", microservice.getResourceName() + ".java", serviceClass); microserviceRepository = createTextFileInRepository(microserviceRepository, "src/test/i5/las2peer/services/" + packageName + "/", microservice.getResourceName() + "Test.java", serviceTest); // commit files try { Git.wrap(microserviceRepository).commit() .setMessage("Generated microservice version " + microservice.getVersion()) .setCommitter(caeUser).call(); } catch (Exception e) { logger.printStackTrace(e); throw new GitHubException(e.getMessage()); } // push (local) repository content to GitHub repository try { pushToRemoteRepository(microserviceRepository, gitHubUser, gitHubPassword); } catch (Exception e) { logger.printStackTrace(e); throw new GitHubException(e.getMessage()); } // close all open resources } finally { microserviceRepository.close(); treeWalk.close(); } }