Example usage for javax.servlet.http HttpServletResponse SC_CONFLICT

List of usage examples for javax.servlet.http HttpServletResponse SC_CONFLICT

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_CONFLICT.

Prototype

int SC_CONFLICT

To view the source code for javax.servlet.http HttpServletResponse SC_CONFLICT.

Click Source Link

Document

Status code (409) indicating that the request could not be completed due to a conflict with the current state of the resource.

Usage

From source file:com.surevine.alfresco.audit.integration.UploadDocumentTest.java

/**
 * Under certain circumstances alfresco will not implement a name change. One instance is where the source of the
 * name clash is not visible to the user, this is the case where they don't have permissions. If this is the case
 * alfresco responds with a 409 (HttpServletResponse.SC_CONFLICT)
 *///  w ww .j  a va2 s. c o m
@Test
public void testNameClashNotChangedByALfresco() {

    try {
        // Setup the request object.
        mockRequest.setContentType("multipart/form-data; boundary=" + MIME_BOUNDARY_PARAMETER);
        String mimeContent = formatMimeType(nonFlashBasedUploadData, TEST_FILE, MIME_BOUNDARY);
        mockRequest.setContent(mimeContent.getBytes());
        mockRequest.setRequestURI("/alfresco/s/api/upload");

        // Setup the response object.
        mockResponse = new MockHttpServletResponse();

        // There is no content to the response so only an empty string is required
        mockChain = new ResponseModifiableMockFilterChain("{}", HttpServletResponse.SC_CONFLICT);

        springAuditFilterBean.doFilter(mockRequest, mockResponse, mockChain);

        Auditable audited = getSingleAuditedEvent();

        assertFalse(audited.isSuccess());

    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }

}

From source file:eu.dasish.annotation.backend.rest.PrincipalResource.java

/**
 * //from   w ww.ja v a2s  . co  m
 * @param name the name of the principal to be registered as a basic-authentication user.
 * @param remoteId the  remote id of the principal to be registered.
 * @param password the password selected by the principal to be registered.
 * @param email the email of the principal to be registered.
 * @return a {@link Principal} element representing the just registered principal.
 * @throws IOException if sending an error fails.
 */
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_XML)
@Path("register/nonshibboleth")
public JAXBElement<Principal> registerNonShibbolizedPrincipal(@FormParam("name") String name,
        @FormParam("remoteId") String remoteId, @FormParam("password") String password,
        @FormParam("email") String email) throws IOException {
    Principal newPrincipal = new Principal();
    newPrincipal.setDisplayName(name);
    newPrincipal.setEMail(email);

    Map params = new HashMap<String, Object>();
    params.put("remoteId", remoteId);
    params.put("password", password);
    params.put("shaStrength", shaStrength);
    params.put("newPrincipal", newPrincipal);

    dbDispatcher.setResourcesPaths(this.getRelativeServiceURI());
    try {
        return (new RequestWrappers(this)).wrapAddPrincipalRequest(params,
                new RegisterNonShibbolizedPrincipal());
    } catch (NotInDataBaseException e1) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage());
        return new ObjectFactory().createPrincipal(new Principal());
    } catch (PrincipalExists e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_CONFLICT, e2.getMessage());
        return new ObjectFactory().createPrincipal(new Principal());
    }
}

From source file:edu.stanford.epad.epadws.xnat.XNATCreationOperations.java

public static int createXNATDICOMStudyExperiment(String xnatProjectLabel, String xnatSubjectLabel,
        String studyUID, String jsessionID) {
    String xnatStudyURL = XNATUtil.buildXNATDICOMStudyCreationURL(xnatProjectLabel, xnatSubjectLabel, studyUID);
    HttpClient client = new HttpClient();
    PutMethod putMethod = new PutMethod(xnatStudyURL);
    int xnatStatusCode;

    putMethod.setRequestHeader("Cookie", "JSESSIONID=" + jsessionID);

    try {//from  ww  w  . j a  v a 2 s .  co  m
        log.info("Creating study " + studyUID + " for patient " + xnatSubjectLabel + " in project "
                + xnatProjectLabel + " in XNAT");
        xnatStatusCode = client.executeMethod(putMethod);
        if (XNATUtil.unexpectedXNATCreationStatusCode(xnatStatusCode))
            log.warning("Failure calling XNAT with URL " + xnatStudyURL + "; status code = " + xnatStatusCode);
        else
            eventTracker.recordStudyEvent(jsessionID, xnatProjectLabel, xnatSubjectLabel, studyUID);
    } catch (IOException e) {
        log.warning("Error calling XNAT with URL " + xnatStudyURL, e);
        xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    } finally {
        putMethod.releaseConnection();
    }

    if (xnatStatusCode == HttpServletResponse.SC_CONFLICT)
        xnatStatusCode = HttpServletResponse.SC_OK;

    return xnatStatusCode;
}

