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

The following examples show how to use org.springframework.extensions.webscripts.Status. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * @see org.springframework.extensions.webscripts.DeclarativeWebScript#executeImpl(WebScriptRequest, Status, Cache)
 */
@Override
protected Map<String, Object> executeImpl(WebScriptRequest request, Status status, Cache cache)
{
    Map<String, Object> result = new HashMap<String, Object>();
    
    cache.setNeverCache(true);
    
    LicenseDescriptor licenseDescriptor = descriptorService.getLicenseDescriptor();
    boolean isEnterprise = (licenseDescriptor == null ? false : (licenseDescriptor.getLicenseMode() == LicenseMode.ENTERPRISE));

    result.put(IS_ENTERPRISE, Boolean.valueOf(isEnterprise));
    result.put(RESULT_IMPORT_STATUS, bulkImporter.getStatus());
    
    return(result);
}
 
Example 2
@Override
protected QName getClassQName(WebScriptRequest req)
{
    QName classQName = null;
    String className = req.getServiceMatch().getTemplateVars().get(DICTIONARY_CLASS_NAME);
    if (className != null && className.length() != 0)
    {            
        classQName = createClassQName(className);
        if (classQName == null)
        {
            // Error 
            throw new WebScriptException(Status.STATUS_NOT_FOUND, "Check the className - " + className + " - parameter in the URL");
        }
    }
    return classQName;
}
 
Example 3
@Override
protected QName getClassQName(WebScriptRequest req)
{
    QName classQName = null;
    String prefix = req.getServiceMatch().getTemplateVars().get(DICTIONARY_PREFIX);
    String shortName = req.getServiceMatch().getTemplateVars().get(DICTIONARY_SHORT_CLASS_NAME);
    if (prefix != null && prefix.length() != 0 && shortName != null && shortName.length()!= 0)
    {            
        classQName = createClassQName(prefix, shortName);
        if (classQName == null)
        {
            // Error 
            throw new WebScriptException(Status.STATUS_NOT_FOUND, "Check the className - " + prefix + ":" + shortName + " - parameter in the URL");
        }
    }
    return classQName;
}
 
Example 4
@Override
protected Map<String, Object> buildModel(WorkflowModelBuilder modelBuilder, WebScriptRequest req, Status status, Cache cache)
{
    Map<String, String> params = req.getServiceMatch().getTemplateVars();

    // getting task id from request parameters
    String taskId = params.get("task_instance_id");

    // searching for task in repository
    WorkflowTask workflowTask = workflowService.getTaskById(taskId);

    // task was not found -> return 404
    if (workflowTask == null)
    {
        throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find workflow task with id: " + taskId);
    }

    Map<String, Object> model = new HashMap<String, Object>();
    // build the model for ftl
    model.put("workflowTask", modelBuilder.buildDetailed(workflowTask));

    return model;
}
 
Example 5
/**
* Negative test - missing parameters
*/
  public void testMissingParameters() throws Exception
  {
  	/**
  	 * Login via get method missing pw
  	 */
      String loginURL = "/api/login?u=" + USER_ONE;
  	sendRequest(new GetRequest(loginURL), Status.STATUS_BAD_REQUEST);
  	
  	/**
  	 * Login via get method missing u
  	 */
      String login2URL = "/api/login?&pw=" + USER_ONE;
  	sendRequest(new GetRequest(login2URL), Status.STATUS_BAD_REQUEST);
  	
  }
 
Example 6
private JSONObject doCreatePost(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 PostRequest(url, post.toString(), "application/json"), expectedStatus);

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

   JSONObject result = new JSONObject(response.getContentAsString());
   JSONObject item = result.getJSONObject("item");
   posts.add(item.getString("name"));
   return item;
}
 
