Java Code Examples for javax.faces.context.ExternalContext#getRequest()

The following examples show how to use javax.faces.context.ExternalContext#getRequest() . 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: JsfUtils.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public static Set<RequestParameter> getViewConfigPageParameters()
{
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();

    Set<RequestParameter> result = new HashSet<RequestParameter>();

    if (externalContext == null || //detection of early config for different mojarra versions
            externalContext.getRequestParameterValuesMap() == null || externalContext.getRequest() == null)
    {
        return result;
    }

    NavigationParameterContext navigationParameterContext =
            BeanProvider.getContextualReference(NavigationParameterContext.class);

    for (Map.Entry<String, String> entry : navigationParameterContext.getPageParameters().entrySet())
    {
        //TODO add multi-value support
        result.add(new RequestParameter(entry.getKey(), new String[]{entry.getValue()}));
    }

    return result;
}
 
Example 2
Source File: MobileRequestCustomizerFactory.java    From XPagesExtensionLibrary with Apache License 2.0 6 votes vote down vote up
private boolean isMobilePage(FacesContext context) {
    ExternalContext o = context.getExternalContext();
    HttpServletRequest r = (javax.servlet.http.HttpServletRequest) o.getRequest();
    String path = r.getServletPath();
    ApplicationEx app = ApplicationEx.getInstance(context);
    String prefix = app.getApplicationProperty(MobileConstants.XSP_THEME_MOBILE_PAGEPREFIX, null);
    if (prefix == null) {
        return false;
    }
    else if (prefix.equals("*")) { // $NON-NLS-1$
        return true;
    }
    else {
        return path.startsWith("/" + prefix); // $NON-NLS-1$
    }
}
 
Example 3
Source File: Headers.java    From softwarecave with GNU General Public License v3.0 6 votes vote down vote up
@PostConstruct
public void init() {
    entries = new ArrayList<>();
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
    HttpServletRequest request = (HttpServletRequest) context.getRequest();
    
    Enumeration<String> namesIt = request.getHeaderNames();
    while (namesIt.hasMoreElements()) {
        String name = namesIt.nextElement();
        Enumeration<String> valueIt = request.getHeaders(name);
        while (valueIt.hasMoreElements()) {
            String value = valueIt.nextElement();
            entries.add(new HeaderEntry(name, value));
        }
    }
}
 
Example 4
Source File: Headers.java    From softwarecave with GNU General Public License v3.0 6 votes vote down vote up
@PostConstruct
public void init() {
    entries = new ArrayList<>();
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
    HttpServletRequest request = (HttpServletRequest) context.getRequest();
    
    Enumeration<String> namesIt = request.getHeaderNames();
    while (namesIt.hasMoreElements()) {
        String name = namesIt.nextElement();
        Enumeration<String> valueIt = request.getHeaders(name);
        while (valueIt.hasMoreElements()) {
            String value = valueIt.nextElement();
            entries.add(new HeaderEntry(name, value));
        }
    }
}
 
Example 5
Source File: FormViewer.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** takes necessary action after editing a custom form */
private String postCustomForm(WorkItemRecord wir) {
    String result = "<success/>";

    // reset session timeout if previously changed
    if (_sb.isSessionTimeoutValueChanged()) {
        _sb.resetSessionTimeout();
        _sb.setSessionTimeoutValueChanged(false);
    }

    // retrieve completion flag - if any
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
    HttpServletRequest request = (HttpServletRequest) context.getRequest();
    String complete = request.getParameter("complete");

    // complete wir if requested
    if ((complete != null) && complete.equalsIgnoreCase("true")) {
        result = completeWorkItem(wir);
    }
    return result;
}
 
Example 6
Source File: ChatTool.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * This is called from the first page to redirect the user to the proper view.
 * This is the first call after JSF creates a new instance, so initialization is 
 *   done here.
 * If the tool is set to go to the select a chat room view and there are multiple chat
 * rooms, then it will go to the select a room page.  If the user is to select a room and
 * there is only one room, then it will go to that room.
 * 
 * @return String
 */
