Search in sources :

Example 1 with WOSession

use of com.webobjects.appserver.WOSession in project wonder-slim by undur.

the class AjaxFileUploadRequestHandler method handleRequest.

@Override
public WOResponse handleRequest(WORequest request) {
    WOApplication application = WOApplication.application();
    application.awake();
    try {
        WOContext context = application.createContextForRequest(request);
        WOResponse response = application.createResponseInContext(context);
        String uploadIdentifier = null;
        String uploadFileName = null;
        InputStream uploadInputStream = null;
        long streamLength = -1L;
        try {
            String sessionIdKey = WOApplication.application().sessionIdKey();
            String sessionId = request.cookieValueForKey(sessionIdKey);
            WOMultipartIterator multipartIterator = request.multipartIterator();
            if (multipartIterator == null) {
                response.appendContentString("Already Consumed!");
            } else {
                WOMultipartIterator.WOFormData formData = null;
                while ((formData = multipartIterator.nextFormData()) != null) {
                    String name = formData.name();
                    if (sessionIdKey.equals(name)) {
                        sessionId = formData.formValue();
                    } else if ("id".equals(name)) {
                        uploadIdentifier = formData.formValue();
                    } else if (formData.isFileUpload()) {
                        uploadFileName = request.stringFormValueForKey(name + ".filename");
                        streamLength = multipartIterator.contentLengthRemaining();
                        uploadInputStream = formData.formDataInputStream();
                        break;
                    }
                }
                context._setRequestSessionID(sessionId);
                WOSession session = null;
                if (context._requestSessionID() != null) {
                    session = WOApplication.application().restoreSessionWithID(sessionId, context);
                }
                if (session == null) {
                    throw new Exception("No valid session!");
                }
                File tempFile = File.createTempFile("AjaxFileUpload", ".tmp", _tempFileFolder);
                tempFile.deleteOnExit();
                AjaxUploadProgress progress = new AjaxUploadProgress(uploadIdentifier, tempFile, uploadFileName, streamLength);
                try {
                    AjaxProgressBar.registerProgress(session, progress);
                } finally {
                    if (context._requestSessionID() != null) {
                        WOApplication.application().saveSessionForContext(context);
                    }
                }
                if (formData != null) {
                    NSArray<String> contentType = (NSArray<String>) formData.headers().valueForKey("content-type");
                    if (contentType != null) {
                        progress.setContentType(contentType.objectAtIndex(0));
                    }
                }
                try {
                    if (_maxUploadSize >= 0L && streamLength > _maxUploadSize) {
                        IOException e = new IOException("You attempted to upload a file larger than the maximum allowed size of " + new ERXUnitAwareDecimalFormat(ERXUnitAwareDecimalFormat.BYTE).format(_maxUploadSize) + ".");
                        progress.setFailure(e);
                        progress.dispose();
                        throw e;
                    }
                    try (FileOutputStream fos = new FileOutputStream(progress.tempFile())) {
                        progress.copyAndTrack(uploadInputStream, fos, _maxUploadSize);
                    }
                    if (!progress.isCanceled() && !progress.shouldReset()) {
                        downloadFinished(progress);
                    }
                } finally {
                    progress.setDone(true);
                }
            }
        } catch (Throwable t) {
            log.error("Upload failed", t);
            response.appendContentString("Failed: " + t.getMessage());
        } finally {
            if (uploadInputStream != null) {
                try {
                    uploadInputStream.close();
                } catch (IOException e) {
                // ignore
                }
            }
        }
        return response;
    } finally {
        application.sleep();
    }
}
Also used : NSArray(com.webobjects.foundation.NSArray) InputStream(java.io.InputStream) WOMultipartIterator(com.webobjects.appserver.WOMultipartIterator) IOException(java.io.IOException) ERXUnitAwareDecimalFormat(er.extensions.formatters.ERXUnitAwareDecimalFormat) IOException(java.io.IOException) FileOutputStream(java.io.FileOutputStream) WOContext(com.webobjects.appserver.WOContext) WOSession(com.webobjects.appserver.WOSession) WOResponse(com.webobjects.appserver.WOResponse) File(java.io.File) WOApplication(com.webobjects.appserver.WOApplication)