Example 7
@Override
protected Map<String, Object> executeImpl(SiteInfo site, NodeRef nodeRef,
      TopicInfo topic, PostInfo post, WebScriptRequest req, JSONObject json,
      Status status, Cache cache) 
{
   // Build the common model parts
   Map<String, Object> model = buildCommonModel(site, topic, post, req);
   
   // Did they want just one post, or the whole of the topic?
   if (post != null)
   {
      model.put(KEY_POSTDATA, renderPost(post, site));
   }
   else if (topic != null)
   {
      model.put(KEY_POSTDATA, renderTopic(topic, site));
   }
   else
   {
      String error = "Node was of the wrong type, only Topic and Post are supported";
      throw new WebScriptException(Status.STATUS_BAD_REQUEST, error);
   }
   
   // All done
   return model;
}
 
Example 8
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache)
{
    Map<String, Object> model = new HashMap<String, Object>();
    
    try
    {
        req.getContent().getInputStream().close();
        model.put("result", "success");
    }
    catch (IOException e)
    {
        throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Fail to read request content.");
    }
    return model;
}
 
Example 9
/**
 * @see org.springframework.extensions.webscripts.DeclarativeWebScript#executeImpl(org.springframework.extensions.webscripts.WebScriptRequest, org.springframework.extensions.webscripts.Status, org.springframework.extensions.webscripts.Cache)
 */
@Override
protected Map<String, Object> executeImpl(final WebScriptRequest request, final Status status, final Cache cache)
{
    Map<String, Object> result = new HashMap<>();

    cache.setNeverCache(true);
    
    if (importer.getStatus().inProgress())
    {
        result.put("result", "stop requested");
        importer.stop();
        status.setCode(Status.STATUS_ACCEPTED, "Stop requested.");
        status.setRedirect(true);  // Make sure the custom 202 status template is used (why this is needed at all is beyond me...)
    }
    else
    {
        result.put("result", "no imports in progress");
        status.setCode(Status.STATUS_BAD_REQUEST, "No bulk imports are in progress.");
    }
    
    return(result);
}
 
Example 10
protected List<String> getFollowing(String user) throws Exception
{
    String url = getUrl(URL_FOLLOWING, user);
    Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);

    JSONObject resultObject = new JSONObject(response.getContentAsString());
    assertTrue(resultObject.has("people"));

    List<String> result = new ArrayList<String>();
    JSONArray people = resultObject.getJSONArray("people");

    for (int i = 0; i < people.length(); i++)
    {
        JSONObject person = people.getJSONObject(i);
        assertTrue(person.has("userName"));
        assertTrue(person.has("firstName"));
        assertTrue(person.has("lastName"));

        result.add(person.getString("userName"));
    }

    return result;
}
 
Example 11
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache)
{
    Map<String, Object> model = new HashMap<String, Object>();

    NodeRef nodeRef = parseRequestForNodeRef(req);
    String ratingSchemeName = parseRequestForScheme(req);
    
    Rating deletedRating = ratingService.removeRatingByCurrentUser(nodeRef, ratingSchemeName);
    if (deletedRating == null)
    {
        // There was no rating in the specified scheme to delete.
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Unable to delete non-existent rating: "
                + ratingSchemeName + " from " + nodeRef.toString());
    }
    
    model.put(NODE_REF, nodeRef.toString());
    model.put(AVERAGE_RATING, ratingService.getAverageRating(nodeRef, ratingSchemeName));
    model.put(RATINGS_TOTAL, ratingService.getTotalRating(nodeRef, ratingSchemeName));
    model.put(RATINGS_COUNT, ratingService.getRatingsCount(nodeRef, ratingSchemeName));
  
    return model;
}
 
Example 12
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req,
      Status status, Cache cache) 
{
   Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
   
   // Site is optional
   SiteInfo site = null;
   String siteName = templateVars.get("site");
   if (siteName != null)
   {
      site = siteService.getSite(siteName);
      
      // MNT-3053 fix, siteName was provided in request but it doesn't exists or user has no permissions to access it.
      if (site == null)
      {
          status.setCode(HttpServletResponse.SC_NOT_FOUND, "Site '" + siteName + "' does not exist or user has no permissions to access it.");
          return null;
      }
   }
   
   return executeImpl(site, null, req, null, status, cache);
}
 
