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.apache.wookie.controller.WidgetInstancesController.java

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

    // System.out.println("doGetWidget() in WidgetInstancesController");

    String userId = request.getParameter("userid"); //$NON-NLS-1$
    // System.out.println("userid="+userId);
    String sharedDataKey = getSharedDataKey(request);
    // System.out.println("sharedDataKey="+sharedDataKey);
    String serviceType = request.getParameter("servicetype"); //$NON-NLS-1$
    // System.out.println("serviceType="+serviceType);
    String widgetId = request.getParameter("widgetid"); //$NON-NLS-1$
    // System.out.println("widgetid="+widgetId);
    HttpSession session = request.getSession(true);
    Messages localizedMessages = LocaleHandler.localizeMessages(request);

    try {/*from  w ww  .  j a va  2  s .c  o  m*/
        if (userId == null || sharedDataKey == null || (serviceType == null && widgetId == null)) {
            throw new InvalidWidgetCallException();
        }
    } catch (InvalidWidgetCallException ex) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    checkProxy(request);

    // check if this API_KEY is allowed to instanciate this widget
    String apiKey = request.getParameter("api_key"); //$NON-NLS-1$      
    IPersistenceManager persistenceManager = PersistenceManagerFactory.getPersistenceManager();
    IWidget iw = persistenceManager.findWidgetByGuid(widgetId);
    Integer wid = new Integer(iw.getId().toString());
    IApiKey[] akey = persistenceManager.findByValue(IApiKey.class, "value", apiKey);
    int storeUserid = 0;
    int apikeyId = 0;
    if (akey != null && akey.length != 0) {
        storeUserid = akey[0].getUserId();
        apikeyId = new Integer(akey[0].getId().toString());
    }

    IApikeyWidget[] akeyWid = persistenceManager.findByValue(IApikeyWidget.class, "apiKey", apikeyId);
    boolean allowed = false;
    if (akeyWid != null && akeyWid.length != 0) {
        if (akeyWid[0].getWidgetId() == 0) {// 0 means access to ALL widgets
            allowed = true;
        } else {
            for (int j = 0; j < akeyWid.length; j++) {
                if (akeyWid[j].getWidgetId() == wid) {
                    allowed = true;
                    break;
                }
            }
        }
    }
    try {
        if (!allowed) {
            throw new InvalidWidgetCallException(
                    "Api_key:" + apiKey + " is not allowed to instanciate widget " + widgetId);
        }
    } catch (InvalidWidgetCallException ex) {
        System.out.println("WidgetInstancesController exception");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    System.out.println("before logging");
    // Log this request on db
    AccessLogImpl al = new AccessLogImpl(wid, storeUserid, apikeyId, userId);
    persistenceManager.save(al);

    //AccessLogImpl al = persistenceManager.newInstance(AccessLogImpl.class);
    //al.setWidgetId(wid);
    //al.setContainerUser(userId);
    //al.setApiKeyId(apikeyId);
    //al.setUserId(storeUserid);       
    //persistenceManager.save(al);

    System.out.println("after logging");

    IWidgetInstance instance = WidgetInstancesController.findWidgetInstance(request);
    String locale = request.getParameter("locale");//$NON-NLS-1$

    // Widget exists
    if (instance == null) {
        instance = WidgetInstanceFactory.getWidgetFactory(session, localizedMessages).newInstance(apiKey,
                userId, sharedDataKey, serviceType, widgetId, locale);
        response.setStatus(HttpServletResponse.SC_CREATED);
    } else {
        // If the requested locale is different to the saved locale, update
        // the "lang" attribute
        // of the widget instance and save it
        if ((locale == null && instance.getLang() != null) || (locale != null && instance.getLang() == null)
                || (locale != null && !instance.getLang().equals(locale))) {
            instance.setLang(locale);
            persistenceManager.save(instance);
        }
        response.setStatus(HttpServletResponse.SC_OK);
    }

    // Return the default widget if not created by now
    if (instance == null) {
        instance = WidgetInstanceFactory.defaultInstance(locale);
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }

    String url = getUrl(request, instance);
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    out.println(WidgetInstanceHelper.createXMLWidgetInstanceDocument(instance, url));
}

From source file:org.syncope.core.rest.controller.UserController.java