Example 2 with WOSession

use of com.webobjects.appserver.WOSession in project wonder-slim by undur.

the class ERXRedirect method appendToResponse.

@Override
public void appendToResponse(WOResponse response, WOContext context) {
    String url;
    // Use secure binding if present, otherwise default to request setting
    boolean secure = (_secure == null) ? ERXRequest.isRequestSecure(context.request()) : _secure.booleanValue();
    // Check whether we are currently generating complete URL's. We'll use this in finally() to reset the context to it's behavior before calling this.
    boolean generatingCompleteURLs = context.doesGenerateCompleteURLs();
    // Generate a full URL if changing between secure and insecure
    boolean generateCompleteURLs = secure != ERXRequest.isRequestSecure(context.request());
    if (generateCompleteURLs) {
        context.generateCompleteURLs();
    }
    try {
        WOComponent component = _component;
        if (component != null) {
            // Build request handler path with session ID if needed
            WOSession aSession = session();
            String aContextId = context.contextID();
            StringBuilder requestHandlerPath = new StringBuilder();
            if (WOApplication.application().pageCacheSize() == 0) {
                if (aSession.storesIDsInURLs()) {
                    requestHandlerPath.append(component.name());
                    requestHandlerPath.append('/');
                    requestHandlerPath.append(aSession.sessionID());
                    requestHandlerPath.append('/');
                    requestHandlerPath.append(aContextId);
                    requestHandlerPath.append(".0");
                } else {
                    requestHandlerPath.append(component.name());
                    requestHandlerPath.append('/');
                    requestHandlerPath.append(aContextId);
                    requestHandlerPath.append(".0");
                }
            } else if (aSession.storesIDsInURLs()) {
                requestHandlerPath.append(aSession.sessionID());
                requestHandlerPath.append('/');
                requestHandlerPath.append(aContextId);
                requestHandlerPath.append(".0");
            } else {
                requestHandlerPath.append(aContextId);
                requestHandlerPath.append(".0");
            }
            url = context._urlWithRequestHandlerKey(WOApplication.application().componentRequestHandlerKey(), requestHandlerPath.toString(), queryParametersString(), secure);
            context._setPageComponent(component);
        } else if (_url != null) {
            if (_secure != null) {
                throw new IllegalArgumentException("You specified a value for 'url' and for 'secure', which is not supported.");
            }
            url = _url;
            // the external url don't need it but if the url is a internal CMS Link then queryParamers is nice to have
            if (_queryParameters != null && _queryParameters.count() > 0)
                url += "?" + queryParametersString();
        } else if (_requestHandlerKey != null) {
            url = context._urlWithRequestHandlerKey(_requestHandlerKey, _requestHandlerPath, queryParametersString(), secure);
        } else if (_directActionName != null) {
            String requestHandlerPath;
            if (_directActionClass != null) {
                requestHandlerPath = _directActionClass + "/" + _directActionName;
            } else {
                requestHandlerPath = _directActionName;
            }
            url = context.directActionURLForActionNamed(requestHandlerPath, directActionQueryParameters(), secure, 0, false);
        } else {
            throw new IllegalStateException("You must provide a component, url, requestHandlerKey, or directActionName to this ERXRedirect.");
        }
        if (ERXAjaxApplication.isAjaxRequest(context.request())) {
            boolean hasUpdateContainer = context.request().stringFormValueForKey(ERXAjaxApplication.KEY_UPDATE_CONTAINER_ID) != null;
            if (hasUpdateContainer) {
                response.appendContentString("<script type=\"text/javascript\">");
            } else {
                response.setHeader("text/javascript", "Content-Type");
            }
            response.appendContentString("document.location.href='" + url + "';");
            if (hasUpdateContainer) {
                response.appendContentString("</script>");
            }
        } else {
            response.setHeader(url, "location");
            response.setStatus(302);
        }
        if (component != null) {
            ERXAjaxApplication.setForceStorePage(response);
        }
    } finally {
        // Switch the context back to the original url behaviour.
        if (generatingCompleteURLs) {
            context.generateCompleteURLs();
        } else {
            context.generateRelativeURLs();
        }
    }
}
Also used : WOComponent(com.webobjects.appserver.WOComponent) WOSession(com.webobjects.appserver.WOSession)