public String getEnterTool() {
   
setupTool();
 
   // if there is no room selected to enter then go to select a room
   String url = PAGE_ENTER_ROOM;

   if(currentChannel == null)
      url = PAGE_LIST_ROOMS;
            
   ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
   
   HttpServletRequest req = (HttpServletRequest) context.getRequest();
   req.setAttribute(Tool.NATIVE_URL, null); //signal to WrappedRequest that we want the Sakai managed
   setToolContext(req.getContextPath());
   req.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);
   
   try {
        context.redirect(url);
   }
   catch (IOException e) {
        throw new RuntimeException("Failed to redirect to " + url, e);
   }
   return "";
}
 
Example 7
Source File: SocialAuth.java    From socialauth with MIT License 5 votes vote down vote up
/**
 * Verifies the user when the external provider redirects back to our
 * application
 * 
 * @throws Exception
 */
public void connect() throws Exception {
	log.info("Connecting Provider:" + id);
	ExternalContext context = javax.faces.context.FacesContext
			.getCurrentInstance().getExternalContext();
	HttpServletRequest request = (HttpServletRequest) context.getRequest();

	provider = manager.connect(SocialAuthUtil.getRequestParametersMap(request));
	profile= provider.getUserProfile();
}
 
Example 8
Source File: ServerUtil.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Safe retrieves http request from FacesContext
 *
 * @return http
 */
public static HttpServletRequest getRequestOrNull() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (facesContext == null)
        return null;

    ExternalContext externalContext = facesContext.getExternalContext();
    if (externalContext == null)
        return null;
    Object request = externalContext.getRequest();
    if (request == null || !(request instanceof HttpServletRequest))
        return null;
    return (HttpServletRequest) request;
}
 
Example 9
Source File: XspUtils.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
/**
 * A more basic generic method that performs boilerplate code to extract XspHttpServletRequest and HttpServletResponse; triggers a
 * callback method passed in ASYNCHRONOUSLY, passing it the request and response; then terminates the response
 * 
 * It's down to you to handle printing something to the response
 * 
 * @param callback
 *            anonymous inner class callback that implements IXspHttpServletResponse, so has a process() method that can be called from
 *            here
 * @throws IOException
 *             that may be caused by manipulating the response
 * @since ODA 4.5.0
 */
public static void initialiseAndProcessResponseAsync(final IXspHttpServletResponseCallback callback) throws IOException {
	FacesContext ctx = FacesContext.getCurrentInstance();
	ExternalContext ext = ctx.getExternalContext();
	BasicXotsXspCallbackRunnable task = new BasicXotsXspCallbackRunnable(callback, (HttpServletRequest) ext.getRequest());
	Xots.getService().submit(task);
	//  Terminate the request processing lifecycle.
	XspHttpServletResponse response = (XspHttpServletResponse) ext.getResponse();
	response.setContentType(HttpServiceConstants.CONTENTTYPE_APPLICATION_JSON);
	response.setHeader("Cache-Control", "no-cache");
	response.setStatus(HttpServletResponse.SC_ACCEPTED);
	PrintWriter writer = response.getWriter();
	writer.write("{\"message\": \"asynchronous task scheduled\"}");
	FacesContext.getCurrentInstance().responseComplete();
}
 
Example 10
Source File: SocialAuth.java    From socialauth with MIT License 5 votes vote down vote up
/**
 * Verifies the user when the external provider redirects back to our
 * application
 * 
 * @throws Exception
 */
public void connect() throws Exception {
	log.info("Connecting Provider:" + id);
	ExternalContext context = javax.faces.context.FacesContext
			.getCurrentInstance().getExternalContext();
	HttpServletRequest request = (HttpServletRequest) context.getRequest();

	provider = manager.connect(SocialAuthUtil
			.getRequestParametersMap(request));
}
 
