Java Code Examples for org.springframework.extensions.webscripts.Status#STATUS_OK

The following examples show how to use org.springframework.extensions.webscripts.Status#STATUS_OK . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ResourceInspector.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static int validSuccessCode(HttpMethod httpMethod, int success)
{
    if (!(ResourceOperation.UNSET_STATUS == success))
    {
        //The status has been set by the api implementor so use it.
        return success;
    }

    switch (httpMethod)
    {
        case GET:
            return Status.STATUS_OK;
        case POST:
            return Status.STATUS_CREATED;
        case PUT:
            return Status.STATUS_OK;
        case DELETE:
            return Status.STATUS_NO_CONTENT;
        default:
            return Status.STATUS_OK;
    }

}
 
Example 2
Source File: DiscussionRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
private JSONObject doUpdatePost(String url, String title, String content, 
      int expectedStatus) throws Exception
{
   JSONObject post = new JSONObject();
   post.put("title", title);
   post.put("content", content);
   Response response = sendRequest(new PutRequest(url, post.toString(), "application/json"), expectedStatus);

   if (expectedStatus != Status.STATUS_OK)
   {
      return null;
   }

   JSONObject result = new JSONObject(response.getContentAsString());
   return result.getJSONObject("item");
}
 
Example 3
Source File: LinksRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Deletes the links
 */
private JSONObject deleteLinks(List<String> names, int expectedStatus) throws Exception
{
   JSONArray items = new JSONArray();
   for (String name : names)
   {
      items.put(name);
   }
   
   JSONObject json = new JSONObject();
   json.put("items", items);
   
   Response response = sendRequest(new PostRequest(URL_LINKS_DELETE, json.toString(), "application/json"), expectedStatus);
   if (expectedStatus == Status.STATUS_OK)
   {
      JSONObject result = new JSONObject(response.getContentAsString());
      return result;
   }
   else
   {
      return null;
   }
}
 
Example 4
Source File: LinksRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
private JSONObject getLink(String name, int expectedStatus) throws Exception
{
   Response response = sendRequest(new GetRequest(URL_LINKS_FETCH + name), expectedStatus);
   if (expectedStatus == Status.STATUS_OK)
   {
      JSONObject result = new JSONObject(response.getContentAsString());
      if (result.has("item"))
      {
         return result.getJSONObject("item");
      }
      return result;
   }
   else
   {
      return null;
   }
}
 
Example 5
Source File: LinksRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a single link based on the supplied details
 */
private JSONObject createLink(String title, String description, String url,
      boolean internal, int expectedStatus) throws Exception
{
   JSONObject json = new JSONObject();
   json.put("site", SITE_SHORT_NAME_LINKS);
   json.put("title", title);
   json.put("description", description);
   json.put("url", url);
   json.put("tags", "");
   if (internal)
   {
      json.put("internal", "true");
   }
   json.put("page", "links-view"); // TODO Is this really needed?
   
   Response response = sendRequest(new PostRequest(URL_LINKS_CREATE, json.toString(), "application/json"), expectedStatus);
   if (expectedStatus == Status.STATUS_OK)
   {
      JSONObject result = new JSONObject(response.getContentAsString());
      if (result.has("link"))
      {
         return result.getJSONObject("link");
      }
      return result;
   }
   else
   {
      return null;
   }
}
 
Example 6
Source File: DiscussionRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private JSONObject doDeletePost(String url, int expectedStatus) throws Exception
{
   Response response = sendRequest(new DeleteRequest(url), Status.STATUS_OK);
   if (expectedStatus == Status.STATUS_OK)
   {
      return new JSONObject(response.getContentAsString());
   }
   else
   {
      return null;
   }
}
 
Example 7
Source File: DiscussionRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private JSONObject doGetPosts(String baseUrl, String type, int expectedStatus) throws Exception
{
   String url = null;
   if (type == null)
   {
      url = baseUrl;
   }
   else if (type == "limit")
   {
      url = baseUrl + "?pageSize=1";
   }
   else if (type == "hot")
   {
      url = baseUrl + "/hot";
   }
   else if (type == "mine")
   {
      url = baseUrl + "/myposts";
   }
   else if (type.startsWith("new"))
   {
      url = baseUrl + "/" + type;
   }
   else
   {
      throw new IllegalArgumentException("Invalid search type " + type);
   }
   
   Response response = sendRequest(new GetRequest(url), expectedStatus);
   if (expectedStatus == Status.STATUS_OK)
   {
      JSONObject result = new JSONObject(response.getContentAsString());
      return result;
   }
   else
   {
      return null;
   }
}
 
