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

/**
 * This test should deal with the scenario where a document is being uploaded which already has a file with the same
 * name in the target directory. Alfresco identifies this and creates the new file with '-<one_up_number>' appended
 * to the file name prior to the file extension. Quite a bit of JSON will need to be inserted into the response to
 * allow this test to be exercised.// w w w . j  av a2 s  . c o  m
 */
@Test
public void testFlashNameClashChangedByAlfresco() {

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

        // Setup the response object.
        JSONObject response = new JSONObject();
        response.put(AlfrescoJSONKeys.NODEREF, TEST_FILENODEREF_STRING);
        response.put("fileName", incrementedTestFilename);
        JSONObject status = new JSONObject();
        status.put("code", HttpServletResponse.SC_OK);
        status.put("name", "OK");
        status.put("description", "File uploaded successfully");
        response.put("status", status);

        mockResponse = new MockHttpServletResponse();

        mockChain = new ResponseModifiableMockFilterChain(response.toString(), HttpServletResponse.SC_CONFLICT);

        springAuditFilterBean.doFilter(mockRequest, mockResponse, mockChain);

        Auditable audited = getSingleAuditedEvent();

        assertEquals(incrementedTestFilename, audited.getSource());

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

From source file:uk.ac.horizon.ug.locationbasedgame.author.CRUDServlet.java

/** Create on POST.
 * E.g. curl -d '{...}' http://localhost:8888/author/configuration/
 * @param req/* ww w.  j  ava 2  s . c  om*/
 * @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);
        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:org.xwiki.platform.patchservice.web.PatchServiceAction.java

protected void processPatch(XWikiRequest request, XWikiResponse response, PatchservicePlugin plugin,
        XWikiContext context) throws Exception {
    if (StringUtils.isEmpty(request.getParameter("patch_id"))) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().print("The request must contain a patch_id parameter.");
        return;/*  w ww  .j  a  va 2s.  c  o  m*/
    }
    if (StringUtils.isEmpty(request.getParameter("patch"))) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().print("The request must contain a patch parameter.");
        return;
    }
    PatchId id = new PatchIdImpl();
    try {
        id.fromXml(parseString(request.getParameter("patch_id")).getDocumentElement());
    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().print("Invalid patch_id parameter: " + ex.getMessage());
        return;
    }
    Patch p = new PatchImpl();
    try {
        p.fromXml(parseString(request.getParameter("patch")).getDocumentElement());
    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().print("Invalid patch parameter: " + ex.getMessage());
        return;
    }
    try {
        if (plugin.getDocumentUpdatesFrom(id).size() > 1) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
            response.getWriter().print("needs update");
            return;
        } else {
            try {
                plugin.applyPatch(p, id, context);
                plugin.logPatch(p);
                response.getWriter().print("OK");
            } catch (Exception ex) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().print("Failed to apply patch: " + ex.getMessage());
            }
        }
    } catch (IOException ex) {
        LOG.warn("Failed to send response");
    }
}

From source file:org.gss_project.gss.server.rest.GroupsHandler.java

/**
 * Handle POST requests in the groups namespace.
 *
  * @param req The servlet request we are processing
  * @param resp The servlet response we are processing
  * @throws IOException if an input/output error occurs
 *///from  w  w  w .j a va 2 s. com
