Example usage for org.eclipse.jgit.transport ReceivePack receive

List of usage examples for org.eclipse.jgit.transport ReceivePack receive

Introduction

In this page you can find the example usage for org.eclipse.jgit.transport ReceivePack receive.

Prototype

public void receive(final InputStream input, final OutputStream output, final OutputStream messages)
        throws IOException 

Source Link

Document

Execute the receive task on the socket.

Usage

From source file:com.gitblit.git.GitDaemon.java

License:Eclipse Distribution License

public GitDaemon(IGitblit gitblit) {

    IStoredSettings settings = gitblit.getSettings();
    int port = settings.getInteger(Keys.git.daemonPort, 0);
    String bindInterface = settings.getString(Keys.git.daemonBindInterface, "localhost");

    if (StringUtils.isEmpty(bindInterface)) {
        myAddress = new InetSocketAddress(port);
    } else {/*from   ww w . java2 s .  c  o  m*/
        myAddress = new InetSocketAddress(bindInterface, port);
    }

    repositoryResolver = new RepositoryResolver<GitDaemonClient>(gitblit);
    uploadPackFactory = new GitblitUploadPackFactory<GitDaemonClient>(gitblit);
    receivePackFactory = new GitblitReceivePackFactory<GitDaemonClient>(gitblit);

    run = new AtomicBoolean(false);
    processors = new ThreadGroup("Git-Daemon");
    services = new GitDaemonService[] { new GitDaemonService("upload-pack", "uploadpack") {
        {
            setEnabled(true);
            setOverridable(false);
        }

        @Override
        protected void execute(final GitDaemonClient dc, final Repository db)
                throws IOException, ServiceNotEnabledException, ServiceNotAuthorizedException {
            UploadPack up = uploadPackFactory.create(dc, db);
            InputStream in = dc.getInputStream();
            OutputStream out = dc.getOutputStream();
            up.upload(in, out, null);
        }
    }, new GitDaemonService("receive-pack", "receivepack") {
        {
            setEnabled(true);
            setOverridable(false);
        }

        @Override
        protected void execute(final GitDaemonClient dc, final Repository db)
                throws IOException, ServiceNotEnabledException, ServiceNotAuthorizedException {
            ReceivePack rp = receivePackFactory.create(dc, db);
            InputStream in = dc.getInputStream();
            OutputStream out = dc.getOutputStream();
            rp.receive(in, out, null);
        }
    } };
}

From source file:com.gitblit.transport.ssh.git.Receive.java

License:Apache License

@Override
protected void runImpl() throws Failure {
    SshKey key = getContext().getClient().getKey();
    if (key != null && !key.canPush()) {
        throw new Failure(1, "Sorry, your SSH public key is not allowed to push changes!");
    }/*  ww  w. j ava 2 s.co  m*/
    try {
        ReceivePack rp = receivePackFactory.create(getContext().getClient(), repo);
        rp.receive(in, out, null);
    } catch (Exception e) {
        throw new Failure(1, "fatal: Cannot receive pack: ", e);
    }
}

From source file:com.google.gerrit.sshd.commands.Receive.java

License:Apache License