Example 8
Source File: DiscussionRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private JSONObject doGetReplies(String url, int expectedStatus) throws Exception
{
   Response response = sendRequest(new GetRequest(url), expectedStatus);
   if (expectedStatus == Status.STATUS_OK)
   {
      JSONObject result = new JSONObject(response.getContentAsString());
      return result;
   }
   else
   {
      return null;
   }
}
 
Example 9
Source File: DiscussionRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private JSONObject doGetPost(String url, int expectedStatus) throws Exception
{
   Response response = sendRequest(new GetRequest(url), expectedStatus);
   if (expectedStatus == Status.STATUS_OK)
   {
      JSONObject result = new JSONObject(response.getContentAsString());
      return result.getJSONObject("item");
   }
   else
   {
      return null;
   }
}
 
Example 10
Source File: LinksRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Deletes the link
 */
private JSONObject deleteLink(String name, int expectedStatus) throws Exception
{
   Response response = sendRequest(new DeleteRequest(URL_LINKS_FETCH+name), expectedStatus);
   if (expectedStatus == Status.STATUS_OK)
   {
      JSONObject result = new JSONObject(response.getContentAsString());
      return result;
   }
   else
   {
      return null;
   }
}
 
Example 11
Source File: LinksRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Updates the link with the new details
 */
private JSONObject updateLink(String name, String title, String description, String url,
      boolean internal, int expectedStatus) throws Exception
{
   JSONObject json = new JSONObject();
   json.put("site", SITE_SHORT_NAME_LINKS);
   json.put("title", title);
   json.put("description", description);
   json.put("url", url);
   json.put("tags", "");
   json.put("internal", Boolean.toString(internal).toLowerCase());
   json.put("page", "links-view"); // TODO Is this really needed?
   
   Response response = sendRequest(new PutRequest(URL_LINKS_UPDATE + name, json.toString(), "application/json"), expectedStatus);
   if (expectedStatus == Status.STATUS_OK)
   {
      JSONObject result = new JSONObject(response.getContentAsString());
      if (result.has("links"))
      {
         return result.getJSONObject("links");
      }
      return result;
   }
   else
   {
      return null;
   }
}
 
Example 12
Source File: WithResponseTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testSetHeader() throws Exception
{
    WithResponse callBack = new WithResponse(Status.STATUS_OK,ResponseWriter.DEFAULT_JSON_CONTENT, ResponseWriter.CACHE_NEVER);
    callBack.setHeader("king", "can");
    callBack.setHeader("king", "kong");
    assertTrue(callBack.getHeaders().size() == 1);
    List<String> vals = callBack.getHeaders().get("king");
    assertTrue(vals.size() == 1);
    assertEquals("kong", vals.get(0));
}
 
Example 13
Source File: WithResponseTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testAddHeader() throws Exception
{
    WithResponse callBack = new WithResponse(Status.STATUS_OK,ResponseWriter.DEFAULT_JSON_CONTENT, ResponseWriter.CACHE_NEVER);
    callBack.addHeader("king", "can");
    callBack.addHeader("king", "kong");
    assertTrue(callBack.getHeaders().size() == 1);
    List<String> vals = callBack.getHeaders().get("king");
    assertTrue(vals.size() == 2);
    assertEquals(vals, Arrays.asList("can", "kong"));
}
 
Example 14
Source File: CalendarRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private JSONObject getEntry(String name, int expectedStatus) throws Exception
{
   Response response = sendRequest(new GetRequest(URL_EVENT_BASE + name), expectedStatus);
   if (expectedStatus == Status.STATUS_OK)
   {
      JSONObject result = validateAndParseJSON(response.getContentAsString());
      return result;
   }
   else
   {
      return null;
   }
}
 
