Search in sources :

Example 96 with FileItem

use of org.apache.commons.fileupload.FileItem in project iaf by ibissource.

the class ApiListenerServlet method service.

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    /**
     * Initiate and populate messageContext
     */
    IPipeLineSession messageContext = new PipeLineSessionBase();
    messageContext.put(IPipeLineSession.HTTP_REQUEST_KEY, request);
    messageContext.put(IPipeLineSession.HTTP_RESPONSE_KEY, response);
    messageContext.put(IPipeLineSession.SERVLET_CONTEXT_KEY, getServletContext());
    ISecurityHandler securityHandler = new HttpSecurityHandler(request);
    messageContext.put(IPipeLineSession.securityHandlerKey, securityHandler);
    try {
        String uri = request.getPathInfo();
        String method = request.getMethod().toUpperCase();
        log.trace("ApiListenerServlet dispatching uri [" + uri + "] and method [" + method + "]");
        if (uri == null) {
            response.setStatus(400);
            log.warn("Aborting request with status [400], empty uri");
            return;
        }
        if (uri.startsWith("/"))
            uri = uri.substring(1);
        if (uri.endsWith("/"))
            uri = uri.substring(0, uri.length() - 1);
        ApiDispatchConfig config = dispatcher.findConfigForUri(uri);
        if (config == null) {
            response.setStatus(404);
            log.trace("Aborting request with status [404], no ApiListener configured for [" + uri + "]");
            return;
        }
        /**
         * Handle Cross-Origin Resource Sharing
         */
        if (method.equals("OPTIONS")) {
            response.setHeader("Access-Control-Allow-Origin", CorsAllowOrigin);
            String headers = request.getHeader("Access-Control-Request-Headers");
            if (headers != null)
                response.setHeader("Access-Control-Allow-Headers", headers);
            response.setHeader("Access-Control-Expose-Headers", CorsExposeHeaders);
            StringBuilder methods = new StringBuilder();
            for (String mtd : config.getMethods()) {
                methods.append(", ").append(mtd);
            }
            response.setHeader("Access-Control-Allow-Methods", methods.toString());
            response.setStatus(200);
            log.trace("Aborting preflight request with status [200], method [" + method + "]");
            return;
        }
        /**
         * Get serviceClient
         */
        ApiListener listener = config.getApiListener(method);
        if (listener == null) {
            response.setStatus(405);
            log.trace("Aborting request with status [405], method [" + method + "] not allowed");
            return;
        }
        log.trace("ApiListenerServlet calling service [" + listener.getName() + "]");
        /**
         * Check authentication
         */
        ApiPrincipal userPrincipal = null;
        if (listener.getAuthenticationMethod() != null) {
            String authorizationToken = null;
            Cookie authorizationCookie = null;
            if (listener.getAuthenticationMethod().equals("COOKIE")) {
                Cookie[] cookies = request.getCookies();
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("authenticationToken")) {
                        authorizationToken = cookie.getValue();
                        authorizationCookie = cookie;
                        authorizationCookie.setPath("/");
                    }
                }
            } else if (listener.getAuthenticationMethod().equals("HEADER")) {
                authorizationToken = request.getHeader("Authorization");
            }
            if (authorizationToken != null && cache.containsKey(authorizationToken))
                userPrincipal = (ApiPrincipal) cache.get(authorizationToken);
            if (userPrincipal == null || !userPrincipal.isLoggedIn()) {
                cache.remove(authorizationToken);
                if (authorizationCookie != null) {
                    authorizationCookie.setMaxAge(0);
                    response.addCookie(authorizationCookie);
                }
                response.setStatus(401);
                log.trace("Aborting request with status [401], no (valid) credentials supplied");
                return;
            }
            if (authorizationCookie != null) {
                authorizationCookie.setMaxAge(authTTL);
                response.addCookie(authorizationCookie);
            }
            userPrincipal.updateExpiry();
            userPrincipal.setToken(authorizationToken);
            cache.put(authorizationToken, userPrincipal, authTTL);
            messageContext.put("authorizationToken", authorizationToken);
        }
        messageContext.put("remoteAddr", request.getRemoteAddr());
        messageContext.put(IPipeLineSession.API_PRINCIPAL_KEY, userPrincipal);
        messageContext.put("uri", uri);
        /**
         * Evaluate preconditions
         */
        String accept = request.getHeader("Accept");
        if (accept != null && !accept.isEmpty() && !accept.equals("*/*")) {
            if (!listener.getProduces().equals("ANY") && !accept.contains(listener.getContentType())) {
                response.setStatus(406);
                response.getWriter().print("It appears you expected the MediaType [" + accept + "] but I only support the MediaType [" + listener.getContentType() + "] :)");
                log.trace("Aborting request with status [406], client expects [" + accept + "] got [" + listener.getContentType() + "] instead");
                return;
            }
        }
        if (request.getContentType() != null && !listener.isConsumable(request.getContentType())) {
            response.setStatus(415);
            log.trace("Aborting request with status [415], did not match consumes [" + listener.getConsumes() + "] got [" + request.getContentType() + "] instead");
            return;
        }
        String etagCacheKey = ApiCacheManager.buildCacheKey(config.getUriPattern());
        if (cache.containsKey(etagCacheKey)) {
            String cachedEtag = (String) cache.get(etagCacheKey);
            if (method.equals("GET")) {
                String ifNoneMatch = request.getHeader("If-None-Match");
                if (ifNoneMatch != null && ifNoneMatch.equals(cachedEtag)) {
                    response.setStatus(304);
                    log.trace("Aborting request with status [304], matched if-none-match [" + ifNoneMatch + "]");
                    return;
                }
            } else {
                String ifMatch = request.getHeader("If-Match");
                if (ifMatch != null && !ifMatch.equals(cachedEtag)) {
                    response.setStatus(412);
                    log.trace("Aborting request with status [412], matched if-match [" + ifMatch + "] method [" + method + "]");
                    return;
                }
            }
        }
        /**
         * Check authorization
         */
        // TODO: authentication implementation
        /**
         * Map uriIdentifiers into messageContext
         */
        String[] patternSegments = listener.getUriPattern().split("/");
        String[] uriSegments = uri.split("/");
        int uriIdentifier = 0;
        for (int i = 0; i < patternSegments.length; i++) {
            String segment = patternSegments[i];
            if (segment.startsWith("{") && segment.endsWith("}")) {
                String name;
                if (segment.equals("*"))
                    name = "uriIdentifier_" + uriIdentifier;
                else
                    name = segment.substring(1, segment.length() - 1);
                uriIdentifier++;
                log.trace("setting uriSegment [" + name + "] to [" + uriSegments[i] + "]");
                messageContext.put(name, uriSegments[i]);
            }
        }
        /**
         * Map queryParameters into messageContext
         */
        Enumeration<?> paramnames = request.getParameterNames();
        while (paramnames.hasMoreElements()) {
            String paramname = (String) paramnames.nextElement();
            String paramvalue = request.getParameter(paramname);
            log.trace("setting queryParameter [" + paramname + "] to [" + paramvalue + "]");
            messageContext.put(paramname, paramvalue);
        }
        /**
         * Map multipart parts into messageContext
         */
        if (ServletFileUpload.isMultipartContent(request)) {
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            List<FileItem> items = servletFileUpload.parseRequest(request);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();
                    log.trace("setting multipart formField [" + fieldName + "] to [" + fieldValue + "]");
                    messageContext.put(fieldName, fieldValue);
                } else {
                    // Process form file field (input type="file").
                    String fieldName = item.getFieldName();
                    String fieldNameName = fieldName + "Name";
                    String fileName = FilenameUtils.getName(item.getName());
                    log.trace("setting multipart formFile [" + fieldNameName + "] to [" + fileName + "]");
                    messageContext.put(fieldNameName, fileName);
                    log.trace("setting parameter [" + fieldName + "] to input stream of file [" + fileName + "]");
                    messageContext.put(fieldName, item.getInputStream());
                }
            }
        }
        /**
         * Compile Allow header
         */
        StringBuilder methods = new StringBuilder();
        methods.append("OPTIONS, ");
        for (String mtd : config.getMethods()) {
            methods.append(mtd + ", ");
        }
        messageContext.put("allowedMethods", methods.substring(0, methods.length() - 2));
        /**
         * Process the request through the pipeline
         */
        String body = "";
        if (!ServletFileUpload.isMultipartContent(request)) {
            body = Misc.streamToString(request.getInputStream(), "\n", false);
        }
        String result = listener.processRequest(null, body, messageContext);
        /**
         * Calculate an etag over the processed result and store in cache
         */
        if (listener.getUpdateEtag()) {
            if (result != null && method.equals("GET")) {
                String eTag = ApiCacheManager.buildEtag(listener.getCleanPattern(), result.hashCode());
                cache.put(etagCacheKey, eTag);
                response.addHeader("etag", eTag);
            } else {
                cache.remove(etagCacheKey);
            }
        }
        /**
         * Add headers
         */
        response.addHeader("Allow", (String) messageContext.get("allowedMethods"));
        String contentType = listener.getContentType() + "; charset=utf-8";
        if (listener.getProduces().equals("ANY")) {
            contentType = (String) messageContext.get("contentType");
        }
        response.setHeader("Content-Type", contentType);
        /**
         * Check if an exitcode has been defined or if a statuscode has been added to the messageContext.
         */
        int statusCode = 0;
        if (messageContext.containsKey("exitcode"))
            statusCode = Integer.parseInt("" + messageContext.get("exitcode"));
        if (statusCode > 0)
            response.setStatus(statusCode);
        /**
         * Finalize the pipeline and write the result to the response
         */
        if (result != null)
            response.getWriter().print(result);
        log.trace("ApiListenerServlet finished with statusCode [" + statusCode + "] result [" + result + "]");
    } catch (Exception e) {
        log.warn("ApiListenerServlet caught exception, will rethrow as ServletException", e);
        try {
            response.flushBuffer();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (IllegalStateException ex) {
            // We're only informing the end user(s), no need to catch this error...
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
Also used : Cookie(javax.servlet.http.Cookie) ISecurityHandler(nl.nn.adapterframework.core.ISecurityHandler) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) HttpSecurityHandler(nl.nn.adapterframework.http.HttpSecurityHandler) IPipeLineSession(nl.nn.adapterframework.core.IPipeLineSession) PipeLineSessionBase(nl.nn.adapterframework.core.PipeLineSessionBase)

Example 97 with FileItem

use of org.apache.commons.fileupload.FileItem in project iaf by ibissource.

the class StreamPipe method doPipe.

@Override
public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    Object result = input;
    String inputString;
    if (input instanceof String) {
        inputString = (String) input;
    } else {
        inputString = "";
    }
    ParameterResolutionContext prc = new ParameterResolutionContext(inputString, session, isNamespaceAware());
    Map parameters = null;
    ParameterList parameterList = getParameterList();
    if (parameterList != null) {
        try {
            parameters = prc.getValueMap(parameterList);
        } catch (ParameterException e) {
            throw new PipeRunException(this, "Could not resolve parameters", e);
        }
    }
    InputStream inputStream = null;
    OutputStream outputStream = null;
    HttpServletRequest httpRequest = null;
    HttpServletResponse httpResponse = null;
    String contentType = null;
    String contentDisposition = null;
    if (parameters != null) {
        if (parameters.get("inputStream") != null) {
            inputStream = (InputStream) parameters.get("inputStream");
        }
        if (parameters.get("outputStream") != null) {
            outputStream = (OutputStream) parameters.get("outputStream");
        }
        if (parameters.get("httpRequest") != null) {
            httpRequest = (HttpServletRequest) parameters.get("httpRequest");
        }
        if (parameters.get("httpResponse") != null) {
            httpResponse = (HttpServletResponse) parameters.get("httpResponse");
        }
        if (parameters.get("contentType") != null) {
            contentType = (String) parameters.get("contentType");
        }
        if (parameters.get("contentDisposition") != null) {
            contentDisposition = (String) parameters.get("contentDisposition");
        }
    }
    if (inputStream == null && input instanceof InputStream) {
        inputStream = (InputStream) input;
    }
    try {
        if (httpResponse != null) {
            HttpSender.streamResponseBody(inputStream, contentType, contentDisposition, httpResponse, log, getLogPrefix(session));
        } else if (httpRequest != null) {
            StringBuilder partsString = new StringBuilder("<parts>");
            String firstStringPart = null;
            List<AntiVirusObject> antiVirusObjects = new ArrayList<AntiVirusObject>();
            if (ServletFileUpload.isMultipartContent(httpRequest)) {
                log.debug(getLogPrefix(session) + "request with content type [" + httpRequest.getContentType() + "] and length [" + httpRequest.getContentLength() + "] contains multipart content");
                DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
                ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
                List<FileItem> items = servletFileUpload.parseRequest(httpRequest);
                int fileCounter = 0;
                int stringCounter = 0;
                log.debug(getLogPrefix(session) + "multipart request items size [" + items.size() + "]");
                String lastFoundFileName = null;
                String lastFoundAVStatus = null;
                String lastFoundAVMessage = null;
                for (FileItem item : items) {
                    if (item.isFormField()) {
                        // Process regular form field (input
                        // type="text|radio|checkbox|etc", select, etc).
                        String fieldValue = item.getString();
                        String fieldName = item.getFieldName();
                        if (isCheckAntiVirus() && fieldName.equalsIgnoreCase(getAntiVirusPartName())) {
                            log.debug(getLogPrefix(session) + "found antivirus status part [" + fieldName + "] with value [" + fieldValue + "]");
                            lastFoundAVStatus = fieldValue;
                        } else if (isCheckAntiVirus() && fieldName.equalsIgnoreCase(getAntiVirusMessagePartName())) {
                            log.debug(getLogPrefix(session) + "found antivirus message part [" + fieldName + "] with value [" + fieldValue + "]");
                            lastFoundAVMessage = fieldValue;
                        } else {
                            log.debug(getLogPrefix(session) + "found string part [" + fieldName + "] with value [" + fieldValue + "]");
                            if (isExtractFirstStringPart() && firstStringPart == null) {
                                firstStringPart = fieldValue;
                            } else {
                                String sessionKeyName = "part_string" + (++stringCounter > 1 ? stringCounter : "");
                                addSessionKey(session, sessionKeyName, fieldValue);
                                partsString.append("<part type=\"string\" name=\"" + fieldName + "\" sessionKey=\"" + sessionKeyName + "\" size=\"" + fieldValue.length() + "\"/>");
                            }
                        }
                    } else {
                        // Process form file field (input type="file").
                        if (lastFoundFileName != null && lastFoundAVStatus != null) {
                            antiVirusObjects.add(new AntiVirusObject(lastFoundFileName, lastFoundAVStatus, lastFoundAVMessage));
                            lastFoundFileName = null;
                            lastFoundAVStatus = null;
                            lastFoundAVMessage = null;
                        }
                        log.debug(getLogPrefix(session) + "found file part [" + item.getName() + "]");
                        String sessionKeyName = "part_file" + (++fileCounter > 1 ? fileCounter : "");
                        String fileName = FilenameUtils.getName(item.getName());
                        InputStream is = item.getInputStream();
                        int size = is.available();
                        String mimeType = item.getContentType();
                        if (size > 0) {
                            addSessionKey(session, sessionKeyName, is, fileName);
                        } else {
                            addSessionKey(session, sessionKeyName, null);
                        }
                        partsString.append("<part type=\"file\" name=\"" + fileName + "\" sessionKey=\"" + sessionKeyName + "\" size=\"" + size + "\" mimeType=\"" + mimeType + "\"/>");
                        lastFoundFileName = fileName;
                    }
                }
                if (lastFoundFileName != null && lastFoundAVStatus != null) {
                    antiVirusObjects.add(new AntiVirusObject(lastFoundFileName, lastFoundAVStatus, lastFoundAVMessage));
                }
            } else {
                log.debug(getLogPrefix(session) + "request with content type [" + httpRequest.getContentType() + "] and length [" + httpRequest.getContentLength() + "] does NOT contain multipart content");
            }
            partsString.append("</parts>");
            if (isExtractFirstStringPart()) {
                result = adjustFirstStringPart(firstStringPart, session);
                session.put(getMultipartXmlSessionKey(), partsString.toString());
            } else {
                result = partsString.toString();
            }
            if (!antiVirusObjects.isEmpty()) {
                for (AntiVirusObject antiVirusObject : antiVirusObjects) {
                    if (!antiVirusObject.getStatus().equalsIgnoreCase(getAntiVirusPassedMessage())) {
                        String errorMessage = "multipart contains file [" + antiVirusObject.getFileName() + "] with antivirus status [" + antiVirusObject.getStatus() + "] and message [" + StringUtils.defaultString(antiVirusObject.getMessage()) + "]";
                        PipeForward antiVirusFailedForward = findForward(ANTIVIRUS_FAILED_FORWARD);
                        if (antiVirusFailedForward == null) {
                            throw new PipeRunException(this, errorMessage);
                        } else {
                            if (antiVirusFailureAsSoapFault) {
                                errorMessage = createSoapFaultMessage(errorMessage);
                            }
                            if (StringUtils.isEmpty(getAntiVirusFailureReasonSessionKey())) {
                                return new PipeRunResult(antiVirusFailedForward, errorMessage);
                            } else {
                                session.put(getAntiVirusFailureReasonSessionKey(), errorMessage);
                                return new PipeRunResult(antiVirusFailedForward, result);
                            }
                        }
                    }
                }
            }
        } else {
            Misc.streamToStream(inputStream, outputStream);
        }
    } catch (IOException e) {
        throw new PipeRunException(this, "IOException streaming input to output", e);
    } catch (FileUploadException e) {
        throw new PipeRunException(this, "FileUploadException getting multiparts from httpServletRequest", e);
    }
    return new PipeRunResult(getForward(), result);
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) PipeForward(nl.nn.adapterframework.core.PipeForward) HttpServletRequest(javax.servlet.http.HttpServletRequest) FileItem(org.apache.commons.fileupload.FileItem) PipeRunResult(nl.nn.adapterframework.core.PipeRunResult) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) PipeRunException(nl.nn.adapterframework.core.PipeRunException) ParameterList(nl.nn.adapterframework.parameters.ParameterList) ParameterException(nl.nn.adapterframework.core.ParameterException) ArrayList(java.util.ArrayList) ParameterList(nl.nn.adapterframework.parameters.ParameterList) List(java.util.List) ParameterResolutionContext(nl.nn.adapterframework.parameters.ParameterResolutionContext) Map(java.util.Map) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 98 with FileItem

