Example usage for javax.servlet.http HttpServletResponse SC_CREATED

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

Introduction

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

Prototype

int SC_CREATED

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

Click Source Link

Document

Status code (201) indicating the request succeeded and created a new resource on the server.

Usage

From source file:org.nuxeo.ecm.core.opencmis.impl.CmisSuiteSession2.java

protected JsonNode checkOkContentStreamResponse(String contentMD5Hex, ObjectMapper mapper,
        CloseableHttpResponse response) throws IOException {
    String content;//from   ww  w  . j  av a 2 s. c o m
    try (InputStream is = response.getEntity().getContent()) {
        content = IOUtils.toString(is);
    }
    assertEquals(content, HttpServletResponse.SC_CREATED, response.getStatusLine().getStatusCode());
    JsonNode root = mapper.readTree(content);
    String expectedContentStreamHash = new ContentStreamHashImpl(ContentStreamHashImpl.ALGORITHM_MD5,
            contentMD5Hex).toString();
    Iterator iter = root.path("succinctProperties").path("cmis:contentStreamHash").getElements();
    boolean found = false;
    while (iter.hasNext()) {
        String hash = ((JsonNode) iter.next()).getTextValue();
        if (expectedContentStreamHash.equals(hash)) {
            found = true;
            break;
        }
    }
    assertTrue("cmis:contentStreamHash does not contain " + expectedContentStreamHash, found);
    return root;
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostServletImportTest.java

/**
 * SLING-2108 Test import operation which auto checks out versionable nodes.
 *//*w ww .  j a  va2 s.  c om*/
public void testImportAutoCheckoutNodes() throws IOException, JSONException {
    final String testPath = TEST_BASE_PATH;
    Map<String, String> props = new HashMap<String, String>();
    String testNode = testClient.createNode(HTTP_BASE_URL + testPath, props);
    urlsToDelete.add(testNode);

    //1. first create some content to update.
    props.clear();
    props.put(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_IMPORT);

    String testNodeName = "testNode_" + String.valueOf(random.nextInt());
    props.put(SlingPostConstants.RP_NODE_NAME_HINT, testNodeName);
    testFile = getTestFile(getClass().getResourceAsStream("/integration-test/servlets/post/testimport3.json"));
    props.put(SlingPostConstants.RP_CONTENT_TYPE, "json");
    props.put(SlingPostConstants.RP_REDIRECT_TO, SERVLET_CONTEXT + testPath + "/*");
    props.put(SlingPostConstants.RP_CHECKIN, "true");
    String importedNodeUrl = testClient.createNode(HTTP_BASE_URL + testPath, new NameValuePairList(props), null,
            true, testFile, SlingPostConstants.RP_CONTENT_FILE, null);

    // assert content at new location
    String content = getContent(importedNodeUrl + ".json", CONTENT_TYPE_JSON);

    JSONObject jsonObj = new JSONObject(content);
    assertNotNull(jsonObj);

    //assert that the versionable node is checked in.
    assertFalse(jsonObj.getBoolean("jcr:isCheckedOut"));

    //2. try an update with the :autoCheckout value set to false
    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_IMPORT));
    postParams.add(new NameValuePair(SlingPostConstants.RP_CONTENT_TYPE, "json"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_CHECKIN, "true"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_REPLACE_PROPERTIES, "true"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_AUTO_CHECKOUT, "false"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_CONTENT, "{ \"abc\": \"def2\" }"));
    assertPostStatus(importedNodeUrl, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, postParams,
            "Expected error from VersionException");

    //3. now try an update with the :autoCheckout value set to true
    postParams.clear();
    postParams.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_IMPORT));
    postParams.add(new NameValuePair(SlingPostConstants.RP_CONTENT_TYPE, "json"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_CHECKIN, "true"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_REPLACE_PROPERTIES, "true"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_AUTO_CHECKOUT, "true"));
    postParams.add(new NameValuePair(SlingPostConstants.RP_CONTENT, "{ \"abc\": \"def2\" }"));
    postParams.add(new NameValuePair(":http-equiv-accept", "application/json,*/*;q=0.9"));
    HttpMethod post = assertPostStatus(importedNodeUrl, HttpServletResponse.SC_CREATED, postParams,
            "Expected 201 status");

    String responseBodyAsString = post.getResponseBodyAsString();
    JSONObject responseJSON = new JSONObject(responseBodyAsString);
    JSONArray changes = responseJSON.getJSONArray("changes");
    JSONObject checkoutChange = changes.getJSONObject(0);
    assertEquals("checkout", checkoutChange.getString("type"));

    // assert content at new location
    String content2 = getContent(importedNodeUrl + ".json", CONTENT_TYPE_JSON);

    JSONObject jsonObj2 = new JSONObject(content2);
    assertNotNull(jsonObj2);

    //make sure it was really updated
    assertEquals("def2", jsonObj2.getString("abc"));

    //assert that the versionable node is checked back in.
    assertFalse(jsonObj.getBoolean("jcr:isCheckedOut"));
}