Example 15
Source File: UserCSVUploadPost.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void processUpload(InputStream input, String filename, List<Map<QName,String>> users)
{
    try
    {
        if (filename != null && filename.length() > 0)
        {
            if (filename.endsWith(".csv"))
            {
                processCSVUpload(input, users);
                return;
            }
            if (filename.endsWith(".xls"))
            {
                processXLSUpload(input, users);
                return;
            }
            if (filename.endsWith(".xlsx"))
            {
                processXLSXUpload(input, users);
                return;
            }
        }
        
        // If in doubt, assume it's probably a .csv
        processCSVUpload(input, users);
    } 
    catch (IOException e)
    {
        // Return the error as a 200 so the user gets a friendly
        //  display of the error message in share
        throw new ResourceBundleWebScriptException(
                Status.STATUS_OK, getResources(),
                ERROR_CORRUPT_FILE, e);
    }
}
 
Example 16
Source File: CalendarRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
     * Updates the event to be a 2 hour, non-all day event on the 28th of June
     */
    private JSONObject updateEntry(String name, String what, String where, String description, 
          boolean withRecurrence, int expectedStatus) throws Exception
    {
       String date = "2011/06/28"; // A Tuesday
       String start = "11:30";
       String end = "13:30";
       
       JSONObject json = new JSONObject();
       json.put("what", what);
       json.put("where", where);
       json.put("desc", description);
       json.put("from", date);
       json.put("to", date);
//       json.put("fromdate", "Tuesday, 30 June 2011"); // Not needed
//       json.put("todate", "Tuesday, 30 June 2011"); // Not needed
       json.put("start", start);
       json.put("end", end);
       json.put("tags", "");
       json.put("docfolder", "");
       json.put("page", "calendar");
       
       if (withRecurrence)
       {
          json.put("recurrenceRule", "FREQ=WEEKLY;INTERVAL=2;BYDAY=WE,FR");
          json.put("recurrenceLastMeeting", "2011-09-11");
       }
       
       Response response = sendRequest(new PutRequest(URL_EVENT_BASE + name, json.toString(), "application/json"), expectedStatus);
       if (expectedStatus == Status.STATUS_OK)
       {
          JSONObject result = validateAndParseJSON(response.getContentAsString());
          if (result.has("event"))
          {
             return result.getJSONObject("event");
          }
          if (result.has("data"))
          {
             return result.getJSONObject("data");
          }
          return result;
       }
       else
       {
          return null;
       }
    }
 
