@Test
  public void testDeleteExtractor() throws IOException {
    ParamsExtractor extractor = new ResourceWebScriptDelete();
    Map<String, String> templateVars = new HashMap<String, String>();

    WebScriptRequest request = mock(WebScriptRequest.class);
    when(request.getServiceMatch()).thenReturn(new Match(null, templateVars, null));

    Params params = null;
    try {
      params = extractor.extractParams(mockEntity(), request);
      fail("Should not get here. DELETE is executed against the instance URL");
    } catch (UnsupportedResourceOperationException uoe) {
      assertNotNull(uoe); // Must throw this exception
    }

    templateVars.put(ResourceLocator.ENTITY_ID, "1234");
    try {
      params = extractor.extractParams(mockRelationship(), request);
      fail("Should not get here. DELETE is executed against the instance URL");
    } catch (UnsupportedResourceOperationException uoe) {
      assertNotNull(uoe); // Must throw this exception
    }
    templateVars.put(ResourceLocator.RELATIONSHIP_ID, "45678");
    params = extractor.extractParams(mockRelationship(), request);
    assertNotNull(params);
    assertEquals("1234", params.getEntityId());
    assertEquals("45678", params.getRelationshipId());
    assertNotNull(params.getFilter());
    assertTrue(
        "Default filter is BeanPropertiesFilter.AllProperties",
        BeanPropertiesFilter.AllProperties.class.equals(params.getFilter().getClass()));

    testExtractAddressedParams(templateVars, request, extractor);
  }
  @Test
  public void testGetExtractor() {
    ParamsExtractor extractor = new ResourceWebScriptGet();
    Map<String, String> templateVars = new HashMap<String, String>();
    WebScriptRequest request = mock(WebScriptRequest.class);
    when(request.getServiceMatch()).thenReturn(new Match(null, templateVars, null));

    Params params = extractor.extractParams(mockEntity(), request);
    assertNull("For getting a Collection there should be no entity params.", params.getEntityId());
    assertNull("For getting a Collection there should be no passed params.", params.getPassedIn());
    assertNull(
        "For getting a Collection there should be no relationshipId params.",
        params.getRelationshipId());
    assertEquals(Paging.DEFAULT_SKIP_COUNT, params.getPaging().getSkipCount());
    assertEquals(Paging.DEFAULT_MAX_ITEMS, params.getPaging().getMaxItems());
    assertNotNull(params.getFilter());
    assertTrue(
        "Default filter is BeanPropertiesFilter.AllProperties",
        BeanPropertiesFilter.AllProperties.class.equals(params.getFilter().getClass()));

    templateVars.put(ResourceLocator.ENTITY_ID, "1234");
    params = extractor.extractParams(mockEntity(), request);
    assertNotNull(params);
    assertNotNull(params.getRelationsFilter());

    templateVars.put(ResourceLocator.RELATIONSHIP_ID, "45678");
    params = extractor.extractParams(mockRelationship(), request);
    assertNotNull(params);
    assertEquals("1234", params.getEntityId());
    assertEquals("45678", params.getRelationshipId());

    testExtractAddressedParams(templateVars, request, extractor);
  }
  public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {

    final String value = req.getParameter(P_VALUE);
    NodeRef nodeRef = null;
    if (null != value && NodeRef.isNodeRef(value)) {
      nodeRef = new NodeRef(value);
    }

    final String engine = req.getParameter(P_ENGINE);

    String mimetype = req.getParameter(P_MIMETYPE);
    mimetype = null == mimetype ? D_MIMETYPE : mimetype;

    final ByteArrayOutputStream output = new ByteArrayOutputStream();

    if (req.getServerPath().contains("/new")) {

      final String reference = referenceProviderService.getNewReference(engine, null);
      generateBarcode(reference, output, mimetype);

    } else {

      String barcodeValue = value;

      if (null != nodeRef) {
        barcodeValue = referenceProviderService.getExistingReference(nodeRef);
      }

      if (null != value && !value.isEmpty()) {
        generateBarcode(barcodeValue, output, mimetype);
      } else {
        logger.debug(String.format("No barcode generated for value '%s'", value));
      }
    }

    res.setContentType(mimetype);
    // res.setContentEncoding(reader.getEncoding());
    res.setHeader("Content-Length", Long.toString(output.size()));

    // get the content and stream directly to the response output stream
    // assuming the repository is capable of streaming in chunks, this should allow large files
    // to be streamed directly to the browser response stream.
    try {
      res.getOutputStream().write(output.toByteArray());
    } catch (SocketException e1) {
      // the client cut the connection - our mission was accomplished apart from a little error
      // message
      if (logger.isInfoEnabled()) logger.info("Client aborted stream read.");
    } catch (ContentIOException e2) {
      if (logger.isInfoEnabled()) logger.info("Client aborted stream read.");
    }
  }
  /*
   * @see org.alfresco.web.scripts.DeclarativeWebScript#executeImpl(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.Status, org.alfresco.web.scripts.Cache)
   */
  @Override
  protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    // create model object with the lists model
    Map<String, Object> model = new HashMap<String, Object>(1);

    boolean extended = false;
    String result = "NONE";

    // Get the nodeRef and confirm it is valid
    String nodeRef = req.getParameter(PARAM_NODEREF);
    if (nodeRef == null || nodeRef.length() == 0) {
      String type = req.getParameter(PARAM_TYPE);
      if (type != null && type.length() != 0 && type.indexOf(':') != -1) {
        Matcher m = QNAME_PATTERN.matcher(type);
        if (m.matches()) {
          QName qname = QName.createQName(type, namespaceService);
          FilePlanComponentKind kind = filePlanService.getFilePlanComponentKindFromType(qname);
          if (kind != null) {
            result = kind.toString();
          }
        }
      }
    } else {
      // quick test before running slow match for full NodeRef pattern
      if (nodeRef.indexOf(':') != -1) {
        Matcher m = NODE_REF_PATTERN.matcher(nodeRef);
        if (m.matches()) {
          NodeRef nodeRefObj = new NodeRef(nodeRef);

          FilePlanComponentKind kind = filePlanService.getFilePlanComponentKind(nodeRefObj);
          if (kind != null) {
            result = kind.toString();
          }

          String extendedValue = req.getParameter(PARAM_EXTENDED);
          if (extendedValue != null && extendedValue.length() != 0) {
            extended = Boolean.parseBoolean(extendedValue);
            if (extended) {
              // get the aspects of the node
              model.put("aspects", getAspects(nodeRefObj));
            }
          }
        }
      }
    }

    model.put("kind", result);
    model.put("extended", extended);
    return model;
  }