@Override
protected void runImpl() throws IOException, Failure {
    if (!projectControl.canRunReceivePack()) {
        throw new Failure(1, "fatal: receive-pack not permitted on this server");
    }//  ww w .jav  a2s  . c  o m

    final ReceiveCommits receive = factory.create(projectControl, repo).getReceiveCommits();

    Capable r = receive.canUpload();
    if (r != Capable.OK) {
        throw new UnloggedFailure(1, "\nfatal: " + r.getMessage());
    }

    verifyProjectVisible("reviewer", reviewerId);
    verifyProjectVisible("CC", ccId);

    receive.addReviewers(reviewerId);
    receive.addExtraCC(ccId);

    final ReceivePack rp = receive.getReceivePack();
    rp.setRefLogIdent(currentUser.newRefLogIdent());
    rp.setTimeout(config.getTimeout());
    rp.setMaxObjectSizeLimit(config.getEffectiveMaxObjectSizeLimit(projectControl.getProjectState()));
    init(rp);
    rp.setPostReceiveHook(PostReceiveHookChain.newChain(Lists.newArrayList(postReceiveHooks)));
    try {
        rp.receive(in, out, err);
    } catch (UnpackException badStream) {
        // In case this was caused by the user pushing an object whose size
        // is larger than the receive.maxObjectSizeLimit gerrit.config parameter
        // we want to present this error to the user
        if (badStream.getCause() instanceof TooLargeObjectInPackException) {
            StringBuilder msg = new StringBuilder();
            msg.append("Receive error on project \"").append(projectControl.getProject().getName())
                    .append("\"");
            msg.append(" (user ");
            msg.append(currentUser.getAccount().getUserName());
            msg.append(" account ");
            msg.append(currentUser.getAccountId());
            msg.append("): ");
            msg.append(badStream.getCause().getMessage());
            log.info(msg.toString());
            throw new UnloggedFailure(128, "error: " + badStream.getCause().getMessage());
        }

        // This may have been triggered by branch level access controls.
        // Log what the heck is going on, as detailed as we can.
        //
        StringBuilder msg = new StringBuilder();
        msg.append("Unpack error on project \"").append(projectControl.getProject().getName()).append("\":\n");

        msg.append("  AdvertiseRefsHook: ").append(rp.getAdvertiseRefsHook());
        if (rp.getAdvertiseRefsHook() == AdvertiseRefsHook.DEFAULT) {
            msg.append("DEFAULT");
        } else if (rp.getAdvertiseRefsHook() instanceof VisibleRefFilter) {
            msg.append("VisibleRefFilter");
        } else {
            msg.append(rp.getAdvertiseRefsHook().getClass());
        }
        msg.append("\n");

        if (rp.getAdvertiseRefsHook() instanceof VisibleRefFilter) {
            Map<String, Ref> adv = rp.getAdvertisedRefs();
            msg.append("  Visible references (").append(adv.size()).append("):\n");
            for (Ref ref : adv.values()) {
                msg.append("  - ").append(ref.getObjectId().abbreviate(8).name()).append(" ")
                        .append(ref.getName()).append("\n");
            }

            Map<String, Ref> allRefs = rp.getRepository().getRefDatabase().getRefs(RefDatabase.ALL);
            List<Ref> hidden = new ArrayList<>();
            for (Ref ref : allRefs.values()) {
                if (!adv.containsKey(ref.getName())) {
                    hidden.add(ref);
                }
            }

            msg.append("  Hidden references (").append(hidden.size()).append("):\n");
            for (Ref ref : hidden) {
                msg.append("  - ").append(ref.getObjectId().abbreviate(8).name()).append(" ")
                        .append(ref.getName()).append("\n");
            }
        }

        IOException detail = new IOException(msg.toString(), badStream);
        throw new Failure(128, "fatal: Unpack error, check server log", detail);
    }
}

From source file:com.sonatype.sshjgit.core.gitcommand.Receive.java

License:Apache License

@Override
protected void runImpl() throws IOException, Failure {
    final Subject subject = SecurityUtils.getSubject();
    subject.checkPermission("gitrepo:push:" + getRepoNameAsPermissionParts(repo));
    ReceivePack rp = new ReceivePack(repo);
    rp.setAllowCreates(true);//w w  w .j  a  v a 2s.c o  m
    final boolean mayNonFastForward = subject
            .isPermitted("gitrepo:non-fast-forward:" + getRepoNameAsPermissionParts(repo));
    rp.setAllowDeletes(mayNonFastForward);
    rp.setAllowNonFastForwards(mayNonFastForward);
    rp.setCheckReceivedObjects(true);
    // TODO make this be a real email address!
    final String name;
    final Object principal = subject.getPrincipal();
    if (principal == null) {
        name = "null_principal";
        log.warn("principal was null when trying to setRefLogIdent on repo.");
    } else {
        name = principal.toString();
    }
    log.info("setting LogIdent to " + name);
    rp.setRefLogIdent(new PersonIdent(name, name + "@example.com"));
    rp.receive(in, out, err);
}

From source file:com.tasktop.c2c.server.scm.web.GitHandler.java