From source file:com.ecyrd.jspwiki.attachment.AttachmentServlet.java

/**
 *  {@inheritDoc}//from w  w  w  .j av a  2  s .co  m
 */
public void doPut(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false); // If something bad happened, Upload should be able to take care of most stuff

    String p = new String(req.getPathInfo().getBytes("ISO-8859-1"), "UTF-8");
    DavPath path = new DavPath(p);

    try {
        InputStream data = req.getInputStream();

        WikiContext context = m_engine.createContext(req, WikiContext.UPLOAD);

        String wikipage = path.get(0);

        errorPage = context.getURL(WikiContext.UPLOAD, wikipage);

        String changeNote = null; // FIXME: Does not quite work

        boolean created = executeUpload(context, data, path.getName(), errorPage, wikipage, changeNote,
                req.getContentLength());

        if (created)
            res.sendError(HttpServletResponse.SC_CREATED);
        else
            res.sendError(HttpServletResponse.SC_OK);
    } catch (ProviderException e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (RedirectException e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:org.opencastproject.adminui.endpoint.BlacklistEndpoint.java

@POST
@Path("")/*from   w  w  w  . j  a  v  a  2s  .  c  om*/
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "createblacklist", description = "Creates a blacklist", returnDescription = "The blacklist as JSON", restParameters = {
        @RestParameter(name = "type", description = "The blacklistable type", isRequired = true, type = RestParameter.Type.STRING),
        @RestParameter(name = "blacklistedId", description = "The id of the blacklistable element", isRequired = true, type = RestParameter.Type.INTEGER),
        @RestParameter(name = "start", description = "The start date", isRequired = true, type = RestParameter.Type.STRING),
        @RestParameter(name = "end", description = "The end date", isRequired = true, type = RestParameter.Type.STRING),
        @RestParameter(name = "purpose", description = "The purpose", isRequired = false, type = RestParameter.Type.STRING),
        @RestParameter(name = "comment", description = "The comment", isRequired = false, type = RestParameter.Type.STRING) }, reponses = {
                @RestResponse(description = "Returns the created blacklist as JSON", responseCode = HttpServletResponse.SC_CREATED),
                @RestResponse(description = "Unable to parse date, unknown type of blacklistable room or person, and if start time is after endpoint", responseCode = HttpServletResponse.SC_BAD_REQUEST),
                @RestResponse(description = "Blacklisted element not found", responseCode = HttpServletResponse.SC_NOT_FOUND) })
public Response createBlacklist(@FormParam("type") String type, @FormParam("blacklistedId") int blacklistedId,
        @FormParam("start") String start, @FormParam("end") String end, @FormParam("purpose") String purpose,
        @FormParam("comment") String comment) throws NotFoundException {
    long startTime;
    long endTime;
    try {
        startTime = DateTimeSupport.fromUTC(start);
    } catch (Exception e) {
        logger.warn("Unable to parse start date {}", start);
        return Response.status(Status.BAD_REQUEST).build();
    }
    try {
        endTime = DateTimeSupport.fromUTC(end);
    } catch (Exception e) {
        logger.warn("Unable to parse end date {}", end);
        return Response.status(Status.BAD_REQUEST).build();
    }

    if (startTime > endTime) {
        logger.warn("Start time {} was after end time {}", startTime, endTime);
        return Response.status(Status.BAD_REQUEST).build();
    }

    Blacklist blacklist = null;
    try {
        Blacklistable blacklistable;
        if (Room.TYPE.equals(type)) {
            blacklistable = participationPersistence.getRoom(blacklistedId);
        } else if (Person.TYPE.equals(type)) {
            blacklistable = participationPersistence.getPerson(blacklistedId);
        } else {
            logger.warn("Unknown type {}", type);
            return Response.status(Status.BAD_REQUEST).build();
        }

        List<Blacklist> blacklists = participationPersistence.findBlacklists(blacklistable);

        Period period = Period.period(new Date(startTime), new Date(endTime), purpose, comment);
        if (blacklists.isEmpty()) {
            List<Period> periods = new ArrayList<Period>();
            periods.add(period);
            blacklist = new Blacklist(blacklistable, periods);
        } else if (blacklists.size() == 1) {
            blacklist = blacklists.get(0);
            blacklist.addPeriod(period);
        } else {
            logger.warn(
                    "There was more than one blacklist returned using a single id and we can't handle that.");
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        }

        Blacklist createdBlacklist = participationPersistence.updateBlacklist(blacklist);
        Long createdPeriodId = null;
        for (Period p : createdBlacklist.getPeriods()) {
            if (p.getStart().equals(period.getStart()) && p.getEnd().equals(period.getEnd())) {
                createdPeriodId = p.getId().get();
                break;
            }
        }
        return Response.created(new URI(getBlacklistUrl(createdBlacklist.getId())))
                .entity(createdBlacklist.toJson(Option.some(createdPeriodId)).get(0).toJson()).build();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not create blacklist {}: {}", blacklist, e.getMessage());
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.eclipse.orion.server.useradmin.servlets.UserHandlerV1.java

private boolean handleUserCreate(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException, JSONException, CoreException {
    //      String store = req.getParameter(UserConstants.KEY_STORE);
    String uid = null;/*from   ww  w  .ja  v  a 2 s.  c  o m*/
    String login = req.getParameter(UserConstants.KEY_LOGIN);
    String name = req.getParameter(ProtocolConstants.KEY_NAME);
    String email = req.getParameter(UserConstants.KEY_EMAIL);
    String password = req.getParameter(UserConstants.KEY_PASSWORD);

    boolean isGuestUser = req.getParameter(UserConstants.KEY_GUEST) != null;
    boolean isPasswordRequired = requirePassword;
    boolean isEmailRequired = Boolean.TRUE.toString().equalsIgnoreCase(
            PreferenceHelper.getString(ServerConstants.CONFIG_AUTH_USER_CREATION_FORCE_EMAIL));

    IOrionCredentialsService userAdmin;
    if (isGuestUser) {
        if (!Boolean.TRUE.toString().equals(PreferenceHelper
                .getString(ServerConstants.CONFIG_AUTH_USER_CREATION_GUEST, Boolean.FALSE.toString()))) {
            return statusHandler.handleRequest(req, resp,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                            "Guest user creation is not allowed on this server.", null));
        }
        isPasswordRequired = false;
        isEmailRequired = false;
        userAdmin = getGuestUserAdmin();
        if (userAdmin == null) {
            return statusHandler.handleRequest(req, resp,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Cannot create guest users. Contact your server administrator.", null));
        }
        uid = login = nextGuestUserUid(userAdmin);
    } else {
        userAdmin = getUserAdmin();
    }

    if (name == null)
        name = login;

    String msg = validateLogin(login, isGuestUser);
    if (msg != null)
        return statusHandler.handleRequest(req, resp,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));

    if (isPasswordRequired && (password == null || password.length() == 0)) {
        return statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "Cannot create user with empty password.", null));
    }

    if (isEmailRequired && (email == null || email.length() == 0)) {
        return statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "User email is mandatory.", null));
    }

    if (userAdmin.getUser(UserConstants.KEY_LOGIN, login) != null)
        return statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "User " + login + " already exists.", null));
    if (email != null && email.length() > 0) {
        if (!email.contains("@")) //$NON-NLS-1$
            return statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR,
                    HttpServletResponse.SC_BAD_REQUEST, "Invalid user email.", null));
        if (userAdmin.getUser(UserConstants.KEY_EMAIL, email) != null)
            return statusHandler.handleRequest(req, resp,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                            NLS.bind("Email address already in use: {0}.", email), null));
    }

    //      if (isGuestUser) {
    //         // Before creating a new guest user, remove any excess guest accounts
    //         int maxGuestAccounts = Math.max(0, PreferenceHelper.getInt(ServerConstants.CONFIG_AUTH_USER_CREATION_GUEST_LIMIT, 100) - 1);
    //         deleteGuestAccounts(WebUser.getGuestAccountsToDelete(maxGuestAccounts));
    //      }

    User newUser;
    if (isGuestUser) {
        // Guest users get distinctive UIDs
        newUser = new User(uid, login, name, password);
    } else {
        newUser = new User(login, name, password);
    }
    if (email != null && email.length() > 0) {
        newUser.setEmail(email);
    }
    if (isEmailRequired)
        newUser.setBlocked(true);
    if (isGuestUser)
        newUser.addProperty(UserConstants.KEY_GUEST, Boolean.TRUE.toString());

    //persist new user in metadata store first
    UserInfo userInfo = new UserInfo();
    userInfo.setUserName(login);
    userInfo.setFullName(name);
    userInfo.setGuest(isGuestUser);
    OrionConfiguration.getMetaStore().createUser(userInfo);
    if (newUser.getUid() == null) {
        newUser.setUid(userInfo.getUniqueId());
    }

    newUser = userAdmin.createUser(newUser);

    if (newUser == null) {
        return statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, NLS.bind("Error creating user: {0}", login), null));
    }

    Logger logger = LoggerFactory.getLogger("org.eclipse.orion.server.account"); //$NON-NLS-1$
    //TODO Don't do cleanup as part of creation, it can be separate op (command line tool, etc)
    //      if (isGuestUser) {
    //         // Remove excess guest accounts
    //         int maxGuestAccounts = PreferenceHelper.getInt(ServerConstants.CONFIG_AUTH_USER_CREATION_GUEST_LIMIT, 100);
    //         deleteGuestAccounts(WebUser.getGuestAccountsToDelete(maxGuestAccounts));
    //      }

    if (logger.isInfoEnabled())
        logger.info("Account created: " + login); //$NON-NLS-1$ 

    try {
        //give the user access to their own user profile
        AuthorizationService.addUserRight(newUser.getUid(), newUser.getLocation());
    } catch (CoreException e) {
        return statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "User rights could not be added.", e));
    }

    URI userLocation = URIUtil.append(ServletResourceHandler.getURI(req), newUser.getUid());
    IOrionUserProfileNode userNode = getUserProfileService().getUserProfileNode(newUser.getUid(), true)
            .getUserProfileNode(IOrionUserProfileConstants.GENERAL_PROFILE_PART);

    if (newUser.getBlocked()) {
        try {
            UserEmailUtil.getUtil().sendEmailConfirmation(req, newUser);
            return statusHandler.handleRequest(req, resp,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_CREATED, NLS.bind(
                            "User {0} has been succesfully created. To log in please confirm your email first.",
                            login), null));
        } catch (URISyntaxException e) {
            LogHelper.log(e);
            return statusHandler.handleRequest(req, resp,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                            "Could not send confirmation email to " + newUser.getEmail(), null));
        }
    }
    OrionServlet.writeJSONResponse(req, resp, formJson(newUser, userNode, userLocation, req.getContextPath()));
    if (email != null && email.length() > 0 && UserEmailUtil.getUtil().isEmailConfigured()) {
        try {
            UserEmailUtil.getUtil().sendEmailConfirmation(req, newUser);
        } catch (URISyntaxException e) {
            LogHelper.log(e);
        }
    }

    return true;
}