Example 11
Source File: UploadRenderer.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void encodeBegin(FacesContext context, UIComponent component)
  throws IOException {
  if (!component.isRendered()) return;
  ResponseWriter writer = context.getResponseWriter();
  ExternalContext external = context.getExternalContext();
  HttpServletRequest request = (HttpServletRequest) external.getRequest();

  String clientId = component.getClientId(context);
  log.debug("** encodeBegin, clientId = {}", clientId);
  encodeUploadField(writer, clientId, component);
}
 
Example 12
Source File: SessionScopeBean.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
private synchronized void logout(String redirectUrlBase64) {
	ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
	HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
	StringBuilder url = new StringBuilder(Urls.LOGIN.toString(request));
	url.append("?");
	url.append(GetParamNames.REFERER);
	url.append("=");
	url.append(redirectUrlBase64);
	externalContext.invalidateSession();
	try {
		externalContext.redirect(url.toString());
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 13
Source File: UploadRenderer.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public void decode(FacesContext context, UIComponent component){
  log.debug("**** decode =");
  ExternalContext external = context.getExternalContext();
  HttpServletRequest request = (HttpServletRequest) external.getRequest();
  String clientId = component.getClientId(context);
  WrappedUpload item = wrapUpload(request, clientId + UPLOAD);

  log.debug("clientId = {}", clientId);
  log.debug("wrappedUpload = {}", item);

  ServerConfigurationService serverConfigurationService = ComponentManager.get(ServerConfigurationService.class);
  Long maxSize = Long.valueOf(serverConfigurationService.getString("samigo.sizeMax", "40960"));

  // Check if file > maxSize allowed
  if (item != null && item.getSize()/1000 > maxSize.intValue()){
    ((ServletContext)external.getContext()).setAttribute("TEMP_FILEUPLOAD_SIZE", Long.valueOf(item.getSize()/1000));
    ((EditableValueHolder) component).setSubmittedValue("SizeTooBig:" + item.getName());
    return;
  }

  Object target;
  ValueBinding binding = component.getValueBinding("target");
  if (binding != null) target = binding.getValue(context);
  else target = component.getAttributes().get("target");

  String repositoryPath = serverConfigurationService.getString("samigo.answerUploadRepositoryPath", "${sakai.home}/samigo/answerUploadRepositoryPath/");
  log.debug("****{}", repositoryPath);
  if (target != null){
    File dir = new File(repositoryPath+target.toString()); //directory where file would be saved
    if (!dir.exists())
      dir.mkdirs();
    if (item != null && !("").equals(item.getName())){
      String fullname = item.getName();
      fullname = fullname.replace('\\','/'); // replace c:\fullname to c:/fullname
      fullname = fullname.substring(fullname.lastIndexOf("/")+1);
   int dot_index = fullname.lastIndexOf(".");
   String filename = "";
   if (dot_index < 0) {
   	filename = fullname + "_" + (new Date()).getTime();
   }
   else {
   	filename = fullname.substring(0, dot_index) + "_" + (new Date()).getTime() + fullname.substring(dot_index);
   }
      String filePath = dir.getPath()+"/"+filename;
      log.debug("**1. filename= {}", filePath);
      try {
        //if (mediaIsValid) item.write(file);
        item.write(filePath);
        // change value so we can evoke the listener
        ((EditableValueHolder) component).setSubmittedValue(filePath);
      }
      catch (Exception ex){
        throw new FacesException(ex);
      }
    }
  }
}
 
Example 14
Source File: InputFileUploadRenderer.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Check for errors (both developer errors and user errors) - return a
 * user-friendly error message describing the error, or null if there are no
 * errors.
 */
private static String checkForErrors(FacesContext context, UIComponent component,
        String clientId, boolean atDecodeTime)
{
    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();

    UIForm form = null;
    try
    {
    	form = getForm(component);
    }
    catch (IllegalArgumentException e)
    {
    	// there are more than one nested form - thats not OK!
    	return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in just ONE form.  Nested forms confuse the browser.";
    }
    if (form == null || !"multipart/form-data".equals(RendererUtil.getAttribute(context, form, "enctype")))
    {
        return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in a <h:form enctype=\"multipart/form-data\"> tag.";
    }

    // check tag attributes
    String directory = (String) RendererUtil.getAttribute(context, component, "directory");
    if (directory != null && directory.length() != 0)
    {
        // the tag is configured to persist the uploaded files to a directory.
        // check that the specified directory exists, and is writeable
        File dir = new File(directory);
        if (!dir.isDirectory() || !dir.exists())
        {
            return "DEVELOPER ERROR: The directory specified on the <inputFileUpload> tag does not exist or is not writable.\n"
            + "Check the permissions on directory:\n"
            + dir;
        }
    }

    FileItem item = getFileItem(context, component);
    boolean isMultipartRequest = request.getContentType() != null && request.getContentType().startsWith("multipart/form-data");
    boolean wasMultipartRequestFullyParsed = request.getParameter(clientId + ID_HIDDEN_ELEMENT) != null;
    String requestFilterStatus = (String) request.getAttribute("upload.status");
    Object requestFilterUploadLimit = request.getAttribute("upload.limit");
    Exception requestFilterException = (Exception) request.getAttribute("upload.exception");
    boolean wasDecodeAlreadyCalledOnTheRequest = "true".equals(request.getAttribute(clientId + ATTR_REQUEST_DECODED));

    if (wasDecodeAlreadyCalledOnTheRequest && !atDecodeTime)
    {
        // decode() was already called on the request, and we're now at encode() time - so don't do further error checking
        // as the FileItem may no longer be valid.
        return null;
    }

    // at this point, if its not a multipart request, it doesn't have a file and there isn't an error.
    if (!isMultipartRequest) return null;

    // check for user errors
    if ("exception".equals(requestFilterStatus))
    {
        return "An error occured while processing the uploaded file.  The error was:\n"
                + requestFilterException;
    }
    else if ("size_limit_exceeded".equals(requestFilterStatus))
    {
        // the user tried to upload too large a file
        return "The upload size limit of " + requestFilterUploadLimit + "MB has been exceeded.";
    }
    else if (item == null || item.getName() == null || item.getName().length() == 0)
    {
         // The file item will be null if the component was previously not rendered.
         return null;
     }
    else if (item.getSize() == 0)
    {
        return "The filename '"+item.getName()+"' is invalid.  Please select a valid file.";
    }

    if (!wasMultipartRequestFullyParsed)
    {
        return "An error occured while processing the uploaded file.  The error was:\n"
        + "DEVELOPER ERROR: The <inputFileUpload> tag requires a <filter> in web.xml to parse the uploaded file.\n"
        + "Check that the Sakai RequestFilter is properly configured in web.xml.";
    }

    if (item.getName().indexOf("..") >= 0)
    {
        return "The filename '"+item.getName()+"' is invalid.  Please select a valid file.";
    }

    // everything checks out fine! The upload was parsed, and a FileItem
    // exists with a filename and non-zero length
    return null;
}
 
Example 15
Source File: InputFileUploadRenderer.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public void decode(FacesContext context, UIComponent comp)
{
    UIInput component = (UIInput) comp;
    if (!component.isRendered()) return;

    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();
    String clientId = component.getClientId(context);
    String directory = (String) RendererUtil.getAttribute(context, component, "directory");

    // mark that this component has had decode() called during request
    // processing
    request.setAttribute(clientId + ATTR_REQUEST_DECODED, "true");

    // check for user errors and developer errors
    boolean atDecodeTime = true;
    String errorMessage = checkForErrors(context, component, clientId, atDecodeTime);
    if (errorMessage != null)
    {
        addFacesMessage(context, clientId, errorMessage);
        return;
    }

    // get the file item
    FileItem item = getFileItem(context, component);

    if (item.getName() == null || item.getName().length() == 0)
    {
        if (component.isRequired())
        {
            addFacesMessage(context, clientId, "Please specify a file.");
            component.setValid(false);
        }
        return;
    }

    if (directory == null || directory.length() == 0)
    {
        // just passing on the FileItem as the value of the component, without persisting it.
        component.setSubmittedValue(item);
    }
    else
    {
        // persisting to a permenent file in a directory.
        // pass on the server-side filename as the value of the component.
        File dir = new File(directory);
        String filename = item.getName();
        filename = filename.replace('\\','/'); // replaces Windows path seperator character "\" with "/"
        filename = filename.substring(filename.lastIndexOf("/")+1);
        File persistentFile = new File(dir, filename);
        try
        {
            item.write(persistentFile);
            component.setSubmittedValue(persistentFile.getPath());
        }
        catch (Exception ex)
        {
            throw new FacesException(ex);
        }
     }

}
 
Example 16
Source File: InputFileUploadRenderer.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Check for errors (both developer errors and user errors) - return a
 * user-friendly error message describing the error, or null if there are no
 * errors.
 */
private static String checkForErrors(FacesContext context, UIComponent component,
        String clientId, boolean atDecodeTime)
{
    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();

    UIForm form = null;
    try
    {
    	form = getForm(component);
    }
    catch (IllegalArgumentException e)
    {
    	// there are more than one nested form - thats not OK!
    	return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in just ONE form.  Nested forms confuse the browser.";
    }
    if (form == null || !"multipart/form-data".equals(RendererUtil.getAttribute(context, form, "enctype")))
    {
        return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in a <h:form enctype=\"multipart/form-data\"> tag.";
    }

    // check tag attributes
    String directory = (String) RendererUtil.getAttribute(context, component, "directory");
    if (directory != null && directory.length() != 0)
    {
        // the tag is configured to persist the uploaded files to a directory.
        // check that the specified directory exists, and is writeable
        File dir = new File(directory);
        if (!dir.isDirectory() || !dir.exists())
        {
            return "DEVELOPER ERROR: The directory specified on the <inputFileUpload> tag does not exist or is not writable.\n"
            + "Check the permissions on directory:\n"
            + dir;
        }
    }

    FileItem item = getFileItem(context, component);
    boolean isMultipartRequest = request.getContentType() != null && request.getContentType().startsWith("multipart/form-data");
    boolean wasMultipartRequestFullyParsed = request.getParameter(clientId + ID_HIDDEN_ELEMENT) != null;
    String requestFilterStatus = (String) request.getAttribute("upload.status");
    Object requestFilterUploadLimit = request.getAttribute("upload.limit");
    Exception requestFilterException = (Exception) request.getAttribute("upload.exception");
    boolean wasDecodeAlreadyCalledOnTheRequest = "true".equals(request.getAttribute(clientId + ATTR_REQUEST_DECODED));

    if (wasDecodeAlreadyCalledOnTheRequest && !atDecodeTime)
    {
        // decode() was already called on the request, and we're now at encode() time - so don't do further error checking
        // as the FileItem may no longer be valid.
        return null;
    }

    // at this point, if its not a multipart request, it doesn't have a file and there isn't an error.
    if (!isMultipartRequest) return null;

    // check for user errors
    if ("exception".equals(requestFilterStatus))
    {
        return "An error occured while processing the uploaded file.  The error was:\n"
                + requestFilterException;
    }
    else if ("size_limit_exceeded".equals(requestFilterStatus))
    {
        // the user tried to upload too large a file
        return "The upload size limit of " + requestFilterUploadLimit + "MB has been exceeded.";
    }
    else if (item == null || item.getName() == null || item.getName().length() == 0)
    {
         // The file item will be null if the component was previously not rendered.
         return null;
     }
    else if (item.getSize() == 0)
    {
        return "The filename '"+item.getName()+"' is invalid.  Please select a valid file.";
    }

    if (!wasMultipartRequestFullyParsed)
    {
        return "An error occured while processing the uploaded file.  The error was:\n"
        + "DEVELOPER ERROR: The <inputFileUpload> tag requires a <filter> in web.xml to parse the uploaded file.\n"
        + "Check that the Sakai RequestFilter is properly configured in web.xml.";
    }

    if (item.getName().indexOf("..") >= 0)
    {
        return "The filename '"+item.getName()+"' is invalid.  Please select a valid file.";
    }

    // everything checks out fine! The upload was parsed, and a FileItem
    // exists with a filename and non-zero length
    return null;
}
 
Example 17
Source File: InputFileUploadRenderer.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public void decode(FacesContext context, UIComponent comp)
{
    UIInput component = (UIInput) comp;
    if (!component.isRendered()) return;

    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();
    String clientId = component.getClientId(context);
    String directory = (String) RendererUtil.getAttribute(context, component, "directory");

    // mark that this component has had decode() called during request
    // processing
    request.setAttribute(clientId + ATTR_REQUEST_DECODED, "true");

    // check for user errors and developer errors
    boolean atDecodeTime = true;
    String errorMessage = checkForErrors(context, component, clientId, atDecodeTime);
    if (errorMessage != null)
    {
        addFacesMessage(context, clientId, errorMessage);
        return;
    }

    // get the file item
    FileItem item = getFileItem(context, component);

    if (item.getName() == null || item.getName().length() == 0)
    {
        if (component.isRequired())
        {
            addFacesMessage(context, clientId, "Please specify a file.");
            component.setValid(false);
        }
        return;
    }

    if (directory == null || directory.length() == 0)
    {
        // just passing on the FileItem as the value of the component, without persisting it.
        component.setSubmittedValue(item);
    }
    else
    {
        // persisting to a permenent file in a directory.
        // pass on the server-side filename as the value of the component.
        File dir = new File(directory);
        String filename = item.getName();
        filename = filename.replace('\\','/'); // replaces Windows path seperator character "\" with "/"
        filename = filename.substring(filename.lastIndexOf("/")+1);
        File persistentFile = new File(dir, filename);
        try
        {
            item.write(persistentFile);
            component.setSubmittedValue(persistentFile.getPath());
        }
        catch (Exception ex)
        {
            throw new FacesException(ex);
        }
     }

}
 
Example 18
Source File: InputFileUploadRenderer.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Check for errors (both developer errors and user errors) - return a
 * user-friendly error message describing the error, or null if there are no
 * errors.
 */
private static String checkForErrors(FacesContext context, UIComponent component,
        String clientId, boolean atDecodeTime)
{
    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();

    UIForm form = null;
    try
    {
    	form = getForm(component);
    }
    catch (IllegalArgumentException e)
    {
    	// there are more than one nested form - thats not OK!
    	return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in just ONE form.  Nested forms confuse the browser.";
    }
    if (form == null || !"multipart/form-data".equals(RendererUtil.getAttribute(context, form, "enctype")))
    {
        return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in a <h:form enctype=\"multipart/form-data\"> tag.";
    }

    // check tag attributes
    String directory = (String) RendererUtil.getAttribute(context, component, "directory");
    if (directory != null && directory.length() != 0)
    {
        // the tag is configured to persist the uploaded files to a directory.
        // check that the specified directory exists, and is writeable
        File dir = new File(directory);
        if (!dir.isDirectory() || !dir.exists())
        {
            return "DEVELOPER ERROR: The directory specified on the <inputFileUpload> tag does not exist or is not writable.\n"
            + "Check the permissions on directory:\n"
            + dir;
        }
    }

    FileItem item = getFileItem(context, component);
    boolean isMultipartRequest = request.getContentType() != null && request.getContentType().startsWith("multipart/form-data");
    boolean wasMultipartRequestFullyParsed = request.getParameter(clientId + ID_HIDDEN_ELEMENT) != null;
    String requestFilterStatus = (String) request.getAttribute("upload.status");
    Object requestFilterUploadLimit = request.getAttribute("upload.limit");
    Exception requestFilterException = (Exception) request.getAttribute("upload.exception");
    boolean wasDecodeAlreadyCalledOnTheRequest = "true".equals(request.getAttribute(clientId + ATTR_REQUEST_DECODED));

    if (wasDecodeAlreadyCalledOnTheRequest && !atDecodeTime)
    {
        // decode() was already called on the request, and we're now at encode() time - so don't do further error checking
        // as the FileItem may no longer be valid.
        return null;
    }

    // at this point, if its not a multipart request, it doesn't have a file and there isn't an error.
    if (!isMultipartRequest) return null;

    // check for user errors
    if ("exception".equals(requestFilterStatus))
    {
        return "An error occured while processing the uploaded file.  The error was:\n"
                + requestFilterException;
    }
    else if ("size_limit_exceeded".equals(requestFilterStatus))
    {
        // the user tried to upload too large a file
        return "The upload size limit of " + requestFilterUploadLimit + "MB has been exceeded.";
    }
    else if (item == null || item.getName() == null || item.getName().length() == 0)
    {
         // The file item will be null if the component was previously not rendered.
         return null;
     }
    else if (item.getSize() == 0)
    {
        return "The filename '"+item.getName()+"' is invalid.  Please select a valid file.";
    }

    if (!wasMultipartRequestFullyParsed)
    {
        return "An error occured while processing the uploaded file.  The error was:\n"
        + "DEVELOPER ERROR: The <inputFileUpload> tag requires a <filter> in web.xml to parse the uploaded file.\n"
        + "Check that the Sakai RequestFilter is properly configured in web.xml.";
    }

    if (item.getName().indexOf("..") >= 0)
    {
        return "The filename '"+item.getName()+"' is invalid.  Please select a valid file.";
    }

    // everything checks out fine! The upload was parsed, and a FileItem
    // exists with a filename and non-zero length
    return null;
}
 
Example 19
Source File: InputFileUploadRenderer.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public void decode(FacesContext context, UIComponent comp)
{
    UIInput component = (UIInput) comp;
    if (!component.isRendered()) return;

    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();
    String clientId = component.getClientId(context);
    String directory = (String) RendererUtil.getAttribute(context, component, "directory");

    // mark that this component has had decode() called during request
    // processing
    request.setAttribute(clientId + ATTR_REQUEST_DECODED, "true");

    // check for user errors and developer errors
    boolean atDecodeTime = true;
    String errorMessage = checkForErrors(context, component, clientId, atDecodeTime);
    if (errorMessage != null)
    {
        addFacesMessage(context, clientId, errorMessage);
        return;
    }

    // get the file item
    FileItem item = getFileItem(context, component);

    if (item.getName() == null || item.getName().length() == 0)
    {
        if (component.isRequired())
        {
            addFacesMessage(context, clientId, "Please specify a file.");
            component.setValid(false);
        }
        return;
    }

    if (directory == null || directory.length() == 0)
    {
        // just passing on the FileItem as the value of the component, without persisting it.
        component.setSubmittedValue(item);
    }
    else
    {
        // persisting to a permenent file in a directory.
        // pass on the server-side filename as the value of the component.
        File dir = new File(directory);
        String filename = item.getName();
        filename = filename.replace('\\','/'); // replaces Windows path seperator character "\" with "/"
        filename = filename.substring(filename.lastIndexOf("/")+1);
        File persistentFile = new File(dir, filename);
        try
        {
            item.write(persistentFile);
            component.setSubmittedValue(persistentFile.getPath());
        }
        catch (Exception ex)
        {
            throw new FacesException(ex);
        }
     }

}
 
Example 20
Source File: AuthBean.java    From sailfish-core with Apache License 2.0 3 votes vote down vote up
public void login() throws IOException {

		FacesContext context = FacesContext.getCurrentInstance();
		ExternalContext externalContext = context.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

		try {

			request.login(username, password + PasswordHasher.getSalt());

			User user = BeanUtil.getSfContext().getAuthStorage().getUser(username);

			if (user == null) {

                logger.error("User with login [{}] not found in storage!", username);

				BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR,
						"Invalid login/password pair", "");

				return;
			}

			externalContext.getSessionMap().put(BeanUtil.KEY_USER, user);

			externalContext.redirect(originalURL);

		} catch (ServletException e) {

			// Handle unknown username/password in request.login().
            logger.warn("Bad login attempt with username [{}]; message: {}", username, e.getMessage());
			BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, "Invalid login/password pair", "");

			return;
		}

		logger.info("Successful login for user [{}]", username);
	}