From source file:org.sakaiproject.nakamura.user.servlet.CreateSakaiGroupServlet.java

@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings(justification = "If there is an exception, the user is certainly not admin", value = {
        "REC_CATCH_EXCEPTION" })

protected void handleOperation(SlingHttpServletRequest request, HtmlResponse response,
        List<Modification> changes) throws RepositoryException {

    // KERN-432 dont allow anon users to access create group.
    if (SecurityConstants.ANONYMOUS_ID.equals(request.getRemoteUser())) {
        response.setStatus(403, "AccessDenied");
        return;//from   w w w  . j  av a 2 s  .c  om
    }

    // check that the submitted parameter values have valid values.
    final String principalName = request.getParameter(SlingPostConstants.RP_NODE_NAME);
    if (principalName == null) {
        throw new RepositoryException("Group name was not submitted");
    }

    NameSanitizer san = new NameSanitizer(principalName, false);
    san.validate();

    // check for allow create Group
    boolean allowCreateGroup = false;
    User currentUser = null;

    try {
        Session currentSession = request.getResourceResolver().adaptTo(Session.class);
        UserManager um = AccessControlUtil.getUserManager(currentSession);
        currentUser = (User) um.getAuthorizable(currentSession.getUserID());
        if (currentUser.isAdmin()) {
            LOGGER.debug("User is an admin ");
            allowCreateGroup = true;
        } else {
            LOGGER.debug("Checking for membership of one of {} ", Arrays.toString(authorizedGroups));
            PrincipalManager principalManager = AccessControlUtil.getPrincipalManager(currentSession);
            PrincipalIterator pi = principalManager
                    .getGroupMembership(principalManager.getPrincipal(currentSession.getUserID()));
            Set<String> groups = new HashSet<String>();
            for (; pi.hasNext();) {
                groups.add(pi.nextPrincipal().getName());
            }

            for (String groupName : authorizedGroups) {
                if (groups.contains(groupName)) {
                    allowCreateGroup = true;
                    break;
                }

                // TODO: move this nasty hack into the PrincipalManager dynamic groups need to
                // be in the principal manager for this to work.
                if ("authenticated".equals(groupName)
                        && !SecurityConstants.ADMIN_ID.equals(currentUser.getID())) {
                    allowCreateGroup = true;
                    break;
                }

                // just check via the user manager for dynamic resolution.
                Group group = (Group) um.getAuthorizable(groupName);
                LOGGER.debug("Checking for group  {} {} ", groupName, group);
                if (group != null && group.isMember(currentUser)) {
                    allowCreateGroup = true;
                    LOGGER.debug("User is a member  of {} {} ", groupName, group);
                    break;
                }
            }
        }
    } catch (Exception ex) {
        LOGGER.warn("Failed to determin if the user is an admin, assuming not. Cause: " + ex.getMessage());
        allowCreateGroup = false;
    }

    if (!allowCreateGroup) {
        LOGGER.debug("User is not allowed to create groups ");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN, "User is not allowed to create groups");
        return;
    }

    Session session = getSession();

    try {
        UserManager userManager = AccessControlUtil.getUserManager(session);
        Authorizable authorizable = userManager.getAuthorizable(principalName);

        if (authorizable != null) {
            // principal already exists!
            response.setStatus(400, "A principal already exists with the requested name: " + principalName);
            return;
        } else {
            Group group = userManager.createGroup(new Principal() {
                public String getName() {
                    return principalName;
                }
            });
            String groupPath = AuthorizableResourceProvider.SYSTEM_USER_MANAGER_GROUP_PREFIX + group.getID();
            Map<String, RequestProperty> reqProperties = collectContent(request, response, groupPath);

            response.setPath(groupPath);
            response.setLocation(externalizePath(request, groupPath));
            response.setParentLocation(
                    externalizePath(request, AuthorizableResourceProvider.SYSTEM_USER_MANAGER_GROUP_PATH));
            changes.add(Modification.onCreated(groupPath));

            // It is not allowed to touch the rep:group-managers property directly.
            String key = SYSTEM_USER_MANAGER_GROUP_PREFIX + principalName + "/";
            reqProperties.remove(key + PROP_GROUP_MANAGERS);
            reqProperties.remove(key + PROP_GROUP_VIEWERS);

            // write content from form
            writeContent(session, group, reqProperties, changes);

            // update the group memberships, although this uses session from the request, it
            // only
            // does so for finding authorizables, so its ok that we are using an admin session
            // here.
            updateGroupMembership(request, group, changes);
            // TODO We should probably let the client decide whether the
            // current user belongs in the managers list or not.
            updateOwnership(request, group, new String[] { currentUser.getID() }, changes);

            try {
                postProcessorService.process(group, session, ModificationType.CREATE, request);
            } catch (RepositoryException e) {
                LOGGER.info("Failed to create Group  {}", e.getMessage());
                response.setStatus(HttpServletResponse.SC_CONFLICT, e.getMessage());
                return;
            } catch (Exception e) {
                LOGGER.warn(e.getMessage(), e);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
                return;
            }

            // Launch an OSGi event for creating a group.
            try {
                Dictionary<String, String> properties = new Hashtable<String, String>();
                properties.put(UserConstants.EVENT_PROP_USERID, principalName);
                EventUtils.sendOsgiEvent(properties, UserConstants.TOPIC_GROUP_CREATED, eventAdmin);
            } catch (Exception e) {
                // Trap all exception so we don't disrupt the normal behaviour.
                LOGGER.error("Failed to launch an OSGi event for creating a user.", e);
            }
        }
    } catch (RepositoryException re) {
        LOGGER.info("Failed to create Group  {}", re.getMessage());
        LOGGER.debug("Failed to create Group Cause {}", re, re.getMessage());
        response.setStatus(HttpServletResponse.SC_CONFLICT, re.getMessage());
        return;
    } finally {
        ungetSession(session);
    }
}