Example 13
protected boolean follows(String user1, String user2) throws Exception
{
    JSONArray jsonUsers = new JSONArray();
    jsonUsers.put(user2);

    String url = getUrl(URL_FOLLOWS, user1);
    Response response = sendRequest(new PostRequest(url, jsonUsers.toString(), "application/json"),
            Status.STATUS_OK);

    JSONArray resultArray = new JSONArray(response.getContentAsString());
    assertEquals(1, resultArray.length());

    JSONObject resultObject = resultArray.getJSONObject(0);
    assertTrue(resultObject.has(user2));

    return resultObject.getBoolean(user2);
}
 
Example 14
/**
* Positive test - login and retrieve a ticket,
* - via json method 
*/
  public void testAuthenticationGetJSON() throws Exception
  {
   	/**
  	 * Login via get method to return json
  	 */
      String loginURL = "/api/login.json?u=" + USER_ONE + "&pw=" + USER_ONE ;
  	Response resp = sendRequest(new GetRequest(loginURL), Status.STATUS_OK);
  	JSONObject result = new JSONObject(resp.getContentAsString());
  	JSONObject data = result.getJSONObject("data");
  	String ticket = data.getString("ticket");
  	assertNotNull("ticket is null", ticket);
  	
  	/**
  	 * This is now testing the framework ... With a different format.
  	 */
      String login2URL = "/api/login?u=" + USER_ONE + "&pw=" + USER_ONE + "&format=json";
  	Response resp2 = sendRequest(new GetRequest(login2URL), Status.STATUS_OK);
  	JSONObject result2 = new JSONObject(resp2.getContentAsString());
  	JSONObject data2 = result2.getJSONObject("data");
  	String ticket2 = data2.getString("ticket");
  	assertNotNull("ticket is null", ticket2);
  	
  }
 
Example 15
/**
 * Create link for sourceNodeRef in destinationNodeRef location
 * 
 * @param destinationNodeRef
 * @param sourceNodeRef
 * @return
 */
private NodeRef createLink(NodeRef destinationNodeRef, NodeRef sourceNodeRef)
{
    NodeRef linkNodeRef = null;
    try
    {
        linkNodeRef = documentLinkService.createDocumentLink(sourceNodeRef, destinationNodeRef);
    }
    catch (IllegalArgumentException ex)
    {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Invalid Arguments: " + ex.getMessage());
    }
    catch (AccessDeniedException e)
    {
        throw new WebScriptException(Status.STATUS_FORBIDDEN, "You don't have permission to perform this operation");
    }
    return linkNodeRef;
}
 
Example 16
private JSONObject getInviteInfo(String inviteId, String inviteTicket, String inviteeUid) throws Exception
{
    String url = "/api/invite/" + inviteId + "/" + inviteTicket + "?inviteeUserName=" + inviteeUid;

    String runAsUser = AuthenticationUtil.getRunAsUser();

    Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);

    if (!runAsUser.equals(AuthenticationUtil.getRunAsUser()))
    {
        AuthenticationUtil.setRunAsUser(runAsUser);
    }

    JSONObject result = new JSONObject(response.getContentAsString());

    return result;
}
 
Example 17
/**
 * Converts the given comma delimited string of NodeRefs to an array
 * of NodeRefs. If the string is null a WebScriptException is thrown.
 * 
 * @param nodeRefsParam Comma delimited string of NodeRefs
 * @return Array of NodeRef objects
 */