From source file:com.couchbase.capi.servlet.CAPIServlet.java

protected void handleDocumentInternal(HttpServletRequest req, HttpServletResponse resp, String databaseName,
        String documentId, String documentType) throws IOException, ServletException {

    logger.trace(String.format("Got document request in database %s document %s type %s", databaseName,
            documentId, documentType));//from   w  w w .j a  v  a 2  s .  co  m

    if (!(req.getMethod().equals("GET") || req.getMethod().equals("HEAD") || req.getMethod().equals("PUT"))) {
        throw new UnsupportedOperationException(
                "Only GET/HEAD/PUT operations on documents are supported at this time");
    }

    if (req.getMethod().equals("GET") || req.getMethod().equals("HEAD")) {

        Map<String, Object> doc = null;
        if (documentType.equals("_local")) {
            doc = capiBehavior.getLocalDocument(databaseName, documentId);
        } else {
            doc = capiBehavior.getDocument(databaseName, documentId);
        }

        if (doc != null) {
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.setContentType("application/json");
            OutputStream os = resp.getOutputStream();
            mapper.writeValue(os, doc);
        } else {
            sendNotFoundResponse(resp, "missing");
            return;
        }

    } else if (req.getMethod().equals("PUT")) {

        String rev = null;

        //read the document
        InputStream is = req.getInputStream();

        int requestLength = req.getContentLength();
        byte[] buffer = new byte[requestLength];
        IOUtils.readFully(is, buffer, 0, requestLength);

        @SuppressWarnings("unchecked")
        Map<String, Object> parsedValue = (Map<String, Object>) mapper.readValue(buffer, Map.class);

        if (documentType.equals("_local)")) {
            rev = capiBehavior.storeLocalDocument(databaseName, documentId, parsedValue);
        } else {
            rev = capiBehavior.storeDocument(databaseName, documentId, parsedValue);
        }

        if (rev == null) {
            throw new ServletException("Storing document did not result in valid revision");
        }

        resp.setStatus(HttpServletResponse.SC_CREATED);
        resp.setContentType("application/json");
        OutputStream os = resp.getOutputStream();

        Map<String, Object> responseMap = new HashMap<String, Object>();
        responseMap.put("ok", true);
        responseMap.put("id", documentId);
        responseMap.put("rev", rev);
        mapper.writeValue(os, responseMap);
    }

}