void postGroup(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Identify the requested resource path
    String path = getInnerPath(req, PATH_GROUPS);
    if (path.equals(""))
        path = "/";

    try {
        User user = getUser(req);
        final User owner = getOwner(req);
        if (!owner.equals(user))
            throw new InsufficientPermissionsException("User " + user.getUsername()
                    + " does not have permission to modify the groups owned by " + owner.getUsername());
        if (path.equals("/")) {
            // Request to add group
            final String group = req.getParameter(GROUP_PARAMETER);
            if (!isValidResourceName(group)) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            if (logger.isDebugEnabled())
                logger.debug("Adding group " + group);
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().createGroup(owner.getId(), group);
                    return null;
                }
            });
            resp.setStatus(HttpServletResponse.SC_CREATED);
        } else {
            // Request to add group member
            String username = req.getParameter(USERNAME_PARAMETER);
            if (!isValidResourceName(username)) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            // Chop any trailing slash
            path = path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
            // Chop any leading slash
            path = path.startsWith("/") ? path.substring(1) : path;
            if (logger.isDebugEnabled())
                logger.debug("Adding member " + username + " to group " + path);
            final Group group = getService().getGroup(owner.getId(), URLDecoder.decode(path, "UTF-8"));
            final User member = getService().findUser(username);
            if (member == null) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "User " + username + " not found");
                return;
            }
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().addUserToGroup(owner.getId(), group.getId(), member.getId());
                    return null;
                }
            });
            resp.setStatus(HttpServletResponse.SC_CREATED);
        }
        // Workaround for IE's broken caching behavior.
        resp.setHeader("Expires", "-1");
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (IllegalArgumentException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (DuplicateNameException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT, e.getMessage());
    } catch (RpcException e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, e.getMessage());
    } catch (Exception e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

}

From source file:org.eclipse.userstorage.tests.util.USSServer.java

protected void updateBlob(HttpServletRequest request, HttpServletResponse response, File blobFile,
        File etagFile, boolean exists) throws IOException {
    String ifMatch = getETag(request, "If-Match");

    if (exists) {
        String etag = IOUtil.readUTF(etagFile);

        if (StringUtil.isEmpty(ifMatch) || !ifMatch.equals(etag)) {
            response.setHeader("ETag", "\"" + etag + "\"");
            response.sendError(HttpServletResponse.SC_CONFLICT);
            return;
        }//from  w ww  .  j a  va 2  s  . c o  m
    }

    String etag = UUID.randomUUID().toString();

    IOUtil.mkdirs(blobFile.getParentFile());
    FileOutputStream out = new FileOutputStream(blobFile);
    InputStream body = null;

    try {
        Map<String, Object> requestObject = JSONUtil.parse(request.getInputStream(), "value");
        body = (InputStream) requestObject.get("value");

        IOUtil.copy(body, out);
    } finally {
        IOUtil.closeSilent(body);
        IOUtil.close(out);
    }

    IOUtil.writeUTF(etagFile, etag);

    response.setStatus(exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_CREATED);
    response.setHeader("ETag", "\"" + etag + "\"");
}