protected NodeRef[] getNodeRefs(String nodeRefsParam)
{
    // check the list of NodeRefs is present
    if (nodeRefsParam == null)
    {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST,
            "Mandatory 'nodeRefs' parameter was not provided in form data");
    }
    
    List<NodeRef> listNodeRefs = new ArrayList<NodeRef>(8);
    StringTokenizer tokenizer = new StringTokenizer(nodeRefsParam, ",");
    while (tokenizer.hasMoreTokens())
    {
        listNodeRefs.add(new NodeRef(tokenizer.nextToken().trim()));
    }
    
    NodeRef[] nodeRefs = new NodeRef[listNodeRefs.size()];
    nodeRefs = listNodeRefs.toArray(nodeRefs);
    
    return nodeRefs;
}
 
Example 18
/**
 * Override method from DeclarativeWebScript
 */
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache)
{
    Map<String, Object> model = new HashMap<String, Object>(1);
    QName classQname = getClassQname(req);
    QName propertyQname = getPropertyQname(req);

    if (this.dictionaryservice.getClass(classQname).getProperties().get(propertyQname) != null)
    {
        model.put(MODEL_PROP_KEY_PROPERTY_DETAILS, this.dictionaryservice.getClass(classQname).getProperties().get(propertyQname));
        model.put(MODEL_PROP_KEY_MESSAGE_LOOKUP, this.dictionaryservice);
    }

    return model;
}
 
Example 19
/**
 * @param prefix        prefix for classname as cm
 * @param shorname      the short class name as person
 * @return String       the full name in the following format {namespaceuri}shorname
 */
public String getFullNamespaceURI(String prefix, String shorname)
{
    try
    {
        String result = null;
        String url = this.namespaceService.getNamespaceURI(prefix);
        result = "{" + url + "}" + shorname;
        return result;
    }
    catch (Exception e)
    {
        throw new WebScriptException(Status.STATUS_NOT_FOUND, "The exact classname - " + prefix + ":" + shorname + "  parameter has not been provided in the URL");
    }
}
 
Example 20
protected void follow(String user1, String user2) throws Exception
{
    JSONArray jsonUsers = new JSONArray();
    jsonUsers.put(user2);

    String url = getUrl(URL_FOLLOW, user1);
    sendRequest(new PostRequest(url, jsonUsers.toString(), "application/json"), Status.STATUS_NO_CONTENT);
}
 
Example 21
protected int getFollowersCount(String user) throws Exception
{
    String url = getUrl(URL_FOLLOWERS_COUNT, user);
    Response response = sendRequest(new GetRequest(url), Status.STATUS_OK);

    JSONObject resultObject = new JSONObject(response.getContentAsString());
    assertTrue(resultObject.has("count"));

    return resultObject.getInt("count");
}
 
Example 22
@Override
protected QName getClassQname(String namespacePrefix, String name)
{
    String className = namespacePrefix + "_" + name;
    if(isValidClassname(className) == false)
    {
        throw new WebScriptException(Status.STATUS_NOT_FOUND, "Check the name - " + name + "parameter in the URL");
    }
    return QName.createQName(getFullNamespaceURI(className));
}
 
Example 23
/**
 * Builds up a listing Paging request, based on the arguments
 *  specified in the URL
 */
protected PagingRequest buildPagingRequest(WebScriptRequest req)
{
   if (req.getParameter("page") == null || req.getParameter("pageSize") == null)
   {
      throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Paging size parameters missing");
   }
   return new ScriptPagingDetails(req, 100);
}
 
Example 24
protected String getExtensionModule(InputStream inputStream, String fileName)
{
    Element rootElement = null;
    try
    {
        final DocumentBuilder db = XMLUtil.getDocumentBuilder();
        rootElement = db.parse(inputStream).getDocumentElement();
    }
    catch (IOException io)
    {
        throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "cmm.rest_api.model.import_process_ext_module_file_failure", io);
    }
    catch (SAXException ex)
    {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "cmm.rest_api.model.import_invalid_ext_module_entry", new Object[] { fileName }, ex);
    }

    if (rootElement != null && SHARE_EXT_MODULE_ROOT_ELEMENT.equals(rootElement.getNodeName()))
    {
        StringWriter sw = new StringWriter();
        XMLUtil.print(rootElement, sw, false);

        return sw.toString();
    }

    return null;
}
 