License:Open Source License

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final boolean containerSupportsChunkedIO = computeContainerSupportsChunkedIO();

    String pathInfo = request.getPathInfo();
    log.info("Git request: " + request.getMethod() + " " + request.getRequestURI() + " " + pathInfo);

    Repository repository = null;/*from  w  ww .  j  a v  a  2  s  .c o  m*/
    try {
        // only work on Git requests
        Matcher matcher = pathInfo == null ? null : GIT_COMMAND_PATTERN.matcher(pathInfo);
        if (matcher == null || !matcher.matches()) {
            log.info("Unexpected path: " + pathInfo);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        String requestCommand = matcher.group(1);
        String requestPath = matcher.group(2);

        // sanity check on path, disallow path separator components
        if (requestPath == null || requestPath.contains("/") || requestPath.contains("..")) {
            badPathResponse();
        }

        repository = repositoryResolver.open(request, requestPath);

        InputStream requestInput = request.getInputStream();
        if (!containerSupportsChunkedIO) {
            requestInput = new ChunkedInputStream(requestInput);
        }

        MultiplexingOutputStream mox = createMultiplexingOutputStream(response, containerSupportsChunkedIO);
        // indicate that we're ok to handle the request
        // note that following this there will be a two-way communication with the process
        // that might still encounter errors. That's ok.
        startOkResponse(response, containerSupportsChunkedIO);

        // identify the git command
        GitCommand command = GitCommand.fromCommandName(requestCommand);
        if (command != null) {
            // permissions check
            if (!Security.hasOneOfRoles(command.getRoles())) {
                log.info("Access denied to " + Security.getCurrentUser() + " for " + command.getCommandName()
                        + " on " + TenancyUtil.getCurrentTenantProjectIdentifer() + " " + requestPath);
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            switch (command) {
            case RECEIVE_PACK:
                ReceivePack rp = new ReceivePack(repository);
                rp.setPostReceiveHook(postReceiveHook);
                rp.receive(requestInput, mox.stream(PacketType.STDOUT), mox.stream(PacketType.STDERR));
                break;
            case UPLOAD_PACK:
                UploadPack up = new UploadPack(repository);
                up.upload(requestInput, mox.stream(PacketType.STDOUT), mox.stream(PacketType.STDERR));
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        }

        // at this stage we're done with IO
        // send the exit value and closing chunk
        try {
            int exitValue = 0;

            if (exitValue != 0) {
                log.info("Exit value: " + exitValue);
            }
            mox.writeExitCode(exitValue);
            mox.close();
        } catch (IOException e) {
            // ignore
            log.debug("Cannot complete writing exit state", e);
        }

        // clear interrupt status
        Thread.interrupted();

    } catch (ErrorResponseException e) {
        createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage());
    } catch (ServiceNotAuthorizedException e) {
        createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage());
    } catch (ServiceNotEnabledException e) {
        createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage());
    } finally {
        log.info("Git request complete");
        if (repository != null) {
            repository.close();
        }
    }
}

From source file:net.antoniy.gidder.beta.ssh.Receive.java

License:Apache License

@Override
protected void runImpl() throws IOException {
    if (!hasPermission()) {
        err.write(MSG_REPOSITORY_PERMISSIONS.getBytes());
        err.flush();//from  w  w w.  j av a 2s  .  c  om
        onExit(CODE_ERROR, MSG_REPOSITORY_PERMISSIONS);
        return;
    }

    //      Config config = new Config();
    //      int timeout = Integer.parseInt(config.getString("transfer", null, "timeout"));
    int timeout = 10;

    //      PackConfig packConfig = new PackConfig();
    //       packConfig.setDeltaCompress(false);
    //       packConfig.setThreads(1);
    //       packConfig.fromConfig(config);

    final ReceivePack rp = new ReceivePack(repo);
    rp.setTimeout(timeout);
    rp.receive(in, out, err);
}

From source file:org.webcat.core.git.http.ReceivePackRequestHandler.java

License:Open Source License

/**
 * Handles the request and generates the ReceivePack response.
 *
 * @param request the request/*from  w  w  w . j a  v a  2  s  . c o m*/
 * @param response the response
 * @throws Exception if an error occurs
 */
public void handleRequest(WORequest request, WOResponse response) throws Exception {
    String contentType = request.headerForKey(HttpSupport.HDR_CONTENT_TYPE);

    if (RECEIVE_PACK_REQUEST_TYPE.equals(contentType)) {
        final Repository repo = RepositoryRequestUtils.repositoryFromRequest(request);

        ReceivePack rp = new ReceivePack(repo);
        rp.setBiDirectionalPipe(false);
        rp.setPostReceiveHook(new PostReceiveHook() {
            public void onPostReceive(ReceivePack pack, Collection<ReceiveCommand> commands) {
                // Once the pack is received, force a pull of the working
                // copy so that anyone using Web-DAV will get synched.
                GitUtilities.workingCopyForRepository(repo, true);
            }
        });

        response.setHeader(RECEIVE_PACK_RESULT_TYPE, HttpSupport.HDR_CONTENT_TYPE);

        InputStream input = RequestUtils.inputStreamForRequest(request);
        SmartGZIPOutputStream output = new SmartGZIPOutputStream(request, response);

        rp.receive(input, output, null);

        output.close();
    } else {
        response.setStatus(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE);
    }
}

From source file:playRepository.RepositoryService.java

License:Apache License

private static void receivePack(final InputStream input, Repository repository, final OutputStream output,
        final PreReceiveHook preReceiveHook, final PostReceiveHook postReceiveHook) {
    final ReceivePack receivePack = new ReceivePack(repository);
    receivePack.setBiDirectionalPipe(false);
    new Thread() {
        @Override// w  ww .  jav  a  2s. c o m
        public void run() {
            try {
                receivePack.setPreReceiveHook(preReceiveHook);
                receivePack.setPostReceiveHook(postReceiveHook);
                receivePack.receive(input, output, null);
            } catch (IOException e) {
                Logger.error("receivePack failed", e);
            }

            closeStreams("receivePack", input, output);
        }
    }.start();
}