Example 3 with WOSession

use of com.webobjects.appserver.WOSession in project wonder-slim by undur.

the class ERXComponentRequestHandler method _handleRequest.

WOResponse _handleRequest(WORequest aRequest) {
    WOContext aContext = null;
    WOResponse aResponse;
    NSDictionary requestHandlerValues = requestHandlerValuesForRequest(aRequest);
    WOApplication anApplication = WOApplication.application();
    String aSessionID = (String) requestHandlerValues.objectForKey(WOApplication.application().sessionIdKey());
    if ((!anApplication.isRefusingNewSessions()) || (aSessionID != null)) {
        String aSenderID = (String) requestHandlerValues.objectForKey("woeid");
        String oldContextID = (String) requestHandlerValues.objectForKey("wocid");
        WOStatisticsStore aStatisticsStore = anApplication.statisticsStore();
        if (aStatisticsStore != null)
            aStatisticsStore.applicationWillHandleComponentActionRequest();
        try {
            aContext = anApplication.createContextForRequest(aRequest);
            aContext._setRequestContextID(oldContextID);
            aContext._setSenderID(aSenderID);
            anApplication.awake();
            aResponse = _dispatchWithPreparedApplication(anApplication, aContext, requestHandlerValues);
            NSNotificationCenter.defaultCenter().postNotification(WORequestHandler.DidHandleRequestNotification, aContext);
            anApplication.sleep();
        } catch (Exception exception) {
            try {
                NSLog.err.appendln("<" + getClass().getName() + ">: Exception occurred while handling request:\n" + exception.toString());
                if (NSLog.debugLoggingAllowedForLevelAndGroups(1, 4L)) {
                    NSLog.debug.appendln(exception);
                }
                if (aContext == null)
                    aContext = anApplication.createContextForRequest(aRequest);
                else {
                    aContext._putAwakeComponentsToSleep();
                }
                WOSession aSession = aContext._session();
                aResponse = anApplication.handleException(exception, aContext);
                if (aSession != null) {
                    try {
                        anApplication.saveSessionForContext(aContext);
                        anApplication.sleep();
                    } catch (Exception eAgain) {
                        NSLog.err.appendln("<WOApplication '" + anApplication.name() + "'>: Another Exception  occurred while trying to clean the application:\n" + eAgain.toString());
                        if (NSLog.debugLoggingAllowedForLevelAndGroups(1, 4L))
                            NSLog.debug.appendln(eAgain);
                    }
                }
            } finally {
                if ((aContext != null) && (aContext._session() != null))
                    anApplication.saveSessionForContext(aContext);
            }
        }
        if (aResponse != null) {
            aResponse._finalizeInContext(aContext);
        }
        if (aStatisticsStore != null) {
            WOComponent aPage = aContext.page();
            String aName = null;
            if (aPage != null) {
                aName = aPage.name();
            }
            aStatisticsStore.applicationDidHandleComponentActionRequestWithPageNamed(aName);
        }
    } else {
        String newLocationURL = anApplication._newLocationForRequest(aRequest);
        String contentString = "Sorry, your request could not immediately be processed. Please try this URL: <a href=\"" + newLocationURL + "\">" + newLocationURL + "</a>";
        aResponse = anApplication.createResponseInContext(null);
        WOResponse._redirectResponse(aResponse, newLocationURL, contentString);
        aResponse._finalizeInContext(null);
    }
    return aResponse;
}
Also used : NSDictionary(com.webobjects.foundation.NSDictionary) WOComponent(com.webobjects.appserver.WOComponent) WOContext(com.webobjects.appserver.WOContext) WOSession(com.webobjects.appserver.WOSession) WOStatisticsStore(com.webobjects.appserver.WOStatisticsStore) WOResponse(com.webobjects.appserver.WOResponse) WOApplication(com.webobjects.appserver.WOApplication)