use of org.apache.commons.fileupload.FileItem in project jwt by emweb.

the class WebRequest method parse.

@SuppressWarnings({ "unchecked", "deprecation" })
private void parse(final ProgressListener progressUpdate) throws IOException {
    if (FileUploadBase.isMultipartContent(this)) {
        try {
            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            if (progressUpdate != null) {
                upload.setProgressListener(new org.apache.commons.fileupload.ProgressListener() {

                    public void update(long pBytesRead, long pContentLength, int pItems) {
                        progressUpdate.update(WebRequest.this, pBytesRead, pContentLength);
                    }
                });
            }
            // Parse the request
            List items = upload.parseRequest(this);
            parseParameters();
            Iterator itr = items.iterator();
            FileItem fi;
            File f = null;
            while (itr.hasNext()) {
                fi = (FileItem) itr.next();
                // else condition handles the submit button input
                if (!fi.isFormField()) {
                    try {
                        f = File.createTempFile("jwt", "jwt");
                        fi.write(f);
                        fi.delete();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    List<UploadedFile> files = files_.get(fi.getFieldName());
                    if (files == null) {
                        files = new ArrayList<UploadedFile>();
                        files_.put(fi.getFieldName(), files);
                    }
                    files.add(new UploadedFile(f.getAbsolutePath(), fi.getName(), fi.getContentType()));
                } else {
                    String[] v = parameters_.get(fi.getFieldName());
                    if (v == null)
                        v = new String[1];
                    else {
                        String[] newv = new String[v.length + 1];
                        for (int i = 0; i < v.length; ++i) newv[i] = v[i];
                        v = newv;
                    }
                    v[v.length - 1] = fi.getString();
                    parameters_.put(fi.getFieldName(), v);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    } else
        parseParameters();
}
Also used : IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 99 with FileItem

use of org.apache.commons.fileupload.FileItem in project acs-community-packaging by Alfresco.

the class ContentUpdateBean method updateFile.

/**
 * Ajax method to update file content. A multi-part form is required as the input.
 *
 * "return-page" = javascript to execute on return from the upload request
 * "nodeRef" = the nodeRef of the item to update the content of
 *
 * @throws Exception
 */
@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML)
public void updateFile() throws Exception {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext externalContext = fc.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setHeaderEncoding("UTF-8");
    List<FileItem> fileItems = upload.parseRequest(request);
    String strNodeRef = null;
    String strFilename = null;
    String strReturnPage = null;
    File file = null;
    for (FileItem item : fileItems) {
        if (item.isFormField() && item.getFieldName().equals("return-page")) {
            strReturnPage = item.getString();
        } else if (item.isFormField() && item.getFieldName().equals("nodeRef")) {
            strNodeRef = item.getString();
        } else {
            strFilename = FilenameUtils.getName(item.getName());
            file = TempFileProvider.createTempFile("alfresco", ".upload");
            item.write(file);
        }
    }
    if (logger.isDebugEnabled())
        logger.debug("Ajax content update request: " + strFilename + " to nodeRef: " + strNodeRef + " return page: " + strReturnPage);
    try {
        if (file != null && strNodeRef != null && strNodeRef.length() != 0) {
            NodeRef nodeRef = new NodeRef(strNodeRef);
            if (nodeRef != null) {
                ServiceRegistry services = Repository.getServiceRegistry(fc);
                // get a writer for the content and put the file
                ContentWriter writer = services.getContentService().getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
                writer.putContent(file);
            }
        }
    } catch (Exception e) {
        strReturnPage = strReturnPage.replace("${UPLOAD_ERROR}", e.getMessage());
    }
    Document result = XMLUtil.newDocument();
    Element htmlEl = result.createElement("html");
    result.appendChild(htmlEl);
    Element bodyEl = result.createElement("body");
    htmlEl.appendChild(bodyEl);
    Element scriptEl = result.createElement("script");
    bodyEl.appendChild(scriptEl);
    scriptEl.setAttribute("type", "text/javascript");
    Node scriptText = result.createTextNode(strReturnPage);
    scriptEl.appendChild(scriptText);
    if (logger.isDebugEnabled())
        logger.debug("Content update request complete.");
    ResponseWriter out = fc.getResponseWriter();
    XMLUtil.print(result, out);
}
Also used : FacesContext(javax.faces.context.FacesContext) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) HttpServletRequest(javax.servlet.http.HttpServletRequest) FileItem(org.apache.commons.fileupload.FileItem) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ResponseWriter(javax.faces.context.ResponseWriter) ExternalContext(javax.faces.context.ExternalContext) ServiceRegistry(org.alfresco.service.ServiceRegistry) File(java.io.File)

Example 100 with FileItem

use of org.apache.commons.fileupload.FileItem in project acs-community-packaging by Alfresco.

the class AlfrescoFacesPortlet method processAction.

/**
 * Called by the portlet container to allow the portlet to process an action request.
 */
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
    Application.setInPortalServer(true);
    try {
        // Set the current locale
        I18NUtil.setLocale(getLanguage(request.getPortletSession()));
        boolean isMultipart = PortletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            if (logger.isDebugEnabled())
                logger.debug("Handling multipart request...");
            PortletSession session = request.getPortletSession();
            // get the file from the request and put it in the session
            DiskFileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List<FileItem> fileItems = upload.parseRequest(request);
            Iterator<FileItem> iter = fileItems.iterator();
            FileUploadBean bean = new FileUploadBean();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                String filename = item.getName();
                if (item.isFormField() == false) {
                    if (logger.isDebugEnabled())
                        logger.debug("Processing uploaded file: " + filename);
                    // workaround a bug in IE where the full path is returned
                    // IE is only available for Windows so only check for the Windows path separator
                    int idx = filename.lastIndexOf('\\');
                    if (idx == -1) {
                        // if there is no windows path separator check for *nix
                        idx = filename.lastIndexOf('/');
                    }
                    if (idx != -1) {
                        filename = filename.substring(idx + File.separator.length());
                    }
                    File tempFile = TempFileProvider.createTempFile("alfresco", ".upload");
                    item.write(tempFile);
                    bean.setFile(tempFile);
                    bean.setFileName(filename);
                    bean.setFilePath(tempFile.getAbsolutePath());
                    session.setAttribute(FileUploadBean.FILE_UPLOAD_BEAN_NAME, bean, PortletSession.PORTLET_SCOPE);
                }
            }
            // Set the VIEW_ID parameter to tell the faces portlet bridge to treat the request
            // as a JSF request, this will send us back to the previous page we came from.
            String lastViewId = (String) request.getPortletSession().getAttribute(SESSION_LAST_VIEW_ID);
            if (lastViewId != null) {
                response.setRenderParameter(VIEW_ID, lastViewId);
            }
        } else {
            SessionUser sessionUser = (SessionUser) request.getPortletSession().getAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE);
            User user = sessionUser instanceof User ? (User) sessionUser : null;
            if (user != null) {
                // setup the authentication context
                try {
                    WebApplicationContext ctx = (WebApplicationContext) getPortletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
                    AuthenticationService auth = (AuthenticationService) ctx.getBean("AuthenticationService");
                    auth.validate(user.getTicket());
                    // save last username into portlet preferences, get from LoginBean state
                    LoginBean loginBean = (LoginBean) request.getPortletSession().getAttribute(AuthenticationHelper.LOGIN_BEAN);
                    if (loginBean != null) {
                        // TODO: Need to login to the Portal to get a user here to store prefs against
                        // so not really a suitable solution as they get thrown away at present!
                        // Also would need to store prefs PER user - so auto login for each...?
                        String oldValue = request.getPreferences().getValue(PREF_ALF_USERNAME, null);
                        if (oldValue == null || oldValue.equals(loginBean.getUsernameInternal()) == false) {
                            if (request.getPreferences().isReadOnly(PREF_ALF_USERNAME) == false) {
                                request.getPreferences().setValue(PREF_ALF_USERNAME, loginBean.getUsernameInternal());
                                request.getPreferences().store();
                            }
                        }
                    }
                    // do the normal JSF processing
                    super.processAction(request, response);
                } catch (AuthenticationException authErr) {
                    // remove User object as it's now useless
                    request.getPortletSession().removeAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE);
                }
            } else {
                // do the normal JSF processing as we may be on the login page
                super.processAction(request, response);
            }
        }
    } catch (Throwable e) {
        if (getErrorPage() != null) {
            handleError(request, response, e);
        } else {
            logger.warn("No error page configured, re-throwing exception");
            if (e instanceof PortletException) {
                throw (PortletException) e;
            } else if (e instanceof IOException) {
                throw (IOException) e;
            } else {
                throw new PortletException(e);
            }
        }
    } finally {
        Application.setInPortalServer(false);
    }
}
Also used : User(org.alfresco.web.bean.repository.User) SessionUser(org.alfresco.repo.SessionUser) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) PortletException(javax.portlet.PortletException) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) WebApplicationContext(org.springframework.web.context.WebApplicationContext) FileItem(org.apache.commons.fileupload.FileItem) SessionUser(org.alfresco.repo.SessionUser) PortletSession(javax.portlet.PortletSession) FileUploadBean(org.alfresco.web.bean.FileUploadBean) LoginBean(org.alfresco.web.bean.LoginBean) PortletFileUpload(org.apache.commons.fileupload.portlet.PortletFileUpload) File(java.io.File) AuthenticationService(org.alfresco.service.cmr.security.AuthenticationService)

Aggregations

FileItem (org.apache.commons.fileupload.FileItem)165 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)78 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)72 FileUploadException (org.apache.commons.fileupload.FileUploadException)59 File (java.io.File)55 IOException (java.io.IOException)51 ArrayList (java.util.ArrayList)40 HashMap (java.util.HashMap)32 ServletException (javax.servlet.ServletException)30 List (java.util.List)27 InputStream (java.io.InputStream)24 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)23 DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)16 Map (java.util.Map)15 UnsupportedEncodingException (java.io.UnsupportedEncodingException)12 ServletRequestContext (org.apache.commons.fileupload.servlet.ServletRequestContext)10 Test (org.junit.Test)10 Iterator (java.util.Iterator)9 FileItemWrap (com.github.bordertech.wcomponents.file.FileItemWrap)8 Locale (java.util.Locale)8