@PreAuthorize("hasRole('USER_CREATE')")
@RequestMapping(method = RequestMethod.POST, value = "/create")
public UserTO create(final HttpServletResponse response, @RequestBody final UserTO userTO)
        throws PropagationException, UnauthorizedRoleException, WorkflowException, NotFoundException {

    LOG.debug("User create called with {}", userTO);

    Set<Long> requestRoleIds = new HashSet<Long>(userTO.getMemberships().size());
    for (MembershipTO membership : userTO.getMemberships()) {
        requestRoleIds.add(membership.getRoleId());
    }//from  w w w .j a va  2s.  com
    Set<Long> adminRoleIds = EntitlementUtil.getRoleIds(EntitlementUtil.getOwnedEntitlementNames());
    requestRoleIds.removeAll(adminRoleIds);
    if (!requestRoleIds.isEmpty()) {
        throw new UnauthorizedRoleException(requestRoleIds);
    }

    WorkflowResult<Map.Entry<Long, Boolean>> created = wfAdapter.create(userTO);

    List<PropagationTask> tasks = propagationManager.getCreateTaskIds(created, userTO.getPassword(),
            userTO.getVirtualAttributes());

    final List<PropagationTO> propagations = new ArrayList<PropagationTO>();

    propagationManager.execute(tasks, new PropagationHandler() {

        @Override
        public void handle(final String resourceName, final PropagationTaskExecStatus executionStatus,
                final ConnectorObject before, final ConnectorObject after) {

            final PropagationTO propagation = new PropagationTO();
            propagation.setResourceName(resourceName);
            propagation.setStatus(executionStatus);

            if (before != null) {
                propagation.setBefore(connInstanceDataBinder.getConnObjectTO(before));
            }

            if (after != null) {
                propagation.setAfter(connInstanceDataBinder.getConnObjectTO(after));
            }

            propagations.add(propagation);
        }
    });

    notificationManager.createTasks(new WorkflowResult<Long>(created.getResult().getKey(),
            created.getPropByRes(), created.getPerformedTasks()));

    final UserTO savedTO = userDataBinder.getUserTO(created.getResult().getKey());

    savedTO.setPropagationTOs(propagations);

    LOG.debug("About to return created user\n{}", savedTO);

    response.setStatus(HttpServletResponse.SC_CREATED);
    return savedTO;
}

From source file:org.sakaiproject.nakamura.files.pool.CreateContentPoolServlet.java

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    String userId = request.getRemoteUser();

    RequestPathInfo rpi = request.getRequestPathInfo();
    String poolId = rpi.getExtension();
    String[] selectors = rpi.getSelectors();
    String alternativeStream = null;
    if (selectors != null && selectors.length > 0) {
        alternativeStream = poolId;//from  w w  w  .  j  ava  2s . com
        poolId = selectors[0];
    }
    javax.jcr.Session jcrSession = request.getResourceResolver().adaptTo(javax.jcr.Session.class);
    Session session;
    try {
        session = JackrabbitSparseUtils.getSparseSession(jcrSession);
    } catch (RepositoryException e) {
        throw new ServletException(e.getMessage(), e);
    }

    // Anonymous users cannot upload files.
    if (UserConstants.ANON_USERID.equals(userId)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Anonymous users cannot upload files to the pool.");
        return;
    }

    Session adminSession = null;
    try {
        // Grab an admin session so we can create files in the pool space.
        adminSession = sparseRepository.loginAdministrative();
        AuthorizableManager authorizableManager = adminSession.getAuthorizableManager();
        // We need the authorizable for the user node that we'll create under the file.

        Authorizable au = authorizableManager.findAuthorizable(userId);

        // Loop over all the parameters
        // All the ones that are files will be stored.
        int statusCode = HttpServletResponse.SC_BAD_REQUEST;
        boolean fileUpload = false;
        Map<String, Object> results = new HashMap<String, Object>();
        for (Entry<String, RequestParameter[]> e : request.getRequestParameterMap().entrySet()) {
            for (RequestParameter p : e.getValue()) {
                if (!p.isFormField()) {
                    // This is a file upload.
                    // Generate an ID and store it.
                    String fileName = FilenameUtils.getName(p.getFileName()); // IE still sends in an absolute path sometimes.
                    if (poolId == null) {
                        String createPoolId = generatePoolId();
                        Content content = createFile(createPoolId, null, adminSession, p, au, true);
                        results.put(fileName, ImmutableMap.of("poolId", (Object) createPoolId, "item",
                                content.getProperties()));
                        statusCode = HttpServletResponse.SC_CREATED;
                        fileUpload = true;

                        notifyFileUploadHandlers(results, createPoolId, p, au.getId(), true);
                    } else {
                        // Add it to the map so we can output something to the UI.
                        Content content = createFile(poolId, alternativeStream, session, p, au, false);
                        results.put(fileName,
                                ImmutableMap.of("poolId", (Object) poolId, "item", content.getProperties()));
                        statusCode = HttpServletResponse.SC_OK;
                        fileUpload = true;

                        notifyFileUploadHandlers(results, poolId, p, au.getId(), false);
                        break;
                    }

                }
            }
        }
        if (!fileUpload) {
            // not a file upload, ok, create an item and use all the request parameters, only
            // if there was no poolId specified
            if (poolId == null) {
                String createPoolId = generatePoolId();
                results.put("_contentItem", ImmutableMap.of("poolId", (Object) createPoolId, "item",
                        createContentItem(createPoolId, adminSession, request, au).getProperties()));
                statusCode = HttpServletResponse.SC_CREATED;
            }
        }

        this.authorizableCountChanger.notify(UserConstants.CONTENT_ITEMS_PROP, userId);

        // Make sure we're outputting proper json.
        if (statusCode == HttpServletResponse.SC_BAD_REQUEST) {
            response.setStatus(statusCode);
        } else {
            response.setStatus(statusCode);
            response.setContentType("text/plain");
            response.setCharacterEncoding("UTF-8");

            JSONWriter jsonWriter = new JSONWriter(response.getWriter());
            ExtendedJSONWriter.writeValueMap(jsonWriter, results);
        }
    } catch (NoSuchAlgorithmException e) {
        LOGGER.warn(e.getMessage(), e);
        throw new ServletException(e.getMessage(), e);
    } catch (ClientPoolException e) {
        LOGGER.warn(e.getMessage(), e);
        throw new ServletException(e.getMessage(), e);
    } catch (StorageClientException e) {
        LOGGER.warn(e.getMessage(), e);
        throw new ServletException(e.getMessage(), e);
    } catch (AccessDeniedException e) {
        LOGGER.warn(e.getMessage(), e);
        throw new ServletException(e.getMessage(), e);
    } catch (JSONException e) {
        LOGGER.warn(e.getMessage(), e);
        throw new ServletException(e.getMessage(), e);
    } finally {
        // Make sure we're logged out.
        try {
            if (adminSession != null) {
                adminSession.logout();
            }
        } catch (ClientPoolException e) {
            LOGGER.warn(e.getMessage(), e);
        }
    }
}

