Java Code Examples for org.springframework.extensions.webscripts.WebScriptRequest#getParameter()

The following examples show how to use org.springframework.extensions.webscripts.WebScriptRequest#getParameter() . 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: SearchEngines.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status)
{
    String urlType = req.getParameter("type");
    if (urlType == null || urlType.length() == 0)
    {
        urlType = URL_ARG_DESCRIPTION;
    }
    else if (!urlType.equals(URL_ARG_DESCRIPTION) && !urlType.equals(URL_ARG_TEMPLATE) && !urlType.equals(URL_ARG_ALL))
    {
        urlType = URL_ARG_DESCRIPTION;
    }
            
    //
    // retrieve open search engines configuration
    //

    Set<UrlTemplate> urls = getUrls(urlType);
    Map<String, Object> model = new HashMap<String, Object>(7, 1.0f);
    model.put("urltype", urlType);
    model.put("engines", urls);
    return model;
}
 
Example 2
Source File: AlfrescoModelGet.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void handle(WebScriptRequest req, WebScriptResponse res) throws JSONException, IOException
{
    // create map of template vars
    String modelQName = req.getParameter("modelQName");
    if(modelQName == null)
    {
        throw new WebScriptException(
                Status.STATUS_BAD_REQUEST,
                "URL parameter 'modelQName' not provided.");
    }

    ModelDefinition.XMLBindingType bindingType = ModelDefinition.XMLBindingType.DEFAULT;
    AlfrescoModel model = solrTrackingComponent.getModel(QName.createQName(modelQName));
    res.setHeader("XAlfresco-modelChecksum", String.valueOf(model.getModelDef().getChecksum(bindingType)));
    model.getModelDef().toXML(bindingType, res.getOutputStream());
}
 
Example 3
Source File: Login.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status)
{
    // extract username and password
    String username = req.getParameter("u");
    if (username == null || username.length() == 0)
    {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Username not specified");
    }
    String password = req.getParameter("pw");
    if (password == null)
    {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Password not specified");
    }

    try
    {
        return login(username, password);
    }
    catch(WebScriptException e)
    {
        status.setCode(e.getStatus());
        status.setMessage(e.getMessage());
        status.setRedirect(true);
        return null;
    }
}
 