示例#5
0
  @Override
  public Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    Map<String, Object> model = new HashMap<String, Object>();
    JSONObject json = null;
    try {
      // Role name
      Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
      String roleParam = templateVars.get("rolename");
      if (roleParam == null) {
        throw new WebScriptException(
            Status.STATUS_NOT_FOUND, "No role name was provided on the URL.");
      }

      json = new JSONObject(new JSONTokener(req.getContent().getContent()));
      String name = json.getString("name");
      // TODO check
      String displayLabel = json.getString("displayLabel");
      // TODO check

      JSONArray capabilitiesArray = json.getJSONArray("capabilities");
      Set<Capability> capabilites = new HashSet<Capability>(capabilitiesArray.length());
      for (int i = 0; i < capabilitiesArray.length(); i++) {
        Capability capability = rmSecurityService.getCapability(capabilitiesArray.getString(i));
        capabilites.add(capability);
      }

      List<NodeRef> roots = rmService.getRecordsManagementRoots();
      NodeRef root = roots.get(0);

      // Check that the role exists
      if (rmSecurityService.existsRole(root, roleParam) == false) {
        throw new WebScriptException(
            Status.STATUS_NOT_FOUND,
            "The role " + roleParam + " does not exist on the records managment root " + root);
      }

      Role role = rmSecurityService.updateRole(root, name, displayLabel, capabilites);
      model.put("role", role);

    } catch (IOException iox) {
      throw new WebScriptException(
          Status.STATUS_BAD_REQUEST, "Could not read content from req.", iox);
    } catch (JSONException je) {
      throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not parse JSON from req.", je);
    }

    return model;
  }
  @Override
  protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    Map<String, Object> result = new HashMap<String, Object>();
    Map<String, String> templateArgs = req.getServiceMatch().getTemplateVars();
    String placeShortName = templateArgs.get("placeShortName");

    Site placeToMigrate = null;
    try {
      placeToMigrate = bulkImportSiteService.getSite(placeShortName);
    } catch (URISyntaxException e) {
      throw new WebScriptException(
          Status.STATUS_NOT_FOUND, "Failed to find site with shortName " + placeShortName, e);
    } catch (InvalidPropertiesFormatException e) {
      throw new WebScriptException(
          Status.STATUS_BAD_REQUEST, "Unable to parse properties for site " + placeShortName, e);
    } catch (IOException e) {
      throw new WebScriptException(
          Status.STATUS_BAD_REQUEST,
          "Unable to read properties file for site " + placeShortName,
          e);
    }

    try {
      bulkImportSiteService.importSite(placeToMigrate);
    } catch (Exception e) {
      throw new WebScriptException(
          Status.STATUS_INTERNAL_SERVER_ERROR,
          "Failed to import place namned " + placeShortName + " into Alfresco",
          e);
    }
    return result;
  }
  @Override
  public void execute(final Api api, WebScriptRequest req, WebScriptResponse res)
      throws IOException {
    final Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();

    ResourceDictionary resourceDic = lookupDictionary.getDictionary();
    Map<String, ResourceWithMetadata> apiResources = resourceDic.getAllResources().get(api);
    if (apiResources == null) {
      throw new InvalidArgumentException(InvalidArgumentException.DEFAULT_INVALID_API);
    }
    String collectionName = templateVars.get(ResourceLocator.COLLECTION_RESOURCE);
    String resourceName = templateVars.get(ResourceLocator.RELATIONSHIP_RESOURCE);
    String resourceKey = ResourceDictionary.resourceKey(collectionName, resourceName);
    if (logger.isDebugEnabled()) {
      logger.debug("Locating resource :" + resourceKey);
    }
    ResourceWithMetadata resource = apiResources.get(resourceKey);
    if (resource == null) {
      // Get entity resource and check if we are referencing a property on it.
      resourceKey = ResourceDictionary.propertyResourceKey(collectionName, resourceName);
      resource = apiResources.get(resourceKey);
    }
    ResourceMetaDataWriter writer = chooseWriter(req);
    writer.writeMetaData(res.getOutputStream(), resource, apiResources);
  }
 /**
  * Chooses the correct writer to use based on the supplied "format" param
  *
  * @param req - the WebScriptRequest
  * @return ResourceMetaDataWriter - a matching writer - DEFAULT is this class.
  */
 protected ResourceMetaDataWriter chooseWriter(WebScriptRequest req) {
   if (writers != null) {
     ResourceMetaDataWriter theWriter = writers.get(req.getParameter("format"));
     if (theWriter != null) return theWriter;
   }
   return this;
 }