From source file:com.ecyrd.jspwiki.attachment.SilverpeasAttachmentServlet.java

/**
 * {@inheritDoc}/*from  w  w w .  j  av a  2 s .co m*/
 */
public void doPut(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false); // If something bad
    // happened, Upload
    // should be able to
    // take care of most
    // stuff

    String p = new String(req.getPathInfo().getBytes("ISO-8859-1"), "UTF-8");
    DavPath path = new DavPath(p);

    try {
        InputStream data = req.getInputStream();

        WikiContext context = m_engine.createContext(req, WikiContext.UPLOAD);

        String wikipage = path.get(0);

        errorPage = context.getURL(WikiContext.UPLOAD, wikipage);

        String changeNote = null; // FIXME: Does not quite work

        boolean created = executeUpload(context, data, path.getName(), errorPage, wikipage, changeNote,
                req.getContentLength());

        if (created) {
            res.sendError(HttpServletResponse.SC_CREATED);
        } else {
            res.sendError(HttpServletResponse.SC_OK);
        }
    } catch (ProviderException e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (RedirectException e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:org.eclipse.orion.internal.server.servlets.workspace.WorkspaceResourceHandler.java

private ProjectInfo handleAddProject(HttpServletRequest request, HttpServletResponse response,
        WorkspaceInfo workspace, JSONObject data) throws IOException, ServletException {
    //make sure required fields are set
    JSONObject toAdd = data;/*w w  w .  j  a  v  a  2  s . com*/
    String id = toAdd.optString(ProtocolConstants.KEY_ID, null);
    String name = toAdd.optString(ProtocolConstants.KEY_NAME, null);
    if (name == null)
        name = request.getHeader(ProtocolConstants.HEADER_SLUG);
    if (!validateProjectName(workspace, name, request, response))
        return null;
    ProjectInfo project = new ProjectInfo();
    if (id != null)
        project.setUniqueId(id);
    project.setFullName(name);
    project.setWorkspaceId(workspace.getUniqueId());
    String content = toAdd.optString(ProtocolConstants.KEY_CONTENT_LOCATION, null);
    if (!isAllowedLinkDestination(content, request.getRemoteUser())) {
        String msg = NLS.bind(
                "Cannot link to server path {0}. Use the orion.file.allowedPaths property to specify server locations where content can be linked.",
                content);
        statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, msg, null));
        return null;
    }
    try {
        //project creation will assign unique project id
        getMetaStore().createProject(project);
    } catch (CoreException e) {
        String msg = "Error persisting project state";
        statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
        return null;
    }
    try {
        computeProjectLocation(request, project, content, getInit(toAdd));
        getMetaStore().updateProject(project);
    } catch (CoreException e) {
        boolean authFail = handleAuthFailure(request, response, e);

        //delete the project so we don't end up with a project in a bad location
        try {
            getMetaStore().deleteProject(workspace.getUniqueId(), project.getFullName());
        } catch (CoreException e1) {
            //swallow secondary error
            LogHelper.log(e1);
        }
        if (authFail) {
            return null;
        }
        //we are unable to write in the platform location!
        String msg = NLS.bind("Cannot create project: {0}", project.getFullName());
        statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
        return null;
    }
    //serialize the new project in the response

    //the baseLocation should be the workspace location
    URI baseLocation = getURI(request);
    JSONObject result = WebProjectResourceHandler.toJSON(workspace, project, baseLocation);
    OrionServlet.writeJSONResponse(request, response, result);

    //add project location to response header
    response.setHeader(ProtocolConstants.HEADER_LOCATION, result.optString(ProtocolConstants.KEY_LOCATION));
    response.setStatus(HttpServletResponse.SC_CREATED);

    return project;
}