From source file:ch.entwine.weblounge.test.harness.rest.PagesEndpointTest.java

/**
 * Tests listing of referrer./* www  .  java  2s  . co  m*/
 * 
 * @param serverUrl
 *          the server url
 * @param pageId
 *          the page identifier
 * @throws Exception
 *           if page creation fails
 */
private void testGetReferrer(String serverUrl, String pageId) throws Exception {

    String requestUrl = UrlUtils.concat(serverUrl, "system/weblounge/pages");
    HttpPost createPageRequest = new HttpPost(requestUrl);
    String referringPageId = null;

    // Create a new page and add a pagelet with a link to the original page
    logger.debug("Creating new page");
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, createPageRequest, null);
        assertEquals(HttpServletResponse.SC_CREATED, response.getStatusLine().getStatusCode());
        assertEquals(0, response.getEntity().getContentLength());

        // Extract the id of the new page
        assertNotNull(response.getHeaders("Location"));
        String locationHeader = response.getHeaders("Location")[0].getValue();
        assertTrue(locationHeader.startsWith(serverUrl));
        referringPageId = locationHeader.substring(locationHeader.lastIndexOf("/") + 1);
        logger.debug("Id of the new page is {}", referringPageId);

        httpClient.getConnectionManager().shutdown();
        httpClient = new DefaultHttpClient();

        // Load the created page
        String referringPageUrl = UrlUtils.concat(requestUrl, referringPageId, "?version=1");
        HttpGet getPageRequest = new HttpGet(referringPageUrl);
        response = TestUtils.request(httpClient, getPageRequest, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        String pageXml = TestUtils.parseTextResponse(response);

        httpClient.getConnectionManager().shutdown();
        httpClient = new DefaultHttpClient();

        // Lock the page
        HttpPut lockPageRequest = new HttpPut(UrlUtils.concat(requestUrl, referringPageId, "lock"));
        logger.info("Locking the page at {}", requestUrl);
        response = TestUtils.request(httpClient, lockPageRequest, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

        httpClient.getConnectionManager().shutdown();
        httpClient = new DefaultHttpClient();

        // Add a pagelet and post the updated page
        String pageletSecurity = "<security><owner><user id=\"hans\" realm=\"testland\"><![CDATA[Hans Muster]]></user></owner></security>";
        String pageletCreation = "<created><user id=\"hans\" realm=\"testland\"><![CDATA[Hans Muster]]></user><date>2009-01-07T19:05:41Z</date></created>";
        String pageletPublication = "<published><user id=\"hans\" realm=\"testland\"><![CDATA[Hans Muster]]></user><from>2009-01-07T19:05:41Z</from></published>";
        String pageletProperties = "<properties><property id=\"resourceid\"><![CDATA[" + pageId
                + "]]></property></properties>";
        pageXml = pageXml.replaceAll("<body/>",
                "<body><composer id=\"main\"><pagelet module=\"navigation\" id=\"link\">" + pageletSecurity
                        + pageletCreation + pageletPublication + pageletProperties
                        + "</pagelet></composer></body>");
        HttpPut updatePageRequest = new HttpPut(referringPageUrl);
        String[][] params = new String[][] { { "content", pageXml } };
        logger.info("Updating page at {}", referringPageUrl);
        response = TestUtils.request(httpClient, updatePageRequest, params);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

        // Publish it
        HttpPut publishPageRequest = new HttpPut(UrlUtils.concat(requestUrl, referringPageId, "publish"));
        httpClient = new DefaultHttpClient();
        logger.info("Publishing the page at {}", requestUrl);
        response = TestUtils.request(httpClient, publishPageRequest, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    // Make sure the page is being issued as a referrer of the original page
    String requestReferrerUrl = UrlUtils.concat(requestUrl, pageId, "referrer");
    HttpGet getPageRequest = new HttpGet(requestReferrerUrl);
    logger.info("Requesting referrer of {} at {}", pageId, requestReferrerUrl);
    // Wait as long as 10s for the asynchronous processing
    boolean success = false;
    for (int i = 0; i < 5; i++) {
        httpClient = new DefaultHttpClient();
        try {
            HttpResponse response = TestUtils.request(httpClient, getPageRequest, null);
            assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Document referrer = TestUtils.parseXMLResponse(response);
            assertEquals(1, XPathHelper.selectList(referrer, "/pages/page").getLength());
            assertEquals(referringPageId, XPathHelper.valueOf(referrer, "/pages/page/@id"));
            success = true;
            break;
        } catch (AssertionError a) {
            logger.debug("Waiting, then retrying due to asynchronous processing");
            Thread.sleep(2000);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
    assertTrue(success);

    // Delete the new page
    HttpDelete deleteRequest = new HttpDelete(UrlUtils.concat(requestUrl, referringPageId));
    httpClient = new DefaultHttpClient();

    // Delete the page
    logger.info("Sending delete request to {}", requestUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, deleteRequest, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:com.homesnap.webserver.ControllerRestAPITest.java

@Test
public void test13OnStatus() {

    // Test to get a controller of type light!
    JSONObject jo = getRequestJSONObject(urn_labels + "/ch1/controller?id=12&param=param");
    testController12(jo);//  w w  w .  jav a  2  s  . co m

    jo = getRequestJSONObject(urn_labels + "/ch1/12?param=param");
    testController12(jo);

    jo = getRequestJSONObject(urn_groups + "/1/controller?id=16&param=param");
    Assert.assertNull(jo); // have been deleted

    jo = getRequestJSONObject(urn_groups + "/1/16?param=param");
    Assert.assertNull(jo); // have been deleted

    jo = getRequestJSONObject("/house/controllers/12?param=param");
    testController12(jo);

    jo = getRequestJSONObject("/house/controllers/controller?id=12&param=param");
    testController12(jo);

    jo = getRequestJSONObject("/house/controllers/12?param=param");
    testController12(jo);

    // Modification
    putRequestJSONObject("/house/controllers/12?status=On", createJsonController12(),
            HttpServletResponse.SC_OK);
    putRequestJSONObject("/house/controllers/controller?id=12&status=Off", createJsonController12(),
            HttpServletResponse.SC_OK);

    putRequestJSONObject(urn_groups + "/1/controller?id=12&param=param", createJsonController12(),
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    putRequestJSONObject(urn_groups + "/1/12?status=Off", createJsonController12(), HttpServletResponse.SC_OK);
    putRequestJSONObject(urn_labels + "/ch1/controller?id=12&status=Off", createJsonController12(),
            HttpServletResponse.SC_OK);
    putRequestJSONObject(urn_labels + "/ch1/12?status=Off", createJsonController12(),
            HttpServletResponse.SC_OK);
    putRequestJSONObject("/house/controllers/12?param=param", createJsonController12(),
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    putRequestJSONObject("/house/controllers/controller?id=12&status=Off", createJsonController12(),
            HttpServletResponse.SC_OK);
    putRequestJSONObject("/house/controllers/12?status=Off", createJsonController12(),
            HttpServletResponse.SC_OK);

    // creation
    postRequestJSONObject(urn_groups + "/1/controller?id=17&status=Off", createJsonController17(),
            HttpServletResponse.SC_CREATED);
    postRequestJSONObject(urn_groups + "/1/12?status=Off", createJsonController12(),
            HttpServletResponse.SC_NOT_ACCEPTABLE);
    postRequestJSONObject(urn_labels + "/ch1/controller?id=17&status=Off", createJsonController17(),
            HttpServletResponse.SC_CREATED);
    postRequestJSONObject(urn_labels + "/ch1/17?status=Off", createJsonController17(),
            HttpServletResponse.SC_NOT_ACCEPTABLE);
    postRequestJSONObject("/house/17?status=Off", createJsonController17(), HttpServletResponse.SC_BAD_REQUEST);
    postRequestJSONObject("/house/controllers/controller?id=12&status=Off", createJsonController17(),
            HttpServletResponse.SC_NOT_IMPLEMENTED);
    postRequestJSONObject("/house/controllers/12?status=Off", createJsonController17(),
            HttpServletResponse.SC_NOT_IMPLEMENTED);

    // Deletion
    deleteRequestJSONObject(urn_groups + "/1/controller?id=11&status=Off",
            HttpServletResponse.SC_NOT_ACCEPTABLE);
    deleteRequestJSONObject(urn_groups + "/1/11?status=Off", HttpServletResponse.SC_NOT_ACCEPTABLE);
    deleteRequestJSONObject(urn_labels + "/ch1/controller?id=12&status=Off", HttpServletResponse.SC_OK);
    deleteRequestJSONObject(urn_labels + "/ch1/12?status=Off", HttpServletResponse.SC_NOT_ACCEPTABLE);
    deleteRequestJSONObject("/house/controllers/12?status=Off", HttpServletResponse.SC_NOT_IMPLEMENTED);
    deleteRequestJSONObject("/house/controllers/controller?id=12&status=Off",
            HttpServletResponse.SC_NOT_IMPLEMENTED);
}

From source file:jp.aegif.alfresco.online_webdav.PutMethod.java

/**
 * Execute the WebDAV request//from   w w  w.j ava2  s.  c  o  m
 * 
 * @exception WebDAVServerException
 */
protected void executeImpl() throws WebDAVServerException, Exception {
    if (logger.isDebugEnabled()) {
        String path = getPath();
        String userName = getDAVHelper().getAuthenticationService().getCurrentUserName();
        logger.debug("Put node: \n" + "     user: " + userName + "\n" + "     path: " + path + "\n"
                + "noContent: " + noContent);
    }

    FileFolderService fileFolderService = getFileFolderService();

    // Get the status for the request path
    LockInfo nodeLockInfo = null;
    try {
        //contentNodeInfo = getNodeForPath(getRootNodeRef(), getPath(), getServletPath());
        contentNodeInfo = getDAVHelper().getFileInfoFromRequestPath(m_request);
        // make sure that we are not trying to use a folder
        if (contentNodeInfo.isFolder()) {
            throw new WebDAVServerException(HttpServletResponse.SC_BAD_REQUEST);
        }

        nodeLockInfo = checkNode(contentNodeInfo);

        // 'Unhide' nodes hidden by us and behave as though we created them
        NodeRef contentNodeRef = contentNodeInfo.getNodeRef();
        if (fileFolderService.isHidden(contentNodeRef) && !getDAVHelper().isRenameShuffle(getPath())) {
            fileFolderService.setHidden(contentNodeRef, false);
            created = true;
        }
    } catch (FileNotFoundException e) {
        //            // the file doesn't exist - create it
        //            String[] paths = getDAVHelper().splitPath(getPath());
        //            try
        //            {
        //                FileInfo parentNodeInfo = getNodeForPath(getRootNodeRef(), paths[0], getServletPath());
        //                // create file
        //                contentNodeInfo = fileFolderService.create(parentNodeInfo.getNodeRef(), paths[1], ContentModel.TYPE_CONTENT);
        //                created = true;
        //                
        //            }
        //            catch (FileNotFoundException ee)
        //            {
        //                // bad path
        //                throw new WebDAVServerException(HttpServletResponse.SC_BAD_REQUEST);
        //            }
        //            catch (FileExistsException ee)
        //            {
        //                // ALF-7079 fix, retry: it looks like concurrent access (file not found but file exists) 
        //                throw new ConcurrencyFailureException("Concurrent access was detected.",  ee);
        //            }
        throw new WebDAVServerException(HttpServletResponse.SC_BAD_REQUEST);
    }

    String userName = getDAVHelper().getAuthenticationService().getCurrentUserName();
    LockInfo lockInfo = getDAVLockService().getLockInfo(contentNodeInfo.getNodeRef());

    if (lockInfo != null) {

        if (lockInfo.isLocked() && !lockInfo.getOwner().equals(userName)) {
            if (logger.isDebugEnabled()) {
                String path = getPath();
                String owner = lockInfo.getOwner();
                logger.debug("Node locked: path=[" + path + "], owner=[" + owner + "], current user=["
                        + userName + "]");
            }
            // Indicate that the resource is locked
            throw new WebDAVServerException(WebDAV.WEBDAV_SC_LOCKED);
        }
    }

    // ALF-16808: We disable the versionable aspect if we are overwriting
    // empty content because it's probably part of a compound operation to
    // create a new single version
    boolean disabledVersioning = false;

    try {
        // Disable versioning if we are overwriting an empty file with content
        NodeRef nodeRef = contentNodeInfo.getNodeRef();
        ContentData contentData = (ContentData) getNodeService().getProperty(nodeRef,
                ContentModel.PROP_CONTENT);
        if ((contentData == null || contentData.getSize() == 0)
                && getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE)) {
            getDAVHelper().getPolicyBehaviourFilter().disableBehaviour(nodeRef,
                    ContentModel.ASPECT_VERSIONABLE);
            disabledVersioning = true;
        }
        // ALF-16756: To avoid firing inbound rules too early (while a node is still locked) apply the no content aspect
        if (nodeLockInfo != null && nodeLockInfo.isExclusive() && !ContentData.hasContent(contentData)) {
            getNodeService().addAspect(contentNodeInfo.getNodeRef(), ContentModel.ASPECT_NO_CONTENT, null);
        }
        // Access the content
        ContentWriter writer = fileFolderService.getWriter(contentNodeInfo.getNodeRef());

        // set content properties
        writer.guessMimetype(contentNodeInfo.getName());
        writer.guessEncoding();

        // Get the input stream from the request data
        InputStream is = m_request.getInputStream();

        // Write the new data to the content node
        writer.putContent(is);
        // Ask for the document metadata to be extracted
        Action extract = getActionService().createAction(ContentMetadataExtracter.EXECUTOR_NAME);
        if (extract != null) {
            extract.setExecuteAsynchronously(false);
            getActionService().executeAction(extract, contentNodeInfo.getNodeRef());
        }

        // If the mime-type determined by the repository is different
        // from the original specified in the request, update it.
        if (m_strContentType == null || !m_strContentType.equals(writer.getMimetype())) {
            String oldMimeType = m_strContentType;
            m_strContentType = writer.getMimetype();
            if (logger.isDebugEnabled()) {
                logger.debug("Mimetype originally specified as " + oldMimeType + ", now guessed to be "
                        + m_strContentType);
            }
        }

        // Record the uploaded file's size
        fileSize = writer.getSize();

        // Set the response status, depending if the node existed or not
        m_response.setStatus(created ? HttpServletResponse.SC_CREATED : HttpServletResponse.SC_NO_CONTENT);
    } catch (Throwable e) {
        // check if the node was marked with noContent aspect previously by lock method AND
        // we are about to give up
        if (noContent && RetryingTransactionHelper.extractRetryCause(e) == null) {
            // remove the 0 bytes content if save operation failed or was cancelled
            final NodeRef nodeRef = contentNodeInfo.getNodeRef();
            getTransactionService().getRetryingTransactionHelper()
                    .doInTransaction(new RetryingTransactionCallback<String>() {
                        public String execute() throws Throwable {
                            getNodeService().deleteNode(nodeRef);
                            if (logger.isDebugEnabled()) {
                                logger.debug("Put failed. DELETE  " + getPath());
                            }
                            return null;
                        }
                    }, false, true);
        }
        throw new WebDAVServerException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    } finally {
        if (disabledVersioning) {
            getDAVHelper().getPolicyBehaviourFilter().enableBehaviour(contentNodeInfo.getNodeRef(),
                    ContentModel.ASPECT_VERSIONABLE);
        }
    }

    postActivity();

}

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

@Test
public void testPutContentToNonExistingFile() throws Exception {
    String fileName = "file-" + GUID.generate();
    NodeRef fileNoderef = null;//  ww w .  j ava  2  s  .co m
    try {
        executeMethod(WebDAV.METHOD_PUT, fileName, testDataFile, null);

        ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE,
                "PATH:\"/app:company_home//cm:" + fileName + "\"");
        fileNoderef = resultSet.getNodeRef(0);
        resultSet.close();

        assertTrue("File does not exist.", nodeService.exists(fileNoderef));
        assertEquals("Filename is not correct", fileName,
                nodeService.getProperty(fileNoderef, ContentModel.PROP_NAME));
        assertTrue("Expected return status is " + HttpServletResponse.SC_CREATED + ", but returned is "
                + response.getStatus(), HttpServletResponse.SC_CREATED == response.getStatus());
        InputStream updatedFileIS = fileFolderService.getReader(fileNoderef).getContentInputStream();
        byte[] updatedFile = IOUtils.toByteArray(updatedFileIS);
        updatedFileIS.close();
        assertTrue("The content has to be equal", ArrayUtils.isEquals(testDataFile, updatedFile));
    } 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:org.opencastproject.scheduler.endpoint.SchedulerRestService.java

/**
 * Creates new event(s) based on parameters. All times and dates are in milliseconds.
 *//* w ww  .j a v a 2s .  co m*/
@POST
@Path("/")
@RestQuery(name = "newrecordings", description = "Creates new event or group of event with specified parameters", returnDescription = "If events were successfully generated, status CREATED is returned, otherwise BAD REQUEST", restParameters = {
        @RestParameter(name = "dublincore", isRequired = true, type = Type.TEXT, description = "Dublin Core describing event", defaultValue = "${this.sampleDublinCore}"),
        @RestParameter(name = "agentparameters", isRequired = true, type = Type.TEXT, description = "Capture agent properties for event", defaultValue = "${this.sampleCAProperties}"),
        @RestParameter(name = "wfproperties", isRequired = false, type = Type.TEXT, description = "Workflow configuration properties"),
        @RestParameter(name = "event", isRequired = false, type = Type.TEXT, description = "Catalog containing information about the event that doesn't exist in DC (IE: Recurrence rule)") }, reponses = {
                @RestResponse(responseCode = HttpServletResponse.SC_CREATED, description = "Event or events were successfully created"),
                @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "Missing or invalid information for this request") })
public Response addEvent(@FormParam("dublincore") String dublinCoreXml,
        @FormParam("agentparameters") String agentParameters,
        @FormParam("wfproperties") String workflowProperties, @FormParam("event") String event) {

    if (StringUtils.isBlank(dublinCoreXml)) {
        logger.warn("Cannot add event without dublin core catalog.");
        return Response.status(Status.BAD_REQUEST).build();
    }

    if (StringUtils.isBlank(agentParameters)) {
        logger.warn("Cannot add event without capture agent parameters catalog.");
        return Response.status(Status.BAD_REQUEST).build();
    }

    DublinCoreCatalog eventCatalog;
    try {
        logger.debug("DublinCore catalog found.");
        eventCatalog = parseDublinCore(dublinCoreXml);
        logger.debug(eventCatalog.toXmlString());
    } catch (Exception e) {
        logger.warn("Could not parse Dublin core catalog: {}", e);
        return Response.status(Status.BAD_REQUEST).build();
    }

    Properties caProperties;
    try {
        caProperties = parseProperties(agentParameters);
    } catch (Exception e) {
        logger.warn("Could not parse capture agent properties: {}", agentParameters);
        return Response.status(Status.BAD_REQUEST).build();
    }

    Map<String, String> wfProperties = new HashMap<String, String>();
    if (StringUtils.isNotBlank(workflowProperties)) {
        try {
            Properties prop = parseProperties(workflowProperties);
            wfProperties.putAll((Map) prop);
        } catch (IOException e) {
            logger.warn("Could not parse workflow configuration properties: {}", workflowProperties);
            return Response.status(Status.BAD_REQUEST).build();
        }
    }

    try {
        if (eventCatalog.hasValue(DublinCoreCatalogImpl.PROPERTY_RECURRENCE)) {
            // try to create event and it's recurrences
            Long[] createdIDs = service.addReccuringEvent(eventCatalog, wfProperties);
            for (long id : createdIDs) {
                service.updateCaptureAgentMetadata(caProperties, tuple(id, service.getEventDublinCore(id)));
            }
            return Response.status(Status.CREATED).build();
        } else {
            Long id = service.addEvent(eventCatalog, wfProperties);
            service.updateCaptureAgentMetadata(caProperties, tuple(id, eventCatalog));
            return Response.status(Status.CREATED)
                    .header("Location",
                            PathSupport.concat(new String[] { this.serverUrl, this.serviceUrl, id + ".xml" }))
                    .build();
        }
    } catch (Exception e) {
        logger.warn("Unable to create new event: {}", e);
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTReport.java

/**
 * This method allows the user to create (run/fill) a new report.
 * //w  ww . jav  a2s.  c o  m
 *
 * @param req
 * @param resp
 * @throws ServiceException
 */
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {

    // We are creating a new report here...
    // Add all the options...
    Map<String, String> options = new HashMap<String, String>();
    // Add as option all the GET parameters...
    Enumeration en = req.getParameterNames();
    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        options.put(key, req.getParameter(key));
    }

    Map<String, Object> parameters = new HashMap<String, Object>();

    // We expect the user to send us a ResourceDescriptor with some parameters in it...
    HttpServletRequest mreq = restUtils.extractAttachments(runReportService, req);

    String resourceDescriptorXml = null;

    // get the resource descriptor...
    if (mreq instanceof MultipartHttpServletRequest) {
        resourceDescriptorXml = mreq.getParameter(restUtils.REQUEST_PARAMENTER_RD);
    } else {
        try {
            resourceDescriptorXml = IOUtils.toString(req.getInputStream());
        } catch (IOException ex) {
            throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage());
        }
    }

    if (resourceDescriptorXml == null) {
        restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "Missing parameter "
                + restUtils.REQUEST_PARAMENTER_RD + " " + runReportService.getInputAttachments());
        return;
    }

    // Parse the resource descriptor...
    InputSource is = new InputSource(new StringReader(resourceDescriptorXml));
    Document doc = null;
    ResourceDescriptor rd = null;
    try {
        doc = XMLUtil.getNewDocumentBuilder().parse(is);
        rd = Unmarshaller.readResourceDescriptor(doc.getDocumentElement());
    } catch (SAXException ex) {
        restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "Invalid resource descriptor");
        return;
    } catch (ServiceException se) {

        if (se.getErrorCode() == ServiceException.RESOURCE_NOT_FOUND) {
            restUtils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp, se.getLocalizedMessage());
            throw new ServiceException(HttpServletResponse.SC_NOT_FOUND, se.getMessage());
        } else {
            throw se;
        }
    } catch (Exception ex) {
        throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage());
    }

    // At this point we have a resource descriptor, find the parameters in it and the uri
    String uri = rd.getUriString();

    List params = rd.getParameters();
    for (int i = 0; i < params.size(); ++i) {
        ListItem parameter = (ListItem) params.get(i);
        if (parameter.isIsListItem()) {
            // Check if a collection exists for this parameter..
            List collection = (List) parameters.get(parameter.getLabel());
            if (collection == null) {
                collection = new ArrayList<String>();
                parameters.put(parameter.getLabel(), collection);
            }
            collection.add(parameter.getValue());
        } else {
            parameters.put(parameter.getLabel(), parameter.getValue());
        }
    }

    if (log.isDebugEnabled())
        log.debug("Running report " + uri + " with parameters: " + parameters + " and options: " + options);

    // highcharts report for REST v1 is by default noninteractive.
    if (!options.containsKey(Argument.PARAM_INTERACTIVE)) {
        options.put(Argument.PARAM_INTERACTIVE, Boolean.FALSE.toString());
    }
    Map<String, DataSource> attachments = new ConcurrentHashMap<String, DataSource>();

    OperationResult or = runReportService.runReport(uri, parameters, options, attachments);

    if (or.getReturnCode() != 0) {
        restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, or.getMessage());
        return;
    } else {
        JasperPrint jp = (JasperPrint) runReportService.getAttributes().get("jasperPrint");

        // Store the attachments in the session, with proper keys...

        HttpSession session = req.getSession();

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

        Report report = new Report();

        report.setUuid(executionId);
        report.setOriginalUri(uri);
        report.setAttachments(attachments);
        report.setJasperPrint(jp);

        session.setAttribute(report.getUuid(), report);

        // Send out the xml...
        resp.setContentType("text/xml; charset=UTF-8");
        restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, report.toXml());
    }
}

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