示例#9
0
  @Override
  public Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    Map<String, Object> model = new HashMap<String, Object>();

    // Role name
    Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
    String roleParam = templateVars.get("rolename");
    if (roleParam == null) {
      throw new WebScriptException(
          Status.STATUS_NOT_FOUND, "No role name was provided on the URL.");
    }

    List<NodeRef> roots = rmService.getRecordsManagementRoots();
    NodeRef root = roots.get(0);

    // Check that the role exists
    if (rmSecurityService.existsRole(root, roleParam) == false) {
      throw new WebScriptException(
          Status.STATUS_NOT_FOUND,
          "The role " + roleParam + " does not exist on the records managment root " + root);
    }

    rmSecurityService.deleteRole(root, roleParam);

    return model;
  }
示例#10
0
 /**
  * Returns the username for the current user.
  *
  * @param req The webscript request
  * @return THe username of the current user
  */
 protected String getCurrentUserId(WebScriptRequest req) {
   String authorization = req.getHeader("Authorization");
   if (authorization != null) {
     String[] parts = authorization.split(" ");
     if (parts.length == 2) {
       return new String(Base64.decode(parts[1])).split(":")[0];
     }
   }
   return null;
 }
 @Override
 protected JSONObject resolveArgument(WebScriptRequest request, WebScriptResponse response) {
   if (request.getContentType().startsWith(MimetypeMap.MIMETYPE_JSON)) {
     try {
       final String contentText = request.getContent().getContent();
       if (contentText != null) {
         try {
           return new JSONObject(contentText);
         } catch (JSONException e) {
           throw new WebScriptException(
               Status.STATUS_BAD_REQUEST, "Failed to parse JSON body: " + contentText, e);
         }
       }
     } catch (IOException ex) {
       throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Failed to read body content", ex);
     }
   }
   return null;
 }
 @Override
 protected Map<String, Object> executeImpl(WebScriptRequest request, Status status) {
   String graphName = request.getServiceMatch().getTemplateVars().get("graph_name");
   logger.debug("executeImpl - graphName = " + graphName);
   Map<String, Object> model = new HashMap<String, Object>();
   Map<String, StatisticsChartGenerator> chartsByName = getChartGeneratorsToDisplay();
   if (graphName != null) {
     model.put("graph", new Object[] {graphName, chartsByName.get(graphName)});
     ;
   }
   model.put("graph_names", chartsByName.keySet());
   return model;
 }
  /**
   * Retrieves the named paramter as a date.
   *
   * @param req The WebScript request
   * @param paramName The name of parameter to look for
   * @return The request parameter value or null if the parameter is not present
   */
  protected Date getDateParameter(WebScriptRequest req, String paramName) {
    String dateString = req.getParameter(paramName);

    if (dateString != null) {
      try {
        return ISO8601DateFormat.parse(dateString.replaceAll(" ", "+"));
      } catch (Exception e) {
        String msg = "Invalid date value: " + dateString;
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, msg);
      }
    }
    return null;
  }