Example 17
Source File: InspectorTests.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testInspectOperations() throws IllegalAccessException, InstantiationException, Throwable
{
    Api api = Api.valueOf("alfrescomock", "private", "1");
    List<ResourceMetadata> metainfo = new ArrayList<ResourceMetadata>();

    GrassEntityResource grassEntityResource = new GrassEntityResource();
    ResourceInspector.inspectOperations(api, GrassEntityResource.class,"-root-", metainfo);
    assertEquals(3, metainfo.size());

    for (ResourceMetadata resourceMetadata : metainfo)
    {
        assertEquals(ResourceMetadata.RESOURCE_TYPE.OPERATION, resourceMetadata.getType());
        OperationResourceMetaData operationResourceMetaData = (OperationResourceMetaData) resourceMetadata;
        Method actionMethod = operationResourceMetaData.getOperationMethod();
        String result = null;
        final WithResponse wr = new WithResponse(Status.STATUS_OK, ResponseWriter.DEFAULT_JSON_CONTENT, ResponseWriter.CACHE_NEVER);

        switch (resourceMetadata.getUniqueId())
        {
            case "/-root-/{id}/grow":
                assertNotNull("GrassEntityResource supports POST", resourceMetadata.getOperation(HttpMethod.POST));
                assertNull("GrassEntityResource does not support DELETE", resourceMetadata.getOperation(HttpMethod.DELETE));
                ResourceOperation op = resourceMetadata.getOperation(HttpMethod.POST);
                assertEquals("grow should return ACCEPTED", Status.STATUS_ACCEPTED, op.getSuccessStatus());
                Class paramType = resourceMetadata.getObjectType(op);
                Object paramObj = paramType.newInstance();
                result = (String) ResourceInspectorUtil.invokeMethod(actionMethod,grassEntityResource, "xyz", paramObj, Params.valueOf("notUsed", null, mock(WebScriptRequest.class)), wr);
                assertEquals("Growing well",result);
                assertFalse(operationResourceMetaData.isNoAuth(null));
                break;
            case "/-root-/{id}/cut":
                assertNotNull("GrassEntityResource supports POST", resourceMetadata.getOperation(HttpMethod.POST));
                assertNull("GrassEntityResource does not support GET", resourceMetadata.getOperation(HttpMethod.GET));
                op = resourceMetadata.getOperation(HttpMethod.POST);
                assertNull(resourceMetadata.getObjectType(op));
                assertEquals("cut should return ACCEPTED", Status.STATUS_NOT_IMPLEMENTED, op.getSuccessStatus());
                result = (String) ResourceInspectorUtil.invokeMethod(actionMethod,grassEntityResource, "xyz", null, Params.valueOf("notUsed", null, mock(WebScriptRequest.class)), wr);
                assertEquals("All done",result);
                assertFalse(operationResourceMetaData.isNoAuth(null));
                break;
            case "/-root-/{id}/cut-noAuth":
                assertNotNull("GrassEntityResource supports POST", resourceMetadata.getOperation(HttpMethod.POST));
                op = resourceMetadata.getOperation(HttpMethod.POST);
                assertNull(resourceMetadata.getObjectType(op));
                assertEquals("cut should return ACCEPTED", Status.STATUS_NOT_IMPLEMENTED, op.getSuccessStatus());
                result = (String) ResourceInspectorUtil.invokeMethod(actionMethod,grassEntityResource, "xyz", null, Params.valueOf("notUsed", null, mock(WebScriptRequest.class)), wr);
                assertEquals("All done without Auth",result);
                assertTrue(operationResourceMetaData.isNoAuth(null));
                break;
            default:
                fail("Invalid action information.");
        }

    }
}
 
Example 18
Source File: UserCSVUploadPost.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Builds user objects based on the supplied data. If a row is empty, then
 *  the child String array should be empty too. (Needs to be present so that
 *  the line number reporting works)
 */
private void processSpreadsheetUpload(String[][] data, List<Map<QName,String>> users)
{
    // What we consider to be the literal string "user name" when detecting
    //  if a row is an example/header one or not
    // Note - all of these want to be lower case!
    List<String> usernameIsUsername = new ArrayList<String>();
    // The English literals
    usernameIsUsername.add("username");
    usernameIsUsername.add("user name");
    // And the localised form too if found
    PropertyDefinition unPD = dictionaryService.getProperty(ContentModel.PROP_USERNAME);
    if (unPD != null)
    {
        if(unPD.getTitle(dictionaryService) != null)
            usernameIsUsername.add(unPD.getTitle(dictionaryService).toLowerCase());
        if(unPD.getDescription(dictionaryService) != null)
            usernameIsUsername.add(unPD.getDescription(dictionaryService).toLowerCase());
    }
    
    
    // Process the contents of the spreadsheet
    for (int lineNumber=0; lineNumber<data.length; lineNumber++)
    {
        Map<QName,String> user = new HashMap<QName, String>();
        String[] userData = data[lineNumber];
        
        if (userData == null || userData.length == 0 || 
           (userData.length == 1 && userData[0].trim().length() == 0))
        {
            // Empty line, skip
            continue;
        }
        
        boolean required = true;
        for (int i=0; i<COLUMNS.length; i++)
        {
            if (COLUMNS[i] == null)
            {
                required = false;
                continue;
            }
            
            String value = null;
            if (userData.length > i)
            {
                value = userData[i];
            }
            if (value == null || value.length() == 0)
            {
                if (required)
                {
                    throw new ResourceBundleWebScriptException(
                            Status.STATUS_OK, getResources(),
                            ERROR_BLANK_COLUMN, new Object[] {
                                    COLUMNS[i].getLocalName(), (i+1), (lineNumber+1)});
                }
            }
            else
            {
                user.put(COLUMNS[i], value);
            }
        }

        // If no password was given, use their surname
        if (!user.containsKey(ContentModel.PROP_PASSWORD))
        {
            user.put(ContentModel.PROP_PASSWORD, "");
        }
        
        // Skip any user who looks like an example file heading
        // i.e. a username of "username" or "user name"
        String username = user.get(ContentModel.PROP_USERNAME).toLowerCase();
        if (usernameIsUsername.contains(username))
        {
            // Skip
        }
        else
        {
            // Looks like a real line, keep it
            users.add(user);
        }
    }
}
 