Example 25
@Override
protected QName getClassQname(WebScriptRequest req)
{
    String classPrefix = req.getServiceMatch().getTemplateVars().get(DICTIONARY_PREFIX);
    String shortClassName = req.getServiceMatch().getTemplateVars().get(DICTIONARY_SHORT_CLASS_NAME);
    
    //validate the classname
    if(isValidClassname(classPrefix, shortClassName) == false)
    {
        throw new WebScriptException(Status.STATUS_NOT_FOUND, "Check the classname - " + classPrefix + ":" + shortClassName + " - parameter in the URL");
    }
   
    return QName.createQName(getFullNamespaceURI(classPrefix, shortClassName));
}
 
Example 26
public void testGetRestrictions() throws Exception
{
    RepoUsage restrictions = repoAdminService.getRestrictions();
    
    String url = "/api/admin/restrictions";
    TestWebScriptServer.GetRequest req = new TestWebScriptServer.GetRequest(url);
    
    Response response = sendRequest(req, Status.STATUS_OK, guest);
    JSONObject json = new JSONObject(response.getContentAsString());
    Long maxUsers = json.isNull(AbstractAdminWebScript.JSON_KEY_USERS) ? null : json.getLong(AbstractAdminWebScript.JSON_KEY_USERS);
    assertEquals("Mismatched max users", restrictions.getUsers(), maxUsers);
    Long maxDocuments = json.isNull(AbstractAdminWebScript.JSON_KEY_DOCUMENTS) ? null : json.getLong(AbstractAdminWebScript.JSON_KEY_DOCUMENTS);
    assertEquals("Mismatched max documents", restrictions.getDocuments(), maxDocuments);
}
 
Example 27
@Override
protected QName getClassQname(String namespacePrefix, String name)
{
    if(isValidClassname(namespacePrefix, name) == false)
    {
        throw new WebScriptException(Status.STATUS_NOT_FOUND, "Check the name - " + name + "parameter in the URL");
    }
    return QName.createQName(getFullNamespaceURI(namespacePrefix, name));
}
 
Example 28
/**
 * Override method from AbstractClassGet
 */
@Override
protected QName getClassQname(WebScriptRequest req)
{
    String prefix = req.getServiceMatch().getTemplateVars().get(DICTIONARY_PREFIX);
    String shortName = req.getServiceMatch().getTemplateVars().get(DICTIONARY_SHORT_CLASS_NAME);
    
    //validate the classname and throw appropriate error message
    if (isValidClassname(prefix, shortName) == false)
    {
        throw new WebScriptException(Status.STATUS_NOT_FOUND, "Check the classname - " + prefix + ":" + shortName + " - parameter in the URL");
    }
    return QName.createQName(getFullNamespaceURI(prefix, shortName));
}
 
Example 29
/**
 * Creates an event, with the date properties manually set
 */
private JSONObject createEntry(String name, String where, String description, 
      JSONObject datesJSON, int expectedStatus) throws Exception
{
   JSONObject json = new JSONObject();
   
   json.put("site", SITE_SHORT_NAME_CALENDAR);
   json.put("what", name);
   json.put("where", where);
   json.put("desc", description);
   json.put("tags", "");
   json.put("docfolder", "");
   json.put("page", "calendar");
   
   // Copy in the date properties
   for (String key : getKeys(datesJSON, false))
   {
      json.put(key, datesJSON.get(key));
   }
   
   Response response = sendRequest(new PostRequest(URL_EVENT_CREATE, json.toString(), "application/json"), expectedStatus);
   if (expectedStatus == Status.STATUS_OK)
   {
      JSONObject result = validateAndParseJSON(response.getContentAsString());
      if (result.has("event"))
      {
         return result.getJSONObject("event");
      }
      return result;
   }
   else
   {
      return null;
   }
}
 
Example 30
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;
   }
}