@Test
public void testCheckInWithDigestHeader() throws Exception {
    setUpData();/*w  w  w  . j a  va 2 s.  co m*/
    session.clear(); // clear cache

    assumeTrue(isBrowser);

    String content = FILE1_CONTENT + " Updated";
    String contentMD5Hex = DigestUtils.md5Hex(content);
    String contentMD5Base64 = NuxeoPropertyData.transcodeHexToBase64(contentMD5Hex);

    File[] files = createFiles(content);

    ObjectMapper mapper = new ObjectMapper();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
        String uri = getURI("/testfolder1/testfile7") + "&succinct=true&filter=cmis:contentStreamHash";
        HttpPost request = new HttpPost(uri);
        request.setHeader("Authorization", BASIC_AUTH);
        for (int i = 0; i < 2; i++) {
            boolean okRequest = i == 0;

            List<NameValuePair> paramList = Arrays.asList(new BasicNameValuePair("cmisaction", "checkOut"));
            HttpEntity reqEntity = new UrlEncodedFormEntity(paramList);
            request.setEntity(reqEntity);
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                assertEquals(HttpServletResponse.SC_CREATED, response.getStatusLine().getStatusCode());
                InputStream is = response.getEntity().getContent();
                JsonNode root = mapper.readTree(is);
                String objectId = root.path("succinctProperties").path("cmis:objectId").getTextValue();
                assertNotNull(objectId);
            }

            request.setHeader("Digest", "md5=" + (String) (okRequest ? contentMD5Base64 : "bogusMD5Sum"));
            reqEntity = getCheckInHttpEntity(files[i]);
            request.setEntity(reqEntity);
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                if (okRequest) {
                    checkOkContentStreamResponse(contentMD5Hex, mapper, response);
                } else {
                    checkBadContentStreamResponse(mapper, response);
                }
            }
        }
    }
    deleteFiles(files);
}