示例#14
0
  /**
   * Gets the specified {@link WorkflowState}, null if not requested.
   *
   * @param req The WebScript request
   * @return The workflow state or null if not requested
   */
  private WorkflowState getState(WebScriptRequest req) {
    String stateName = req.getParameter(PARAM_STATE);
    if (stateName != null) {
      try {
        return WorkflowState.valueOf(stateName.toUpperCase());
      } catch (IllegalArgumentException e) {
        String msg = "Unrecognised State parameter: " + stateName;
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, msg);
      }
    }

    return null;
  }
示例#15
0
  @Override
  protected Map<String, Object> buildModel(
      WorkflowModelBuilder modelBuilder, WebScriptRequest req, Status status, Cache cache) {
    Map<String, String> params = req.getServiceMatch().getTemplateVars();

    // state is not included into filters list as it will be taken into account before filtering
    WorkflowState state = getState(req);

    // get filter param values
    Map<String, Object> filters = new HashMap<String, Object>(9);
    filters.put(PARAM_INITIATOR, req.getParameter(PARAM_INITIATOR));
    filters.put(PARAM_PRIORITY, req.getParameter(PARAM_PRIORITY));
    filters.put(PARAM_DEFINITION_NAME, req.getParameter(PARAM_DEFINITION_NAME));

    String excludeParam = req.getParameter(PARAM_EXCLUDE);
    if (excludeParam != null && excludeParam.length() > 0) {
      filters.put(PARAM_EXCLUDE, new ExcludeFilter(excludeParam));
    }

    // process all the date related parameters
    processDateFilter(req, PARAM_DUE_BEFORE, filters);
    processDateFilter(req, PARAM_DUE_AFTER, filters);
    processDateFilter(req, PARAM_STARTED_BEFORE, filters);
    processDateFilter(req, PARAM_STARTED_AFTER, filters);
    processDateFilter(req, PARAM_COMPLETED_BEFORE, filters);
    processDateFilter(req, PARAM_COMPLETED_AFTER, filters);

    // determine if there is a definition id to filter by
    String workflowDefinitionId = params.get(VAR_DEFINITION_ID);
    if (workflowDefinitionId == null) {
      workflowDefinitionId = req.getParameter(PARAM_DEFINITION_ID);
    }

    List<WorkflowInstance> workflows;

    // list workflows for specified workflow definition
    if (state == null) {
      workflows = workflowService.getWorkflows(workflowDefinitionId);
    } else if (state == WorkflowState.ACTIVE) {
      workflows = workflowService.getActiveWorkflows(workflowDefinitionId);
    } else {
      workflows = workflowService.getCompletedWorkflows(workflowDefinitionId);
    }

    // sort workflows by due date
    Collections.sort(workflows, workflowComparator);

    // filter result
    List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(workflows.size());

    for (WorkflowInstance workflow : workflows) {
      if (matches(workflow, filters, modelBuilder)) {
        results.add(modelBuilder.buildSimple(workflow));
      }
    }

    // create and return results, paginated if necessary
    return createResultModel(req, "workflowInstances", results);
  }