From source file:org.osaf.cosmo.mc.MorseCodeServlet.java

/**
 * Handles publish requests.//from  w w w.j av  a  2s . c  o m
 */
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (log.isDebugEnabled())
        log.debug("handling PUT for " + req.getPathInfo());

    CollectionPath cp = CollectionPath.parse(req.getPathInfo());
    if (cp != null) {
        String parentUid = req.getParameter(PARAM_PARENT_UID);
        if (StringUtils.isEmpty(parentUid))
            parentUid = null;
        EimmlStreamReader reader = null;
        try {
            if (!checkWritePreconditions(req, resp))
                return;

            reader = new EimmlStreamReader(req.getReader());
            if (!reader.getCollectionUuid().equals(cp.getUid())) {

                String msg = "EIMML collection uid " + reader.getCollectionUuid()
                        + " does not match target collection uid " + cp.getUid();
                handleGeneralException(new BadRequestException(msg), resp);
                return;
            }

            EimmlStreamReaderIterator i = new EimmlStreamReaderIterator(reader);
            PubRecords records = new PubRecords(i, reader.getCollectionName(), reader.getCollectionHue());

            Set<TicketType> ticketTypes = null;
            try {
                ticketTypes = parseTicketTypes(req);
            } catch (IllegalArgumentException e) {
                handleGeneralException(new BadRequestException(e), resp);
                return;
            }

            PubCollection pubCollection = controller.publishCollection(cp.getUid(), parentUid, records,
                    ticketTypes);

            resp.setStatus(HttpServletResponse.SC_CREATED);
            resp.addHeader(HEADER_SYNC_TOKEN, pubCollection.getToken().serialize());
            for (Ticket ticket : pubCollection.getCollection().getTickets())
                resp.addHeader(HEADER_TICKET, formatTicket(ticket));

            return;
        } catch (CosmoSecurityException e) {
            if (e instanceof ItemSecurityException) {
                InsufficientPrivilegesException ipe = new InsufficientPrivilegesException(
                        (ItemSecurityException) e);
                handleGeneralException(ipe, resp);
            } else {
                resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
            }
            return;
        } catch (IllegalArgumentException e) {
            String msg = "Parent uid must be specified when authenticated principal is not a user";
            handleGeneralException(new BadRequestException(msg), resp);
            return;
        } catch (EimmlStreamException e) {
            Throwable cause = e.getCause();
            String msg = "Unable to read EIM stream: " + e.getMessage();
            msg += cause != null ? ": " + cause.getMessage() : "";
            handleGeneralException(new BadRequestException(msg, e), resp);
            return;
        } catch (UidInUseException e) {
            handleGeneralException(new MorseCodeException(HttpServletResponse.SC_CONFLICT, e), resp);
            return;
        } catch (ServerBusyException e) {
            log.debug("received ServerBusyException during PUT");
            resp.setIntHeader(HEADER_RETRY_AFTER, 5);
            resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "The server was busy, try again later");
            return;
        } catch (MorseCodeException e) {
            Throwable root = e.getCause();
            if (root != null && root instanceof EimmlStreamException) {
                String msg = "Unable to read EIM stream: " + root.getMessage();
                handleGeneralException(new BadRequestException(msg, e), resp);
                return;
            }
            if (root != null && root instanceof EimSchemaException) {
                String msg = "Unable to process EIM records: " + root.getMessage();
                handleGeneralException(new BadRequestException(msg, e), resp);
                return;
            }
            handleGeneralException(e, resp);
            return;
        } catch (RuntimeException e) {
            handleGeneralException(new MorseCodeException(e), resp);
            return;
        } finally {
            if (reader != null)
                reader.close();
        }
    }
    resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}