From source file:com.sun.faban.harness.webclient.Deployer.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from   w  ww .j  a  va  2  s .  c om
        List<String> deployNames = new ArrayList<String>();
        List<String> cantDeployNames = new ArrayList<String>();
        List<String> errDeployNames = new ArrayList<String>();
        List<String> invalidNames = new ArrayList<String>();
        List<String> errHeaders = new ArrayList<String>();
        List<String> errDetails = new ArrayList<String>();

        String user = null;
        String password = null;
        boolean clearConfig = false;
        boolean hasPermission = true;

        // Check whether we have to return text or html
        boolean acceptHtml = false;
        String acceptHeader = request.getHeader("Accept");
        if (acceptHeader != null && acceptHeader.indexOf("text/html") >= 0)
            acceptHtml = true;

        DiskFileUpload fu = new DiskFileUpload();
        // No maximum size
        fu.setSizeMax(-1);
        // maximum size that will be stored in memory
        fu.setSizeThreshold(4096);
        // the location for saving data that is larger than getSizeThreshold()
        fu.setRepositoryPath(Config.TMP_DIR);

        StringWriter messageBuffer = new StringWriter();
        PrintWriter messageWriter = new PrintWriter(messageBuffer);

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }
        // assume we know there are two files. The first file is a small
        // text file, the second is unknown and is written to a file on
        // the server
        for (Iterator i = fileItems.iterator(); i.hasNext();) {
            FileItem item = (FileItem) i.next();
            String fieldName = item.getFieldName();
            if (item.isFormField()) {
                if ("user".equals(fieldName)) {
                    user = item.getString();
                } else if ("password".equals(fieldName)) {
                    password = item.getString();
                } else if ("clearconfig".equals(fieldName)) {
                    String value = item.getString();
                    clearConfig = Boolean.parseBoolean(value);
                }
                continue;
            }

            if (!"jarfile".equals(fieldName))
                continue;

            String fileName = item.getName();

            if (fileName == null) // We don't process files without names
                continue;

            if (Config.SECURITY_ENABLED) {
                if (Config.DEPLOY_USER == null || Config.DEPLOY_USER.length() == 0
                        || !Config.DEPLOY_USER.equals(user)) {
                    hasPermission = false;
                    break;
                }
                if (Config.DEPLOY_PASSWORD == null || Config.DEPLOY_PASSWORD.length() == 0
                        || !Config.DEPLOY_PASSWORD.equals(password)) {
                    hasPermission = false;
                    break;
                }
            }
            // Now, this name may have a path attached, dependent on the
            // source browser. We need to cover all possible clients...

            char[] pathSeparators = { '/', '\\' };
            // Well, if there is another separator we did not account for,
            // just add it above.

            for (int j = 0; j < pathSeparators.length; j++) {
                int idx = fileName.lastIndexOf(pathSeparators[j]);
                if (idx != -1) {
                    fileName = fileName.substring(idx + 1);
                    break;
                }
            }

            // Ignore all non-jarfiles.
            if (!fileName.toLowerCase().endsWith(".jar")) {
                invalidNames.add(fileName);
                continue;
            }

            String deployName = fileName.substring(0, fileName.length() - 4);

            if (deployName.indexOf('.') > -1) {
                invalidNames.add(deployName);
                continue;
            }

            // Check if we can deploy benchmark or service.
            // If running or queued, we won't deploy benchmark.
            // If service being used by current run,we won't deploy service.
            if (!DeployUtil.canDeployBenchmark(deployName) || !DeployUtil.canDeployService(deployName)) {
                cantDeployNames.add(deployName);
                continue;
            }

            File uploadFile = new File(Config.BENCHMARK_DIR, fileName);
            if (uploadFile.exists())
                FileHelper.recursiveDelete(uploadFile);

            try {
                item.write(uploadFile);
            } catch (Exception e) {
                throw new ServletException(e);
            }

            try {
                DeployUtil.processUploadedJar(uploadFile, deployName);
            } catch (Exception e) {
                messageWriter.println("\nError deploying " + deployName + ".\n");
                e.printStackTrace(messageWriter);
                errDeployNames.add(deployName);
                continue;
            }
            deployNames.add(deployName);
        }

        if (clearConfig)
            for (String benchName : deployNames)
                DeployUtil.clearConfig(benchName);

        if (!hasPermission)
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        else if (cantDeployNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        else if (errDeployNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        else if (invalidNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        else if (deployNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_CREATED);
        else
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);

        StringBuilder b = new StringBuilder();

        if (deployNames.size() > 0) {
            if (deployNames.size() > 1)
                b.append("Benchmarks/services ");
            else
                b.append("Benchmark/service ");

            for (int i = 0; i < deployNames.size(); i++) {
                if (i > 0)
                    b.append(", ");
                b.append((String) deployNames.get(i));
            }

            b.append(" deployed.");
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (invalidNames.size() > 0) {
            if (invalidNames.size() > 1)
                b.append("Invalid deploy files ");
            else
                b.append("Invalid deploy file ");
            for (int i = 0; i < invalidNames.size(); i++) {
                if (i > 0)
                    b.append(", ");
                b.append((String) invalidNames.get(i));
            }
            b.append(". Deploy files must have .jar extension.");
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (cantDeployNames.size() > 0) {
            if (cantDeployNames.size() > 1)
                b.append("Cannot deploy benchmarks/services ");
            else
                b.append("Cannot deploy benchmark/services ");
            for (int i = 0; i < cantDeployNames.size(); i++) {
                if (i > 0)
                    b.append(", ");
                b.append((String) cantDeployNames.get(i));
            }
            b.append(". Benchmark/services being used or " + "queued up for run.");
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (errDeployNames.size() > 0) {
            if (errDeployNames.size() > 1) {
                b.append("Error deploying benchmarks/services ");
                for (int i = 0; i < errDeployNames.size(); i++) {
                    if (i > 0)
                        b.append(", ");
                    b.append((String) errDeployNames.get(i));
                }
            }

            errDetails.add(messageBuffer.toString());
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (!hasPermission)
            errHeaders.add("Permission denied!");

        Writer writer = response.getWriter();
        if (acceptHtml)
            writeHtml(request, writer, errHeaders, errDetails);
        else
            writeText(writer, errHeaders, errDetails);
        writer.flush();
        writer.close();
    } catch (ServletException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw new ServletException(e);
    }
}

From source file:com.rmn.qa.servlet.AutomationTestRunServlet.java

/**
 * Attempts to register a new run request with the server. Returns a 201 if the request can be fulfilled but AMIs
 * must be started Returns a 202 if the request can be fulfilled Returns a 400 if the required parameters are not
 * passed in. Returns a 409 if the server is at full node capacity
 *//*from  w  ww  . ja va 2s  .com*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");

    String browserRequested = request.getParameter("browser");
    String browserVersion = request.getParameter("browserVersion");
    String osRequested = request.getParameter("os");
    String threadCount = request.getParameter("threadCount");
    String uuid = request.getParameter(AutomationConstants.UUID);
    BrowserPlatformPair browserPlatformPairRequest;
    Platform requestedPlatform;

    // Return a 400 if any of the required parameters are not passed in
    // Check for uuid first as this is the most important variable
    if (uuid == null) {
        String msg = "Parameter 'uuid' must be passed in as a query string parameter";
        log.error(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }
    if (browserRequested == null) {
        String msg = "Parameter 'browser' must be passed in as a query string parameter";
        log.error(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }
    if (threadCount == null) {
        String msg = "Parameter 'threadCount' must be passed in as a query string parameter";
        log.error(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }
    if (StringUtils.isEmpty(osRequested)) {
        requestedPlatform = Platform.ANY;
    } else {
        requestedPlatform = AutomationUtils.getPlatformFromObject(osRequested);
        if (requestedPlatform == null) {
            String msg = "Parameter 'os' does not have a valid Selenium Platform equivalent: " + osRequested;
            log.error(msg);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
            return;
        }
    }

    Integer threadCountRequested = Integer.valueOf(threadCount);

    AutomationRunRequest runRequest = new AutomationRunRequest(uuid, threadCountRequested, browserRequested,
            browserVersion, requestedPlatform);
    browserPlatformPairRequest = new BrowserPlatformPair(browserRequested, requestedPlatform);

    log.info(String.format("Server request [%s] received.", runRequest));
    boolean amisNeeded;
    int amiThreadsToStart = 0;
    int currentlyAvailableNodes;
    // Synchronize this block until we've added the run to our context for other potential threads to see
    synchronized (AutomationTestRunServlet.class) {
        int remainingNodesAvailable = AutomationContext.getContext().getTotalThreadsAvailable(getProxySet());
        // If the number of nodes this grid hub can actually run is less than the number requested, this hub can not
        // fulfill this run at this time
        if (remainingNodesAvailable < runRequest.getThreadCount()) {
            log.error(String.format(
                    "Requested node count of [%d] could not be fulfilled due to hub limit. [%d] nodes available - Request UUID [%s]",
                    threadCountRequested, remainingNodesAvailable, uuid));
            response.sendError(HttpServletResponse.SC_CONFLICT,
                    "Server cannot fulfill request due to configured node limit being reached.");
            return;
        }
        // Get the number of matching, free nodes to determine if we need to start up AMIs or not
        currentlyAvailableNodes = requestMatcher.getNumFreeThreadsForParameters(getProxySet(), runRequest);
        // If the number of available nodes is less than the total number requested, we will have to spin up AMIs in
        // order to fulfill the request
        amisNeeded = currentlyAvailableNodes < threadCountRequested;
        if (amisNeeded) {
            // Get the difference which will be the number of additional nodes we need to spin up to supplement
            // existing nodes
            amiThreadsToStart = threadCountRequested - currentlyAvailableNodes;
        }
        // If the browser requested is not supported by AMIs, we need to not unnecessarily spin up AMIs
        if (amisNeeded && !AutomationUtils.browserAndPlatformSupported(browserPlatformPairRequest)) {
            response.sendError(HttpServletResponse.SC_GONE,
                    "Request cannot be fulfilled and browser and platform is not supported by AMIs");
            return;
        }
        // Add the run to our context so we can track it
        AutomationRunRequest newRunRequest = new AutomationRunRequest(uuid, threadCountRequested,
                browserRequested, browserVersion, requestedPlatform);
        boolean addSuccessful = AutomationContext.getContext().addRun(newRunRequest);
        if (!addSuccessful) {
            log.warn(String.format("Test run already exists for the same UUID [%s]", uuid));
            //                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Test run already exists with the same UUID.");
            response.setStatus(HttpServletResponse.SC_CREATED);
            return;
        }
    }
    if (amisNeeded) {
        // Start up AMIs as that will be required
        log.warn(String.format(
                "Insufficient nodes to fulfill request. New AMIs will be queued up. Requested [%s] - Available [%s] - Request UUID [%s]",
                threadCountRequested, currentlyAvailableNodes, uuid));
        try {
            AutomationTestRunServlet.startNodes(ec2, uuid, amiThreadsToStart, browserRequested,
                    requestedPlatform);
        } catch (NodesCouldNotBeStartedException e) {
            // Make sure and de-register the run if the AMI startup was not successful
            AutomationContext.getContext().deleteRun(uuid);
            String throwableMessage = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();
            String msg = "Nodes could not be started: " + throwableMessage;
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
            return;
        }
        // Return a 201 to let the caller know AMIs will be started
        response.setStatus(HttpServletResponse.SC_CREATED);
        return;
    } else {
        // Otherwise just return a 202 letting the caller know the requested resources are available
        response.setStatus(HttpServletResponse.SC_ACCEPTED);
        return;
    }
}

From source file:org.sakaiproject.access.tool.WebServlet.java

protected boolean writeFile(String name, String type, byte[] data, String dir, HttpServletRequest req,
        HttpServletResponse resp, boolean mkdir) {
    try {//from   w ww. j a v  a  2s.c o  m
        // validate filename. Need to be fairly careful.
        int i = name.lastIndexOf(Entity.SEPARATOR);
        if (i >= 0)
            name = name.substring(i + 1);
        if (name.length() < 1) {
            // System.out.println("no name left / removal");
            resp.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }

        // do our web thing with the path
        dir = preProcessPath(dir, req);

        // make sure there's a trailing separator
        if (!dir.endsWith(Entity.SEPARATOR))
            dir = dir + Entity.SEPARATOR;

        // get a reference to the content collection - this lets us use alias and short refs
        Reference ref = entityManager.newReference(dir);

        // the reference id replaces the dir - as a fully qualified path (no alias, no short ref)
        dir = ref.getId();

        String path = dir + name;

        ResourcePropertiesEdit resourceProperties = contentHostingService.newResourceProperties();

        // Try to delete the resource
        try {
            // System.out.println("Trying Del " + path);
            // The existing document may be a collection or a file.
            boolean isCollection = contentHostingService.getProperties(path)
                    .getBooleanProperty(ResourceProperties.PROP_IS_COLLECTION);

            if (isCollection) {
                // System.out.println("Can't del, iscoll");
                resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                return false;
            } else {
                // not sure why removeesource(path) didn't
                // work for my workspace
                ContentResourceEdit edit = contentHostingService.editResource(path);
                // if (edit != null)
                // System.out.println("Got edit");
                contentHostingService.removeResource(edit);
            }
        } catch (IdUnusedException e) {
            // Normal situation - nothing to do
        } catch (Exception e) {
            // System.out.println("Can't del, exception " + e.getClass() + ": " + e.getMessage());
            resp.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }

        // Add the resource

        try {
            User user = userDirectoryService.getCurrentUser();

            TimeBreakdown timeBreakdown = timeService.newTime().breakdownLocal();
            String mycopyright = "copyright (c)" + " " + timeBreakdown.getYear() + ", " + user.getDisplayName()
                    + ". All Rights Reserved. ";

            resourceProperties.addProperty(ResourceProperties.PROP_COPYRIGHT, mycopyright);

            resourceProperties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);

            // System.out.println("Trying Add " + path);
            ContentResource resource = contentHostingService.addResource(path, type, data, resourceProperties,
                    NotificationService.NOTI_NONE);

        } catch (InconsistentException e) {
            // get this error if containing dir doesn't exist
            if (mkdir) {
                try {
                    ContentCollection collection = contentHostingService.addCollection(dir, resourceProperties);
                    return writeFile(name, type, data, dir, req, resp, false);
                } catch (Throwable ee) {
                }
            }
            // System.out.println("Add fail, inconsistent");
            resp.sendError(HttpServletResponse.SC_CONFLICT);
            return false;
        } catch (IdUsedException e) {
            // Should not happen because we deleted above (unless tawo requests at same time)
            // System.out.println("Add fail, in use");
            M_log.warn("access post IdUsedException:" + e.getMessage());

            resp.sendError(HttpServletResponse.SC_CONFLICT);
            return false;
        } catch (Exception e) {
            // System.out.println("Add failed, exception " + e.getClass() + ": " + e.getMessage());
            resp.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
    } catch (IOException e) {
        // System.out.println("overall fail IOException " + e);
    }
    return true;
}

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

/**
 * Report workload to be executed on orchestrator for particular executor master.
 *
 * The order of items from orchestrator is preserved though not guaranteed to be exactly the same as the builds ware
 * scheduled on individual executor Jenkinses.
 *///w  w w  .  ja v a  2s  .c o  m
@RequirePOST
public void doReportWorkload(@Nonnull final StaplerRequest req, @Nonnull final StaplerResponse rsp)
        throws IOException {
    Jenkins.getActiveInstance().checkPermission(RestEndpoint.RESERVE);

    Pool pool = Pool.getInstance();
    final ConfigRepo.Snapshot config = pool.getConfig(); // Fail early when there is no config

    final ReportWorkloadRequest request = Entity.fromInputStream(req.getInputStream(),
            ReportWorkloadRequest.class);

    final List<ReportWorkloadRequest.Workload.WorkloadItem> reportedItems = request.getWorkload().getItems();
    final ArrayList<ReservationTask> reportedTasks = new ArrayList<>(reportedItems.size());
    final ExecutorJenkins executor;
    try {
        executor = config.getJenkinsByUrl(request.getExecutorUrl());
    } catch (NoSuchElementException ex) {
        rsp.setStatus(HttpServletResponse.SC_CONFLICT);
        rsp.getWriter().println(unknownExecutor(request.getExecutorUrl(), pool.getConfigRepoUrl()));
        return;
    }

    for (ReportWorkloadRequest.Workload.WorkloadItem item : reportedItems) {
        reportedTasks.add(new ReservationTask(executor, item.getLabel(), item.getName(), item.getId()));
    }

    Queue.withLock(new Runnable() {
        @Override
        public void run() {
            Queue queue = Jenkins.getActiveInstance().getQueue();
            for (Queue.Item item : queue.getItems()) {
                if (item.task instanceof ReservationTask
                        && ((ReservationTask) item.task).getOwner().equals(executor)) {
                    // Cancel items executor is no longer interested in and keep those it cares for
                    if (!reportedTasks.contains(item.task)) {
                        queue.cancel(item);
                    }
                    reportedTasks.remove(item.task);
                }
            }

            // These might have been reported just before the build started the execution on Executor so now the
            // ReservationTask might be executing or even completed on executor, though there is no way for orchestrator
            // to know. This situation will be handled by executor rejecting the `utilizeNode` call.
            for (ReservationTask newTask : reportedTasks) {
                queue.schedule2(newTask, 0);
            }
        }
    });

    String version = this.version;
    new ReportWorkloadResponse(pool.getConfigRepoUrl(), version).toOutputStream(rsp.getOutputStream());
}