示例#16
0
  @Override
  protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    Map<String, Object> model = new HashMap<String, Object>();

    // get request parameters
    NodeRef nodeRef = parseRequestForNodeRef(req);
    String ruleType = req.getParameter("ruleType");

    RuleType type = ruleService.getRuleType(ruleType);

    if (type == null) {
      ruleType = null;
    }

    RuleSet ruleset = new RuleSet();

    // get all "owned" rules
    List<Rule> ownedRules = ruleService.getRules(nodeRef, false, ruleType);

    // get all rules (including inherited)
    List<Rule> inheritedRules = ruleService.getRules(nodeRef, true, ruleType);

    // remove "owned" rules
    inheritedRules.removeAll(ownedRules);

    List<RuleRef> rulesToSet = new ArrayList<RuleRef>();

    for (Rule rule : ownedRules) {
      rulesToSet.add(
          new RuleRef(rule, fileFolderService.getFileInfo(ruleService.getOwningNodeRef(rule))));
    }
    ruleset.setRules(rulesToSet);

    List<RuleRef> inheritedRulesToSet = new ArrayList<RuleRef>();

    for (Rule rule : inheritedRules) {
      inheritedRulesToSet.add(
          new RuleRef(rule, fileFolderService.getFileInfo(ruleService.getOwningNodeRef(rule))));
    }
    ruleset.setInheritedRules(inheritedRulesToSet);

    ruleset.setLinkedToRuleSet(ruleService.getLinkedToRuleNode(nodeRef));

    ruleset.setLinkedFromRuleSets(ruleService.getLinkedFromRuleNodes(nodeRef));

    ruleset.setRulesetNodeRef(nodeRef);

    model.put("ruleset", ruleset);

    return model;
  }