From source file:org.sakaiproject.sdata.tool.JCRHandler.java

@Override
public void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {// w w  w . j a v a 2 s .c o  m
        snoopRequest(request);

        ResourceDefinition rp = resourceDefinitionFactory.getSpec(request);
        String mimeType = ContentTypes.getContentType(rp.getRepositoryPath(), request.getContentType());
        String charEncoding = null;
        if (mimeType.startsWith("text")) {
            charEncoding = request.getCharacterEncoding();
        }
        Node n = jcrNodeFactory.getNode(rp.getRepositoryPath());
        boolean created = false;
        if (n == null) {
            n = jcrNodeFactory.createFile(rp.getRepositoryPath(), mimeType);
            created = true;
            if (n == null) {
                throw new RuntimeException(
                        "Failed to create node at " + rp.getRepositoryPath() + " type " + JCRConstants.NT_FILE);
            }
        } else {
            NodeType nt = n.getPrimaryNodeType();
            if (!JCRConstants.NT_FILE.equals(nt.getName())) {
                response.reset();
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Content Can only be put to a file, resource type is " + nt.getName());
                return;
            }
        }

        GregorianCalendar gc = new GregorianCalendar();
        long lastMod = request.getDateHeader(LAST_MODIFIED);
        if (lastMod > 0) {
            gc.setTimeInMillis(lastMod);
        } else {
            gc.setTime(new Date());
        }

        InputStream in = request.getInputStream();
        saveStream(n, in, mimeType, charEncoding, gc);

        in.close();
        if (created) {
            response.setStatus(HttpServletResponse.SC_CREATED);
        } else {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    } catch (UnauthorizedException ape) {
        // catch any Unauthorized exceptions and send a 401
        response.reset();
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ape.getMessage());
    } catch (PermissionDeniedException pde) {
        // catch any permission denied exceptions, and send a 403
        response.reset();
        response.sendError(HttpServletResponse.SC_FORBIDDEN, pde.getMessage());
    } catch (SDataException e) {
        sendError(request, response, e);
        LOG.error("Failed  To service Request " + e.getMessage());
    } catch (Exception e) {
        sendError(request, response, e);
        snoopRequest(request);
        LOG.error("Failed  TO service Request ", e);
    }
}