Example 4 with WOSession

use of com.webobjects.appserver.WOSession in project wonder-slim by undur.

the class ERXComponentRequestHandler method _dispatchWithPreparedApplication.

private WOResponse _dispatchWithPreparedApplication(WOApplication anApplication, WOContext aContext, NSDictionary someElements) {
    WOSession aSession = null;
    WOResponse aResponse = null;
    WOResponse errorResponse = null;
    String aSessionID = (String) someElements.objectForKey(WOApplication.application().sessionIdKey());
    if (aSessionID == null) {
        aSession = anApplication._initializeSessionInContext(aContext);
        if (aSession == null)
            errorResponse = anApplication.handleSessionCreationErrorInContext(aContext);
    } else {
        aSession = anApplication.restoreSessionWithID(aSessionID, aContext);
        if (aSession == null) {
            errorResponse = anApplication.handleSessionRestorationErrorInContext(aContext);
        }
    }
    if (errorResponse == null) {
        aResponse = _dispatchWithPreparedSession(aSession, aContext, someElements);
    } else
        aResponse = errorResponse;
    aContext._putAwakeComponentsToSleep();
    anApplication.saveSessionForContext(aContext);
    return aResponse;
}
Also used : WOSession(com.webobjects.appserver.WOSession) WOResponse(com.webobjects.appserver.WOResponse)

Example 5 with WOSession

use of com.webobjects.appserver.WOSession in project wonder-slim by undur.

the class JSONRequestHandler method handleRequest.