示例#17
0
  /**
   * @see
   *     org.springframework.extensions.webscripts.DeclarativeWebScript#executeImpl(org.springframework.extensions.webscripts.WebScriptRequest,
   *     org.springframework.extensions.webscripts.Status,
   *     org.springframework.extensions.webscripts.Cache)
   */
  @Override
  public Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    Map<String, Object> model = new HashMap<String, Object>();
    Set<Role> roles = null;

    // get the file plan
    NodeRef filePlan = getFilePlan(req);
    if (filePlan == null) {
      throw new WebScriptException(Status.STATUS_FOUND, "File plan does not exist.");
    }

    // get the includesystem parameter
    boolean includeSystem = false;
    String includeSystemValue = req.getParameter("is");
    if (includeSystemValue != null && includeSystemValue.length() != 0) {
      includeSystem = Boolean.parseBoolean(includeSystemValue);
    }

    // get the user filter
    String user = req.getParameter("user");
    if (user != null && user.length() != 0) {
      roles = filePlanRoleService.getRolesByUser(filePlan, user, includeSystem);
    } else {
      roles = filePlanRoleService.getRoles(filePlan, includeSystem);
    }

    // get the auths parameter
    boolean showAuths = false;
    String auths = req.getParameter("auths");
    if (auths != null && auths.length() != 0) {
      showAuths = Boolean.parseBoolean(auths);
    }

    Set<RoleItem> items = createRoleItems(filePlan, roles, showAuths);
    model.put("roles", items);
    return model;
  }
  @Override
  protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {

    // Fetching request params
    Map<String, String> templateArgs = req.getServiceMatch().getTemplateVars();
    String storeId = templateArgs.get("storeId");
    String storeProtocol = templateArgs.get("storeProtocol");
    String uuid = templateArgs.get("uuid");

    // Getting the Store ID on which the changes are requested
    Pair<Long, StoreRef> store = nodeDao.getStore(new StoreRef(storeProtocol, storeId));
    if (store == null) {
      throw new IllegalArgumentException(
          "Invalid store reference: " + storeProtocol + "://" + storeId);
    }

    Set<NodeEntity> nodes = new HashSet<NodeEntity>();

    NodeEntity node = indexingService.getNodeByUuid(store, uuid);
    if (node != null) {
      nodes.add(node);
    }

    // Render them out
    Map<String, Object> model = new HashMap<String, Object>(1, 1.0f);
    model.put("qnameDao", qnameDao);
    model.put("nsResolver", namespaceService);
    model.put("nodes", nodes);
    model.put("storeId", storeId);
    model.put("storeProtocol", storeProtocol);
    model.put("propertiesUrlTemplate", propertiesUrlTemplate);

    // This allows to call the static method QName.createQName from the FTL template
    try {
      BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
      TemplateHashModel staticModels = wrapper.getStaticModels();
      TemplateHashModel qnameStatics =
          (TemplateHashModel) staticModels.get("org.alfresco.service.namespace.QName");
      model.put("QName", qnameStatics);
    } catch (Exception e) {
      throw new AlfrescoRuntimeException(
          "Cannot add BeansWrapper for static QName.createQName method to be used from a Freemarker template",
          e);
    }

    logger.debug(String.format("Attaching %s nodes to the WebScript template", nodes.size()));

    return model;
  }
  /**
   * Processes the given date filter parameter from the provided webscript request.
   *
   * <p>If the parameter is present but set to an empty string or to "null" the date is added to the
   * given filters Map as "", if the parameter contains an ISO8601 date it's added as a Date object
   * to the filters.
   *
   * @param req The WebScript request
   * @param paramName The name of the parameter to look for
   * @param filters Map of filters to add the date to
   */
  protected void processDateFilter(
      WebScriptRequest req, String paramName, Map<String, Object> filters) {
    // TODO: support other keywords i.e. today, tomorrow

    String dateParam = req.getParameter(paramName);
    if (dateParam != null) {
      Object date = EMPTY;

      if (!EMPTY.equals(dateParam) && !NULL.equals(dateParam)) {
        date = getDateParameter(req, paramName);
      }

      filters.put(paramName, date);
    }
  }
  /** {@inheritDoc} */
  @Override
  protected Map<String, Object> executeImpl(final WebScriptRequest req, final Status status) {
    final String visibleStr = req.getParameter("visible");
    final boolean visible = Boolean.parseBoolean(visibleStr);

    if (visible) {
      this.debugger.activate();
    } else {
      this.debugger.shutdown();
    }

    final Map<String, Object> model = new HashMap<String, Object>(7, 1.0f);
    model.put("visible", Boolean.valueOf(this.debugger.isActive()));
    return model;
  }
  @Override
  protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    // Check we got a valid Multi-Part Form Upload
    FormData form = (FormData) req.parseContent();
    if (form == null || !form.getIsMultiPart()) {
      throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Bad Upload");
    }

    // Look for a file, we're quite flexible!
    File spreadsheet = null;
    for (FormData.FormField field : form.getFields()) {
      if (field.getIsFile()) {
        String ext = ".xls";
        if (field.getFilename() != null && field.getFilename().endsWith(".xlsx")) {
          ext = ".xlsx";
        }

        try {
          spreadsheet = TempFileProvider.createTempFile("spreadsheet", ext);
          FileOutputStream sout = new FileOutputStream(spreadsheet);
          IOUtils.copy(field.getInputStream(), sout);
          sout.close();
        } catch (IOException e) {
          throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Upload Failed");
        }

        break;
      }
    }

    // Process
    String[] sheetnames = null;
    if (spreadsheet != null) {
      try {
        sheetnames = excerpter.getSheetNames(spreadsheet);
      } catch (IOException e) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Spreadsheet Corrupt", e);
      }
    } else {
      throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Spreadsheet Missing");
    }

    // Report
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("file", spreadsheet.getName());
    model.put("sheets", sheetnames);
    return model;
  }
  /**
   * Retrieves the named parameter as an integer, if the parameter is not present the default value
   * is returned
   *
   * @param req The WebScript request
   * @param paramName The name of parameter to look for
   * @param defaultValue The default value that should be returned if parameter is not present in
   *     request or if it is not positive
   * @return The request parameter or default value
   */
  protected 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;
  }
  @Test
  public void testSpecialChars() throws IOException {
    String specialChars = new String(new char[] {(char) '香'}) + " 香蕉";
    ResourceWebScriptPost extractor = new ResourceWebScriptPost();
    extractor.setJsonHelper(jsonHelper);
    Map<String, String> templateVars = new HashMap<String, String>();
    String mockMe =
        "{\"name\":\""
            + specialChars
            + "\",\"created\":\"2012-03-23T15:56:18.552+0000\",\"age\":54,\"id\":\"1234A3\",\"farm\":\"LARGE\"}";
    Content content = mock(Content.class);
    when(content.getReader()).thenReturn(new StringReader(mockMe));
    WebScriptRequest request = mock(WebScriptRequest.class);
    when(request.getServiceMatch()).thenReturn(new Match(null, templateVars, null));
    when(request.getContent()).thenReturn(content);

    Params params = extractor.extractParams(mockEntity(), request);
    assertNotNull(params);
    Object passed = params.getPassedIn();
    assertTrue(List.class.isAssignableFrom(passed.getClass()));
    @SuppressWarnings("unchecked")
    List<Object> passedObjs = (List<Object>) passed;
    assertTrue(passedObjs.size() == 1);
    assertTrue("A Farmer was passed in.", Farmer.class.equals(passedObjs.get(0).getClass()));
    Farmer f = (Farmer) passedObjs.get(0);
    assertTrue(f.getName().equals("香 香蕉"));

    // Test passing in special characters as a param.
    ResourceWebScriptGet getExtractor = new ResourceWebScriptGet();
    getExtractor.setJsonHelper(jsonHelper);
    Map<String, String> getTemplateVars = new HashMap<String, String>();
    WebScriptRequest getRequest = mock(WebScriptRequest.class);
    when(getRequest.getServiceMatch()).thenReturn(new Match(null, getTemplateVars, null));
    when(getRequest.getParameterNames()).thenReturn(new String[] {"aParam"});
    when(getRequest.getParameterValues("aParam")).thenReturn(new String[] {specialChars});
    Params pGet = getExtractor.extractParams(mockEntity(), getRequest);
    assertNotNull(pGet);
    String pVal = pGet.getParameter("aParam");
    assertTrue(pVal.equals("香 香蕉"));
  }
  protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {

    Map<String, String> templateArgs = req.getServiceMatch().getTemplateVars();

    String storeType = templateArgs.get("store_type");
    String storeId = templateArgs.get("store_id");
    String nodeId = templateArgs.get("id");

    String nodePath = storeType + "/" + storeId + "/" + nodeId;

    NodeRef folder = repository.findNodeRef("node", nodePath.split("/"));

    // validate that folder has been found
    if (folder == null) {
      throw new WebScriptException(Status.STATUS_NOT_FOUND, "Folder " + nodePath + " not found");
    }

    // construct model for response template to render
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("folder", folder);

    return model;
  }