From source file:org.sakaiproject.kernel.rest.friends.RestFriendsProvider.java

/**
 * @param params//from w w  w.  j  av  a  2 s  .  com
 * @param request
 * @param response
 * @return
 * @throws RepositoryException
 * @throws JCRNodeFactoryServiceException
 * @throws IOException
 */
private Map<String, Object> doRequestConnect(FriendsParams params, HttpServletRequest request,
        HttpServletResponse response) throws JCRNodeFactoryServiceException, RepositoryException, IOException {
    FriendsBean myFriends = friendsResolverService.resolve(params.uuid);
    FriendsBean friendFriends = friendsResolverService.resolve(params.friendUuid);
    if (myFriends.hasFriend(params.friendUuid) || friendFriends.hasFriend(params.uuid)) {
        throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT,
                "There is already a connection invited, pending or accepted ");
    }
    FriendBean friend = new FriendBean(params.uuid, params.friendUuid, FriendStatus.PENDING);
    FriendBean me = new FriendBean(params.friendUuid, params.uuid, FriendStatus.INVITED);
    if (!StringUtils.isEmpty(params.type)) {
        me.setProperties(ImmutableMap.of("type", params.type, "message", params.message));
        friend.setProperties(ImmutableMap.of("type", params.type, "message", params.message));
    }
    myFriends.addFriend(friend);
    friendFriends.addFriend(me);
    authzResolverService.setRequestGrant("Saving Request Connect");
    try {
        myFriends.save();
        friendFriends.save();
        jcrService.getSession().save();
    } finally {
        authzResolverService.clearRequestGrant();
    }
    return OK;
}

From source file:org.alfresco.repo.webdav.PutMethodTest.java

/**
 * Updating a file in an non-existent path
 *//*  ww  w . j  a va  2  s .com*/