Example 19
Source File: WithResponseTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testSetResponse() throws Exception
{
    AbstractResourceWebScript responseWriter = new ResourceWebScriptDelete();
    responseWriter.setAssistant(new ApiAssistant());
    WithResponse wr = new WithResponse(Status.STATUS_OK, ResponseWriter.DEFAULT_JSON_CONTENT, ResponseWriter.CACHE_NEVER);

    WebScriptResponse response = mock(WebScriptResponse.class);

    responseWriter.setResponse(response,wr.getStatus(), wr.getCache(), wr.getContentInfo(), wr.getHeaders());
    verify(response, times(1)).setStatus(anyInt());
    verify(response, times(1)).setCache((Cache) any());
    verify(response, times(1)).setContentType(anyString());
    verify(response, times(0)).setHeader(anyString(), anyString());

    response = mock(WebScriptResponse.class);

    responseWriter.setResponse(response,wr.getStatus(), null, null, null);
    verify(response, times(1)).setStatus(anyInt());
    verify(response, times(0)).setCache((Cache) any());
    verify(response, times(0)).setContentType(anyString());
    verify(response, times(0)).setHeader(anyString(), anyString());

    response = mock(WebScriptResponse.class);

    wr.addHeader("king", "can");
    wr.addHeader("king", "kong");
    responseWriter.setResponse(response,wr.getStatus(), null, null, wr.getHeaders());
    verify(response, times(1)).setStatus(anyInt());
    verify(response, times(0)).setCache((Cache) any());
    verify(response, times(0)).setContentType(anyString());
    verify(response, times(1)).setHeader(eq("king"), anyString());
    verify(response, times(1)).addHeader(eq("king"), anyString());

    response = mock(WebScriptResponse.class);

    wr.addHeader("king", "kin");
    wr.setHeader("ping", "ping");
    responseWriter.setResponse(response,wr.getStatus(), null, null, wr.getHeaders());
    verify(response, times(1)).setStatus(anyInt());
    verify(response, times(0)).setCache((Cache) any());
    verify(response, times(0)).setContentType(anyString());
    verify(response, times(1)).setHeader(eq("king"), anyString());
    verify(response, times(1)).setHeader(eq("ping"), anyString());
    verify(response, times(2)).addHeader(eq("king"), anyString());


}
 
Example 20
Source File: MessagesTransferCommandProcessor.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
public int process(WebScriptRequest req, WebScriptResponse resp)
{
    String transferRecordId = null;
    try
    {
        // return the unique transfer id (the lock id)
        StringWriter stringWriter = new StringWriter(300);
        JSONWriter jsonWriter = new JSONWriter(stringWriter);
        
        jsonWriter.startValue("data");

        jsonWriter.startArray();
        jsonWriter.startObject();
        //TODO - clearly a dummy message for now.
        jsonWriter.writeValue("message", "hello world");
        jsonWriter.endObject();
        jsonWriter.startObject();
        //TODO - clearly a dummy message for now.
        jsonWriter.writeValue("message", "message2");
        jsonWriter.endObject();
        jsonWriter.endArray();
        jsonWriter.endValue();
        String response = stringWriter.toString();
        
        resp.setContentType("application/json");
        resp.setContentEncoding("UTF-8");
        int length = response.getBytes("UTF-8").length;
        resp.addHeader("Content-Length", "" + length);
        resp.setStatus(Status.STATUS_OK);
        resp.getWriter().write(response);
        
        return Status.STATUS_OK;

    } catch (Exception ex)
    {
        receiver.end(transferRecordId);
        if (ex instanceof TransferException)
        {
            throw (TransferException) ex;
        }
        throw new TransferException(MSG_CAUGHT_UNEXPECTED_EXCEPTION, ex);
    }
}