@SuppressWarnings("unchecked")
@Override
public WOResponse handleRequest(WORequest request) {
    WOApplication application = WOApplication.application();
    application.awake();
    try {
        WOContext context = application.createContextForRequest(request);
        WOResponse response = application.createResponseInContext(context);
        Object output;
        try {
            String inputString = request.contentString();
            JSONObject input = new JSONObject(inputString);
            String sessionIdKey = WOApplication.application().sessionIdKey();
            String sessionId = request.cookieValueForKey(sessionIdKey);
            if (sessionId == null) {
                ERXMutableURL url = new ERXMutableURL();
                url.setQueryParameters(request.queryString());
                sessionId = url.queryParameter(sessionIdKey);
                if (sessionId == null && input.has(sessionIdKey)) {
                    sessionId = input.getString(sessionIdKey);
                }
            }
            context._setRequestSessionID(sessionId);
            WOSession session = null;
            if (context._requestSessionID() != null) {
                session = WOApplication.application().restoreSessionWithID(sessionId, context);
            }
            if (session != null) {
                session.awake();
            }
            try {
                JSONComponentCallback componentCallback = null;
                WODynamicURL url = request._uriDecomposed();
                String requestHandlerPath = url.requestHandlerPath();
                JSONRPCBridge jsonBridge;
                if (requestHandlerPath != null && requestHandlerPath.length() > 0) {
                    String componentNameAndInstance = requestHandlerPath;
                    String componentInstance;
                    String componentName;
                    int slashIndex = componentNameAndInstance.indexOf('/');
                    if (slashIndex == -1) {
                        componentName = componentNameAndInstance;
                        componentInstance = null;
                    } else {
                        componentName = componentNameAndInstance.substring(0, slashIndex);
                        componentInstance = componentNameAndInstance.substring(slashIndex + 1);
                    }
                    if (session == null) {
                        session = context.session();
                    }
                    String bridgesKey = (componentInstance == null) ? "_JSONGlobalBridges" : "_JSONInstanceBridges";
                    Map<String, JSONRPCBridge> componentBridges = (Map<String, JSONRPCBridge>) session.objectForKey(bridgesKey);
                    if (componentBridges == null) {
                        int limit = ERXProperties.intForKeyWithDefault((componentInstance == null) ? "er.ajax.json.globalBacktrackCacheSize" : "er.ajax.json.backtrackCacheSize", WOApplication.application().pageCacheSize());
                        componentBridges = new LRUMap<>(limit);
                        session.setObjectForKey(componentBridges, bridgesKey);
                    }
                    jsonBridge = componentBridges.get(componentNameAndInstance);
                    if (jsonBridge == null) {
                        Class componentClass = _NSUtilities.classWithName(componentName);
                        JSONComponent component;
                        if (JSONComponent.class.isAssignableFrom(componentClass)) {
                            component = (JSONComponent) _NSUtilities.instantiateObject(componentClass, new Class[] { WOContext.class }, new Object[] { context }, true, false);
                        } else {
                            throw new SecurityException("There is no JSON component named '" + componentName + "'.");
                        }
                        jsonBridge = createBridgeForComponent(component, componentName, componentInstance, componentBridges);
                    }
                    componentCallback = new JSONComponentCallback(context);
                    jsonBridge.registerCallback(componentCallback, WOContext.class);
                } else {
                    jsonBridge = _sharedBridge;
                }
                try {
                    output = jsonBridge.call(new Object[] { request, response, context }, input);
                } finally {
                    if (componentCallback != null) {
                        jsonBridge.unregisterCallback(componentCallback, WOContext.class);
                    }
                }
                if (context._session() != null) {
                    WOSession contextSession = context._session();
                    // If this is a new session, then we have to force it to be a cookie session
                    if (sessionId == null) {
                        boolean storesIDsInCookies = contextSession.storesIDsInCookies();
                        try {
                            contextSession.setStoresIDsInCookies(true);
                            contextSession._appendCookieToResponse(response);
                        } finally {
                            contextSession.setStoresIDsInCookies(storesIDsInCookies);
                        }
                    } else {
                        contextSession._appendCookieToResponse(response);
                    }
                }
                response.appendContentString(output.toString());
                response._finalizeInContext(context);
                response.disableClientCaching();
            } finally {
                try {
                    if (session != null) {
                        session.sleep();
                    }
                } finally {
                    if (context._session() != null) {
                        WOApplication.application().saveSessionForContext(context);
                    }
                }
            }
        } catch (NoSuchElementException e) {
            e.printStackTrace();
            output = new JSONRPCResult(JSONRPCResult.CODE_ERR_NOMETHOD, null, JSONRPCResult.MSG_ERR_NOMETHOD);
        } catch (JSONException e) {
            e.printStackTrace();
            output = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE);
        } catch (Throwable t) {
            t.printStackTrace();
            output = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, t.getMessage());
        }
        return response;
    } finally {
        application.sleep();
    }
}
Also used : ERXMutableURL(er.extensions.foundation.ERXMutableURL) WODynamicURL(com.webobjects.appserver.WODynamicURL) JSONRPCBridge(org.jabsorb.JSONRPCBridge) JSONException(org.json.JSONException) JSONRPCResult(org.jabsorb.JSONRPCResult) JSONObject(org.json.JSONObject) WOContext(com.webobjects.appserver.WOContext) WOSession(com.webobjects.appserver.WOSession) JSONObject(org.json.JSONObject) WOResponse(com.webobjects.appserver.WOResponse) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) WOApplication(com.webobjects.appserver.WOApplication) NoSuchElementException(java.util.NoSuchElementException)

Aggregations

WOSession (com.webobjects.appserver.WOSession)5 WOResponse (com.webobjects.appserver.WOResponse)4 WOApplication (com.webobjects.appserver.WOApplication)3 WOContext (com.webobjects.appserver.WOContext)3 WOComponent (com.webobjects.appserver.WOComponent)2 WODynamicURL (com.webobjects.appserver.WODynamicURL)1 WOMultipartIterator (com.webobjects.appserver.WOMultipartIterator)1 WOStatisticsStore (com.webobjects.appserver.WOStatisticsStore)1 NSArray (com.webobjects.foundation.NSArray)1 NSDictionary (com.webobjects.foundation.NSDictionary)1 ERXUnitAwareDecimalFormat (er.extensions.formatters.ERXUnitAwareDecimalFormat)1 ERXMutableURL (er.extensions.foundation.ERXMutableURL)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 NoSuchElementException (java.util.NoSuchElementException)1 JSONRPCBridge (org.jabsorb.JSONRPCBridge)1