@Test
public void testPutContentBadPath() throws Exception {
    String fileName = "file-" + GUID.generate();
    NodeRef fileNoderef = null;
    try {
        // Add non-existent path
        executeMethod(WebDAV.METHOD_PUT, "non/existent/path" + fileName, testDataFile, null);

        fail("The PUT execution should fail with a 400 error");
    } catch (WebDAVServerException wse) {
        // The execution failed and it is expected
        assertTrue(wse.getHttpStatusCode() == HttpServletResponse.SC_CONFLICT);
    } catch (Exception e) {
        fail("Failed to upload a file: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    } finally {
        if (fileNoderef != null) {
            nodeService.deleteNode(fileNoderef);
        }
    }
}

From source file:uk.ac.horizon.ug.mrcreator.http.CRUDServlet.java

/** Create on POST.
 * E.g. curl -d '{...}' http://localhost:8888/author/configuration/
 * @param req//from   w ww . j a v a  2  s.c o  m
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
private void doCreate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // TODO Auto-generated method stub
    try {
        Object o = parseObject(req);
        if (filterByCreator) {
            String creator = getRequestCreator(req);
            setCreator(o, creator);
        }
        Key key = validateCreate(o);
        // try adding
        EntityManager em = EMF.get().createEntityManager();
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            if (em.find(getObjectClass(), key) != null)
                throw new RequestException(HttpServletResponse.SC_CONFLICT,
                        "object already exists (" + key + ")");
            em.persist(o);
            et.commit();
            logger.info("Added " + o);
        } finally {
            if (et.isActive())
                et.rollback();
            em.close();
        }
        resp.setCharacterEncoding(ENCODING);
        resp.setContentType(JSON_MIME_TYPE);
        Writer w = new OutputStreamWriter(resp.getOutputStream(), ENCODING);
        JSONWriter jw = new JSONWriter(w);
        listObject(jw, o);
        w.close();
    } catch (RequestException e) {
        resp.sendError(e.getErrorCode(), e.getMessage());
    } catch (Exception e) {
        logger.log(Level.WARNING, "Getting object of type " + getObjectClass(), e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        return;
    }
}

From source file:fi.hoski.web.forms.RaceEntryServlet.java

/**
 * Handles the HTTP/*w w w.jav a 2  s . c om*/
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        String raceFleetKeyStr = request.getParameter("RaceFleetKey");
        if (raceFleetKeyStr == null) {
            throw new ServletException("no RaceFleetKey");
        }
        Key raceFleetKey = KeyFactory.stringToKey(raceFleetKeyStr);
        Entity raceFleetEntity = datastore.get(raceFleetKey);
        Key raceSeriesKey = raceFleetKey.getParent();
        Entity raceseriesEntity = datastore.get(raceSeriesKey);
        RaceSeries raceSeries = (RaceSeries) entities.newInstance(raceseriesEntity);
        RaceFleet raceFleet = (RaceFleet) entities.newInstance(raceFleetEntity);
        RaceEntry raceEntry = new RaceEntry(raceFleet);
        raceEntry.populate(request.getParameterMap());

        String fn = request.getParameter(RaceEntry.FIRSTNAME);
        String ln = request.getParameter(RaceEntry.LASTNAME);
        raceEntry.set(RaceEntry.HELMNAME, fn + " " + ln);

        String sa = request.getParameter(RaceEntry.STREETADDRESS);
        String zc = request.getParameter(RaceEntry.ZIPCODE);
        String ct = request.getParameter(RaceEntry.CITY);
        String cn = request.getParameter(RaceEntry.COUNTRY);
        if (cn == null || cn.isEmpty()) {
            raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct);
        } else {
            raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct + ", " + cn);
        }

        Day closingDay = (Day) raceSeries.get(RaceSeries.ClosingDate);
        Number fee = 0.0;
        if (closingDay != null) {
            Day now = new Day();
            if (closingDay.before(now)) {
                fee = (Number) raceFleet.get(RaceFleet.Fee2);
            } else {
                fee = (Number) raceFleet.get(RaceFleet.Fee);
            }
        }
        Boolean clubDiscount = (Boolean) raceSeries.get(RaceSeries.CLUBDISCOUNT);
        String clubname = repositoryBundle.getString("Clubname");
        if (clubDiscount != null && clubDiscount
                && clubname.equalsIgnoreCase("" + raceEntry.get(RaceEntry.CLUB))) {
            fee = new Double(0);
        }
        raceEntry.set(RaceEntry.FEE, fee);
        raceEntry.set(RaceEntry.TIMESTAMP, new Date());

        entities.put(raceEntry);

        String payingInstructions = "";
        String payingInstructionsHtml = "";
        BankingBarcode bb = races.getBarcode(raceEntry);
        if (bb != null) {
            Day dueDay = new Day(bb.getDueDate());
            String payingFormat = EntityReferences.encode(msg(Messages.RACEENTRYPAYING), "UTF-8");
            String bic = EntityReferences.encode(msg(Messages.RACEBIC), "UTF-8");
            payingInstructions = String.format(payingFormat, bb.toString(), // 1 = barcode
                    bb.getAccount().getIBAN(), // 2 = account
                    bb.getReference().toFormattedRFString(), // 3 = ref
                    dueDay, // 4 = due date
                    String.format("%.2f", bb.getTotal()), // 5 = total
                    bic // 6 = bic
            );
            payingInstructionsHtml = String.format(payingFormat.replace("\n", "<br>"),
                    "<span id='barcode'>" + bb.toString() + "</span>", // 1 = barcode
                    "<span id='iban'>" + bb.getAccount().getIBAN() + "</span>", // 2 = account
                    "<span id='rf'>" + bb.getReference().toFormattedRFString() + "</span>", // 3 = ref
                    "<span id='due'>" + dueDay + "</span>", // 4 = due date
                    "<span id='fee'>" + String.format("%.2f", bb.getTotal()) + "</span>", // 5 = total
                    "<span id='bic'>" + bic + "</span>" // 6 = bic
            );
        }
        URL base = new URL(request.getRequestURL().toString());
        URL barcodeUrl = new URL(base, "/races/code128.html?ancestor=" + raceEntry.createKeyString());
        String name = (String) raceEntry.get(RaceEntry.HELMNAME);
        String email = (String) raceEntry.get(RaceEntry.HELMEMAIL);
        String confirmation = msg(Messages.RACEENTRYCONFIRMATION);
        String plainMessage = "";
        String htmlMessage = "<html><head></head><body>" + EntityReferences.encode(confirmation)
                + payingInstructionsHtml + raceEntry.getFieldsAsHtmlTable() + "<iframe src="
                + barcodeUrl.toString() + "/>" + "</body></html>";
        if (email != null) {
            InternetAddress recipient = new InternetAddress(email, name);
            String senderStr = msg(Messages.RACEENTRYFROMADDRESS);
            InternetAddress sender;
            try {
                sender = new InternetAddress(senderStr);
                plainMessage = confirmation + "\n" + payingInstructions + "\n" + raceEntry.getFields();

                String subject = msg(Messages.RACEENTRYSUBJECT);
                mailService.sendMail(sender, subject, plainMessage, htmlMessage, recipient);
            } catch (Exception ex) {
                log(senderStr, ex);
            }
        }
        Cookie cookie = null;
        Cookie[] cookies = null;
        if (useCookies) {
            cookies = request.getCookies();
        }
        if (cookies != null) {
            for (Cookie ck : cookies) {
                if (COOKIENAME.equals(ck.getName())) {
                    cookie = ck;
                }
            }
        }
        JSONObject json = null;
        if (useCookies && cookie != null) {
            Base64 decoder = new Base64();
            String str = new String(decoder.decode(cookie.getValue()));
            json = new JSONObject(str);
        } else {
            json = new JSONObject();
        }
        for (Map.Entry<String, String[]> entry : ((Map<String, String[]>) request.getParameterMap())
                .entrySet()) {
            String property = entry.getKey();
            String[] values = entry.getValue();
            if (values.length == 1) {
                json.put(property, values[0]);
            }
        }
        Base64 encoder = new Base64();
        String base64 = encoder.encodeAsString(json.toString().getBytes("UTF-8"));
        if (useCookies) {
            if (cookie == null) {
                cookie = new Cookie(COOKIENAME, base64);
                cookie.setPath("/");
                cookie.setMaxAge(400 * 24 * 60 * 60);
            } else {
                cookie.setValue(base64);
            }
            response.addCookie(cookie);
        }
        sendError(response, HttpServletResponse.SC_OK,
                "<div id=\"" + raceEntry.createKeyString() + "\">Ok</div>");
    } catch (JSONException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "<div id=\"eJSON\">Internal error.</div>");
    } catch (EntityNotFoundException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "<div id=\"eEntityNotFound\">Internal error.</div>");
    } catch (NumberFormatException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eNumberFormat\">Number error.</div>");
    }
}