示例#25
0
  /**
   * Set attachment header
   *
   * @param req
   * @param res
   * @param attach
   * @param attachFileName
   */
  public void setAttachment(
      WebScriptRequest req, WebScriptResponse res, boolean attach, String attachFileName) {
    if (attach == true) {
      String headerValue = "attachment";
      if (attachFileName != null && attachFileName.length() > 0) {
        if (logger.isDebugEnabled())
          logger.debug("Attaching content using filename: " + attachFileName);

        if (req == null) {
          headerValue +=
              "; filename*=UTF-8''"
                  + WebDAVHelper.encodeURL(attachFileName)
                  + "; filename=\""
                  + attachFileName
                  + "\"";
        } else {
          String userAgent = req.getHeader(HEADER_USER_AGENT);
          boolean isLegacy =
              (null != userAgent) && (userAgent.contains("MSIE 8") || userAgent.contains("MSIE 7"));
          if (isLegacy) {
            headerValue += "; filename=\"" + WebDAVHelper.encodeURL(attachFileName);
          } else {
            headerValue +=
                "; filename=\""
                    + attachFileName
                    + "\"; filename*=UTF-8''"
                    + WebDAVHelper.encodeURL(attachFileName);
          }
        }
      }

      // set header based on filename - will force a Save As from the browse if it doesn't recognize
      // it
      // this is better than the default response of the browser trying to display the contents
      res.setHeader("Content-Disposition", headerValue);
    }
  }