Example 4
Source File: SiteAdminSitesGet.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
private int getIntParameter(WebScriptRequest req, String paramName, int defaultValue)
{
    String paramString = req.getParameter(paramName);

    if (paramString != null)
    {
        try
        {
            int param = Integer.valueOf(paramString);

            if (param >= 0)
            {
                return param;
            }
        }
        catch (NumberFormatException e)
        {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    return defaultValue;
}
 
Example 5
Source File: ReplicationDefinitionsGet.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected Map<String, Object> buildModel(ReplicationModelBuilder modelBuilder, 
                                         WebScriptRequest req, Status status, Cache cache)
{
    // Get all the defined replication definitions
    List<ReplicationDefinition> definitions = replicationService.loadReplicationDefinitions();
    
    // How do we need to sort them?
    Comparator<Map<String,Object>> sorter = new ReplicationModelBuilder.SimpleSorterByName();
    String sort = req.getParameter("sort");
    if(sort == null) {
       // Default was set above
    } else if(sort.equalsIgnoreCase("status")) {
       sorter = new ReplicationModelBuilder.SimpleSorterByStatus();
    } else if(sort.equalsIgnoreCase("lastRun") ||
          sort.equalsIgnoreCase("lastRunTime")) {
       sorter = new ReplicationModelBuilder.SimpleSorterByLastRun();
    }
    
    // Have them turned into simple models
    return modelBuilder.buildSimpleList(definitions, sorter);
}
 
Example 6
Source File: AbstractCommentsWebScript.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * returns SiteInfo needed for post activity
 * @param req
 * @return
 */
protected SiteInfo getSiteInfo(WebScriptRequest req, boolean searchForSiteInJSON)
{
    String siteName = req.getParameter(JSON_KEY_SITE);

    if (siteName == null && searchForSiteInJSON )
    {
        JSONObject json = parseJSON(req);
        if (json != null){
            if (json.containsKey(JSON_KEY_SITE))
            {
                siteName = (String) json.get(JSON_KEY_SITE);
            }
            else if (json.containsKey(JSON_KEY_SITE_ID))
            {
                siteName = (String) json.get(JSON_KEY_SITE_ID);
            }
        }
    }
    if (siteName != null)
    {
        SiteInfo site = siteService.getSite(siteName);
        return site;
    }

    return null;
}
 
Example 7
Source File: AbstractLinksWebScript.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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 8
Source File: InviteResponse.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected Map<String, Object> executeImpl(final WebScriptRequest req, final Status status)
{
    String tenantDomain = TenantService.DEFAULT_DOMAIN;
    final String inviteeUserName = req.getParameter(PARAM_INVITEE_USER_NAME);
    
    if (tenantService.isEnabled())
    {
        if (inviteeUserName != null)
        {
            tenantDomain = tenantService.getUserDomain(inviteeUserName);
        }
    }
    
    // run as system user
    return TenantUtil.runAsSystemTenant(new TenantRunAsWork<Map<String, Object>>()
    {
        public Map<String, Object> doWork() throws Exception
        {
            String oldUser = null;
            try
            {
                if (inviteeUserName != null && !inviteeUserName.equals(oldUser))
                {
                    oldUser = AuthenticationUtil.getFullyAuthenticatedUser();
                    AuthenticationUtil.setFullyAuthenticatedUser(inviteeUserName);
                }
                return execute(req, status);
            }
            finally
            {
                if (oldUser != null && !oldUser.equals(inviteeUserName))
                {
                    AuthenticationUtil.setFullyAuthenticatedUser(oldUser);
                }
            }
        }
    }, tenantDomain);
}
 
Example 9
Source File: RunningReplicationActionsPost.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected Action identifyAction(WebScriptRequest req, Status status,
      Cache cache) {
   // Which action did they ask for?
   String name = req.getParameter("name");
   if(name == null) {
      try {
         JSONObject json = new JSONObject(new JSONTokener(req.getContent().getContent()));
         if(! json.has("name")) {
            throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not find required 'name' parameter");
         }
         name = json.getString("name");
      }
      catch (IOException iox)
      {
          throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not read content from request.", iox);
      }
      catch (JSONException je)
      {
          throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not parse JSON from request.", je);
      }
   }
   
   // Load the specified replication definition
   ReplicationDefinition replicationDefinition = 
      replicationService.loadReplicationDefinition(name);
   return replicationDefinition;
}
 
Example 10
Source File: InviteByTicket.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected Map<String, Object> executeImpl(final WebScriptRequest req, final Status status)
{
    String tenantDomain = TenantService.DEFAULT_DOMAIN;
    
    if (tenantService.isEnabled())
    {
        String inviteeUserName = req.getParameter(PARAM_INVITEE_USER_NAME);
        if (inviteeUserName != null)
        {
            tenantDomain = tenantService.getUserDomain(inviteeUserName);
        }
    }
    
    // run as system user
    String mtAwareSystemUser = tenantService.getDomainUser(AuthenticationUtil.getSystemUserName(), tenantDomain);
    
    Map<String, Object> ret = TenantUtil.runAsSystemTenant(new TenantRunAsWork<Map<String, Object>>()
    {
        public Map<String, Object> doWork() throws Exception
        {
            return execute(req, status);
        }
    }, tenantDomain);
    
    // authenticate as system for the rest of the webscript
    AuthenticationUtil.setRunAsUser(mtAwareSystemUser);
    
    return ret;
}
 
Example 11
Source File: RunningActionsPost.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected Action identifyAction(WebScriptRequest req, Status status,
      Cache cache) {
   // Which action did they ask for?
   String nodeRef = req.getParameter("nodeRef");
   if(nodeRef == null) {
      try {
         JSONObject json = new JSONObject(new JSONTokener(req.getContent().getContent()));
         if(! json.has("nodeRef")) {
            throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not find required 'nodeRef' parameter");
         }
         nodeRef = json.getString("nodeRef");
      }
      catch (IOException iox)
      {
          throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not read content from request.", iox);
      }
      catch (JSONException je)
      {
          throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not parse JSON from request.", je);
      }
   }
   
   // Does it exist in the repo?
   NodeRef actionNodeRef = new NodeRef(nodeRef);
   if(! nodeService.exists(actionNodeRef)) {
      return null;
   }
   
   // Load the specified action
   Action action = runtimeActionService.createAction(actionNodeRef);
   return action;
}
 
Example 12
Source File: WorkflowDefinitionsGet.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected Map<String, Object> buildModel(WorkflowModelBuilder modelBuilder, WebScriptRequest req, Status status, Cache cache)
{
    ExcludeFilter excludeFilter = null;
    String excludeParam = req.getParameter(PARAM_EXCLUDE);
    if (excludeParam != null && excludeParam.length() > 0)
    {
        excludeFilter = new ExcludeFilter(excludeParam);
    }
    
    // list all workflow's definitions simple representation
    List<WorkflowDefinition> workflowDefinitions = workflowService.getDefinitions();            
        
    ArrayList<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
    
    for (WorkflowDefinition workflowDefinition : workflowDefinitions)            
    {
        // if present, filter out excluded definitions
        if (excludeFilter == null || !excludeFilter.isMatch(workflowDefinition.getName()))
        {
            results.add(modelBuilder.buildSimple(workflowDefinition));
        }
    }
    
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("workflowDefinitions", results);
    return model;
}
 
Example 13
Source File: TaskInstancesGet.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Retrieves the list of property names to include in the response.
 * 
 * @param req The WebScript request
 * @return List of property names
 */
private List<String> getProperties(WebScriptRequest req)
{
    String propertiesStr = req.getParameter(PARAM_PROPERTIES);
    if (propertiesStr != null)
    {
        return Arrays.asList(propertiesStr.split(","));
    }
    return null;
}
 
Example 14
Source File: TaskInstancesGet.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Retrieves the pooledTasks parameter.
 * 
 * @param req The WebScript request
 * @return null if not present, Boolean object otherwise
 */
private Boolean getPooledTasks(WebScriptRequest req)
{
    Boolean result = null;
    String includePooledTasks = req.getParameter(PARAM_POOLED_TASKS);
    
    if (includePooledTasks != null)
    {
        result = Boolean.valueOf(includePooledTasks);
    }
    
    return result;
}
 
Example 15
Source File: ForumTopicsFilteredGet.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @param site SiteInfo
 * @param nodeRef Not required. It is only included because it is overriding the parent class.
 * @param topic Not required. It is only included because it is overriding the parent class.
 * @param post Not required. It is only included because it is overriding the parent class.
 * @param req WebScriptRequest
 * @param status Not required. It is only included because it is overriding the parent class.
 * @param cache Not required. It is only included because it is overriding the parent class.
 * 
 * @return Map
 */
@Override
protected Map<String, Object> executeImpl(SiteInfo site, NodeRef nodeRef, TopicInfo topic,
      PostInfo post, WebScriptRequest req, JSONObject json, Status status, Cache cache)
{
   // They shouldn't be trying to list of an existing Post or Topic
   if (topic != null || post != null)
   {
      String error = "Can't list Topics inside an existing Topic or Post";
      throw new WebScriptException(Status.STATUS_BAD_REQUEST, error);
   }

   // Set search filter to users topics or all topics
   String pAuthor = req.getParameter("topics");
   String author = DEFAULT_TOPIC_AUTHOR;
   if (pAuthor != null)
   {
      author = pAuthor;  
   }
   // Set the number of days in the past to search from 
   String pDaysAgo = req.getParameter("history");
   int daysAgo = DEFAULT_TOPIC_LATEST_POST_DAYS_AGO;
   if (pDaysAgo != null)
   {
      try
      {
         daysAgo = Integer.parseInt(pDaysAgo);
      }
      catch (NumberFormatException e)
      {
         //do nothing. history has already been preset to the default value.
      }  
   }
   
   // Get the complete search query
   Pair<String, String> searchQuery = getSearchQuery(site, author, daysAgo);

   // Get the filtered topics
   PagingRequest paging = buildPagingRequest(req);
   PagingResults<TopicInfo> topics = doSearch(searchQuery, false, paging);

   // Build the common model parts
   Map<String, Object> model = buildCommonModel(site, topic, post, req);

   // Have the topics rendered
   model.put("data", renderTopics(topics, paging, site));

   // All done
   return model;
}
 
Example 16
Source File: AbstractDiscussionWebScript.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Generates an activity entry for the discussion item
 * 
 * @param thing Either post or reply
 * @param event One of created, updated, deleted
 */
protected void addActivityEntry(String thing, String event, TopicInfo topic, 
      PostInfo post, SiteInfo site, WebScriptRequest req, JSONObject json)
{
   // We can only add activities against a site
   if (site == null)
   {
      logger.info("Unable to add activity entry for " + thing + " " + event + " as no site given");
      return;
   }
   
   // What page is this for?
   String page = req.getParameter("page");
   if (page == null && json != null)
   {
      if (json.containsKey("page"))
      {
         page = (String)json.get("page");
      }
   }
   if (page == null)
   {
      // Default
      page = "discussions-topicview";
   }
   
   // Get the title
   String title = topic.getTitle();
   if (post != null)
   {
      String postTitle = post.getTitle();
      if (postTitle != null && postTitle.length() > 0)
      {
         title = postTitle;
      }
   }
   
   try
   {
      JSONObject params = new JSONObject();
      params.put("topicId", topic.getSystemName());
      
      JSONObject activity = new JSONObject();
      activity.put("title", title);
      activity.put("page", page + "?topicId=" + topic.getSystemName());
      activity.put("params", params);
      
      activityService.postActivity(
            "org.alfresco.discussions." + thing + "-" + event,
            site.getShortName(),
            DISCUSSIONS_SERVICE_ACTIVITY_APP_NAME,
            activity.toString());
   }
   catch(Exception e)
   {
      // Warn, but carry on
      logger.warn("Error adding discussions " + thing + " " + event + " to activities feed", e);
   }
}
 
Example 17
Source File: DeleteSpaceWebScript.java    From alfresco-bulk-import with Apache License 2.0 4 votes vote down vote up
/**
 * @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        = null;
    String              targetPath    = null;
    NodeRef             targetNodeRef = null;
    
    cache.setNeverCache(true);
    
    try
    {
        targetPath = request.getParameter(PARAMETER_TARGET_PATH);

        if (targetPath == null || targetPath.trim().length() == 0)
        {
            throw new RuntimeException("Error: parameter '" + PARAMETER_TARGET_PATH + "' was not provided.");
        }
        
        targetPath    = targetPath.trim();
        targetNodeRef = convertPathToNodeRef(serviceRegistry, targetPath);
        
        fastDeleteSpace(targetPath, targetNodeRef);
        
    }
    catch (final WebScriptException wse)
    {
        throw wse;
    }
    catch (final FileNotFoundException fnfe)
    {
        throw new WebScriptException(Status.STATUS_NOT_FOUND, "The path " + targetPath + " does not exist.", fnfe);
    }
    catch (final Throwable t)
    {
        throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, buildTextMessage(t), t);
    }
    
    // If successful, redirect back to the delete GET Web Script
    status.setCode(Status.STATUS_MOVED_TEMPORARILY);
    status.setRedirect(true);
    status.setLocation(request.getServiceContextPath() + WEB_SCRIPT_URI_DELETE_SPACE);
    
    return(result);
}
 
Example 18
Source File: ForumPostRepliesGet.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected Map<String, Object> executeImpl(SiteInfo site, NodeRef nodeRef,
      TopicInfo topic, PostInfo post, WebScriptRequest req, JSONObject json,
      Status status, Cache cache) 
{
   // How many levels did they want?
   int levels = 1;
   String levelsS = req.getParameter("levels");
   if (levelsS != null)
   {
      try
      {
         levels = Integer.parseInt(levelsS);
      }
      catch (NumberFormatException e)
      {
         throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Level depth parameter invalid");
      }
   }
   
   // Fetch the replies
   PostWithReplies replies;
   if (post != null)
   {
      replies = discussionService.listPostReplies(post, levels);
   }
   else if (topic != null)
   {
      replies = discussionService.listPostReplies(topic, levels);
   }
   else 
   {
      String error = "Node was of the wrong type, only Topic and Post are supported";
      throw new WebScriptException(Status.STATUS_BAD_REQUEST, error);
   }
   
   // Build the common model parts
   Map<String, Object> model = buildCommonModel(site, topic, post, req);
   
   // Build the JSON for the replies
   model.put("data", renderReplies(replies, site).get("children"));  
   
   // All done
   return model;
}
 
Example 19
Source File: SolrFacetConfigAdminPut.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected Map<String, Object> unprotectedExecuteImpl(WebScriptRequest req, Status status, Cache cache)
{
    final String relativePosString = req.getParameter(PARAM_RELATIVE_POS);
    try
    {
        if (relativePosString != null)
        {
            // This is a request to 'move' (reposition) the specified facet.
            
            // We need the relative position that the facet will move.
            final int relativePos;
            
            try { relativePos = Integer.parseInt(relativePosString); }
            catch (NumberFormatException nfe)
            {
                throw new WebScriptException(Status.STATUS_BAD_REQUEST,
                                             "Cannot move facet as could not parse relative position: '" + relativePosString + "'");
            }
            
            // And we need the filterID for the facet we're moving.
            final Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
            String filterId = templateVars.get(URL_PARAM_FILTER_ID);
            
            if (filterId == null) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Illegal null filterId"); }
            
            // So let's move the filter...
            try
            {
                // Get the current sequence of filter IDs.
                List<SolrFacetProperties> facets = facetService.getFacets();
                List<String> facetIDs = CollectionUtils.transform(facets, new Function<SolrFacetProperties, String>()
                        {
                            @Override public String apply(SolrFacetProperties value)
                            {
                                return value.getFilterID();
                            }
                        });
                
                List<String> reorderedIDs = CollectionUtils.moveRight(relativePos, filterId, facetIDs);
                
                this.facetService.reorderFacets(reorderedIDs);
                
                if (logger.isDebugEnabled()) { logger.debug("Moved facet " + filterId + " to relative position: " + relativePos); }
            }
            catch (UnrecognisedFacetId ufi)
            {
                throw new WebScriptException(Status.STATUS_NOT_FOUND, "Unrecognised filter ID: " + ufi.getFacetId());
            }
        }
        // TODO Allow for simultaneous move and update of facet.
        else
        {
            SolrFacetProperties fp = parseRequestForFacetProperties(req);
            facetService.updateFacet(fp);
            
            if (logger.isDebugEnabled())
            {
                logger.debug("Updated facet node: " + fp);
            }
        }
    }
    catch (Throwable t)
    {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not update the facet configuration.", t);
    }

    Map<String, Object> model = new HashMap<String, Object>(1);
    return model;
}
 
Example 20
Source File: StatsGet.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) 
{
   Map<String, Object> model = new HashMap<String, Object>(2, 1.0f);
   Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
   SiteInfo siteInfo = null;
   
   String listFacets = req.getParameter("listFacets");
   if (listFacets != null)
   {
       model.put("facets", facets.keySet());
       model.put("resultSize", 0);
       return model;
   }
   
   if (templateVars != null && templateVars.containsKey("siteId") )
   {
     siteInfo = siteService.getSite(templateVars.get("siteId"));
     if (siteInfo == null)
     {
         throw new AccessDeniedException("No such site: " + templateVars.get("siteId"));
     }
   }

   String facetKey = req.getParameter("facet");
   if (facetKey == null) facetKey = facets.entrySet().iterator().next().getKey();  //default
   String query;
   
   QName propFacet = findFacet(facetKey);
   Pair<LocalDate, LocalDate> startAndEnd = getStartAndEndDates(req.getParameter("startDate"),req.getParameter("endDate"));
   query = buildQuery(siteInfo, facetKey, startAndEnd);

   StatsParameters params = new StatsParameters(SearchService.LANGUAGE_SOLR_FTS_ALFRESCO, query, false);
   //params.addSort(new SortDefinition(SortDefinition.SortType.FIELD, this.statsField, false));
   params.addStatsParameter(StatsParameters.PARAM_FIELD, this.statsField);
   params.addStatsParameter(StatsParameters.PARAM_FACET, StatsParameters.FACET_PREFIX+propFacet.toString());
  
   StatsResultSet result = stats.query(params);
   
   if (postProcessors.containsKey(facetKey))
   {
       StatsProcessor processor = postProcessors.get(facetKey);
       result = processor.process(result);
   }
   model.put("result", result);
   model.put("resultSize", result.getStats().size());
   return model;
}