From source file:no.sesat.search.http.filters.SiteLocatorFilter.java

private static void doChainFilter(final FilterChain chain, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {

    final HttpSession session = request.getSession();

    // fetch the user's deque
    final Deque<ServletRequest> deque = getUsersDeque(session);

    // lock to execute
    final ReentrantLock lock = (ReentrantLock) session.getAttribute(USER_REQUEST_LOCK);

    // deque has a time limit. start counting.
    long timeLeft = WAIT_TIME;

    try {//from  w w  w  .ja v  a2s  .c  o  m
        // attempt to join deque
        if (deque.offerFirst(request)) {
            timeLeft = tryLock(request, deque, lock, timeLeft);
        }

        if (lock.isHeldByCurrentThread()) {

            // waiting is over. and we can execute
            chain.doFilter(request, response);

        } else {
            // we failed to execute. return 409 response.
            if (response instanceof HttpServletResponse) {

                LOG.warn(" -- response 409 "
                        + (0 < timeLeft ? "(More then " + REQUEST_QUEUE_SIZE + " requests already in queue)"
                                : "(Timeout: Waited " + WAIT_TIME + " ms)"));

                response.sendError(HttpServletResponse.SC_CONFLICT);
            }
        }
    } finally {

        // take out of deque first
        deque.remove(request);

        // release the lock, waiting up the next request
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}

From source file:com.redhat.jenkins.nodesharingbackend.Api.java

/**
 * Return node to orchestrator when no longer needed.
 *///  ww w  .  ja  va2  s.co  m
@RequirePOST
public void doReturnNode(@Nonnull final StaplerRequest req, @Nonnull final StaplerResponse rsp)
        throws IOException {
    Jenkins.getActiveInstance().checkPermission(RestEndpoint.RESERVE);

    String ocr = Pool.getInstance().getConfigRepoUrl(); // Fail early when there is no config
    ReturnNodeRequest request = Entity.fromInputStream(req.getInputStream(), ReturnNodeRequest.class);
    String ecr = request.getConfigRepoUrl();
    if (!Objects.equals(ocr, ecr)) { // TODO we do not require this anywhere else, should we?
        rsp.getWriter().println("Unable to return node - config repo mismatch " + ocr + " != " + ecr);
        rsp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    Jenkins jenkins = Jenkins.getActiveInstance();
    Computer c = jenkins.getComputer(request.getNodeName());
    if (c == null) {
        LOGGER.info("An attempt to return a node '" + request.getNodeName() + "' that does not exist by "
                + request.getExecutorUrl());
        rsp.getWriter().println("No shareable node named '" + request.getNodeName() + "' exists");
        rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (!(c instanceof ShareableComputer)) {
        LOGGER.warning("An attempt to return a node '" + request.getNodeName() + "' that is not reservable by "
                + request.getExecutorUrl());
        rsp.getWriter().println("No shareable node named '" + request.getNodeName() + "' exists");
        rsp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    ShareableComputer computer = (ShareableComputer) c;
    ReservationTask.ReservationExecutable executable = computer.getReservation();
    if (executable == null) {
        rsp.setStatus(HttpServletResponse.SC_OK);
        return;
    }

    String reservationOwnerUrl = executable.getParent().getOwner().getUrl().toExternalForm();
    if (!reservationOwnerUrl.equals(request.getExecutorUrl())) {
        rsp.getWriter().println("Executor '" + request.getExecutorUrl() + "' is not an owner of the host");
        rsp.setStatus(HttpServletResponse.SC_CONFLICT);
        return;
    }

    executable.complete();
    // TODO Report status
    rsp.setStatus(HttpServletResponse.SC_OK);
}