示例#26
0
  @Override
  public Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    Map<String, Object> model = new HashMap<String, Object>();
    JSONObject json = null;
    try {
      json = new JSONObject(new JSONTokener(req.getContent().getContent()));
      String name = json.getString("name");
      // TODO check
      String displayString = json.getString("displayLabel");
      // TODO check

      JSONArray capabilitiesArray = json.getJSONArray("capabilities");
      Set<Capability> capabilites = new HashSet<Capability>(capabilitiesArray.length());
      for (int i = 0; i < capabilitiesArray.length(); i++) {
        Capability capability = capabilityService.getCapability(capabilitiesArray.getString(i));
        capabilites.add(capability);
      }

      // get the file plan
      NodeRef filePlan = getFilePlan(req);
      if (filePlan == null) {
        throw new WebScriptException(Status.STATUS_NOT_FOUND, "File plan does not exist.");
      }

      Role role = filePlanRoleService.createRole(filePlan, name, displayString, capabilites);
      model.put("role", new RoleItem(role));

    } catch (IOException iox) {
      throw new WebScriptException(
          Status.STATUS_BAD_REQUEST, "Could not read content from req.", iox);
    } catch (JSONException je) {
      throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not parse JSON from req.", je);
    }

    return model;
  }
示例#27
0
  /*
   * @see org.alfresco.web.scripts.DeclarativeWebScript#executeImpl(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.Status, org.alfresco.web.scripts.Cache)
   */
  @Override
  protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {

    try {
      JSONObject json = null;
      json = new JSONObject(new JSONTokener(req.getContent().getContent()));

      if (json.has("add")) {
        JSONArray toAdd = json.getJSONArray("add");
        for (int i = 0; i < toAdd.length(); i++) {
          JSONObject val = toAdd.getJSONObject(i);
          customEmailMappingService.addCustomMapping(val.getString("from"), val.getString("to"));
        }
      }

      if (json.has("delete")) {
        JSONArray toDelete = json.getJSONArray("delete");
        for (int i = 0; i < toDelete.length(); i++) {
          JSONObject val = toDelete.getJSONObject(i);
          customEmailMappingService.deleteCustomMapping(val.getString("from"), val.getString("to"));
        }
      }

      // Set the return value.
      Set<CustomMapping> emailMap = customEmailMappingService.getCustomMappings();
      // create model object with the lists model
      Map<String, Object> model = new HashMap<String, Object>(1);
      model.put("emailmap", emailMap);
      return model;
    } catch (IOException iox) {
      throw new WebScriptException(
          Status.STATUS_BAD_REQUEST, "Could not read content from req.", iox);
    } catch (JSONException je) {
      throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not parse JSON from req.", je);
    }
  }
示例#28
0
 /**
  * Constructor
  *
  * @param req The webscript request
  * @throws IOException if body of correct format cannot be created
  */
 ActivitiWebScriptBody(WebScriptRequest req) throws IOException {
   jsonBody = new JSONObject(req.getContent().getContent());
 }
示例#29
0
 /**
  * Gets the string parameter value.
  *
  * @param req The webscript request.
  * @param param The name of the string parameter value
  * @param defaultValue The value to return if the parameter isn't present
  * @return The value of the string parameter or the default value if parameter isn't present
  */
 protected String getString(WebScriptRequest req, String param, String defaultValue) {
   String value = checkString(req.getParameter(param), param, false);
   return value != null ? value : defaultValue;
 }
示例#30
0
 /**
  * Gets a mandatory string parameter value of throws an exception if the parameter isn't present.
  *
  * @param req The webscript request
  * @param param The name of the string parameter value
  * @return The string parameter value
  * @throws WebScriptException if the parameter isn't present
  */
 protected String getMandatoryString(WebScriptRequest req, String param) {
   return checkString(req.getParameter(param), param, true);
 }