/** Abort an ongoing upload or download. */ private void abort(String objectId) { final RequestContext context; synchronized (activeRequests) { context = activeRequests.remove(objectId); } if (context != null) { File file = context.targetFile; if (file != null) { file.delete(); } // Trigger the abort callback immediately to minimize latency between it and abort() being // called. JSONObject error = createFileTransferError(ABORTED_ERR, context.source, context.target, null, -1); synchronized (context) { context.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); context.aborted = true; } // Closing the streams can block, so execute on a background thread. cordova .getThreadPool() .execute( new Runnable() { public void run() { synchronized (context) { safeClose(context.currentInputStream); safeClose(context.currentOutputStream); } } }); } }
public static Admin validateCredentials(RequestContext request) { String username = request.getRequestUsername(); Admin admin = AdminMapper.retrieveAdmin(username); if (admin != null && admin.getPassword().equals(request.getRequestPassword())) { return admin; } else { return null; } }
@Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; request.setCharacterEncoding(httpEncoding); response.setCharacterEncoding(httpEncoding); String path = RequestUtils.getPathInfo(request); if (httpCache == false) { ResponseUtils.setBufferOff(response); } if (bypassRequestUrls != null && bypassRequestUrls.accept(request, path)) { chain.doFilter(request, response); return; } HttpMethod httpMethod = HttpMethod.valueOf(request.getMethod()); if (corsRequestProcessor != null) { corsRequestProcessor.setHeaders(request, response); if (httpMethod == HttpMethod.OPTIONS) { response.setStatus(HttpServletResponse.SC_OK); return; } } RouteInfo route = router.lookup(request, path, httpMethod); request = fileUploadResolver.transform(request); RequestContext ctx = new RequestContext(request, response, path, httpMethod, route); try { if (route == null || route == RouteInfo.NOT_FOUND) { throw new ActionNotFoundException(path); } InterceptorChainImpl interceptorChain = new InterceptorChainImpl(WebConfig.getInterceptors(), ctx); interceptorChain.invoke(); ResultInfo result = interceptorChain.getResult(); if (result != null) { ResultHandler<Object> handler = resultHandlerResolver.lookup(result.getResultClass()); handler.handle(ctx, result.getResultObject()); } } catch (Exception e) { handleError(ctx, e); } finally { if (ctx != null) { ctx.destory(); } } }
private HandshakeRequest createHandshakeRequest(final UpgradeRequest webSocketRequest) { if (webSocketRequest instanceof RequestContext) { final RequestContext requestContext = (RequestContext) webSocketRequest; // TYRUS-208; spec requests headers to be read only when passed to // ServerEndpointConfig.Configurator#modifyHandshake. // TYRUS-211; spec requests parameterMap to be read only when passed to // ServerEndpointConfig.Configurator#modifyHandshake. requestContext.lock(); return requestContext; } return null; }
/** * Invoke an HTTP GET request on a remote host. You must close the InputStream after you are done * with. * * @param path The request path * @param parameters The parameters (collection of Parameter objects) * @return The Response */ @Override public com.flickr4java.flickr.Response get( String path, Map<String, Object> parameters, String sharedSecret) { OAuthRequest request = new OAuthRequest(Verb.GET, API_HOST + path); for (Map.Entry<String, Object> entry : parameters.entrySet()) { request.addQuerystringParameter(entry.getKey(), String.valueOf(entry.getValue())); } if (proxyAuth) { request.addHeader("Proxy-Authorization", "Basic " + getProxyCredentials()); } RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null) { Token requestToken = new Token(auth.getToken(), auth.getTokenSecret()); OAuthService service = createOAuthService(parameters, sharedSecret); service.signRequest(requestToken, request); } if (Flickr.debugRequest) { logger.debug("GET: " + request.getCompleteUrl()); } setTimeouts(request); org.scribe.model.Response scribeResponse = request.send(); try { com.flickr4java.flickr.Response response = null; synchronized (mutex) { String strXml = scribeResponse.getBody(); if (Flickr.debugStream) { logger.debug(strXml); } Document document = builder.parse(new InputSource(new StringReader(strXml))); response = (com.flickr4java.flickr.Response) responseClass.newInstance(); response.parse(document); } return response; } catch (IllegalAccessException e) { throw new FlickrRuntimeException(e); } catch (InstantiationException e) { throw new FlickrRuntimeException(e); } catch (SAXException e) { throw new FlickrRuntimeException(e); } catch (IOException e) { throw new FlickrRuntimeException(e); } }
@Override protected boolean onCreateRequest(RequestContext context) { GwtUtils.log( getClass(), "onCreateRequest", "service = " + getServiceName() + ", methodName = " + context.getMethodName() + " serviceEntryPoint = " + context.getServiceEntryPoint()); showWaitPanelIfRequired(context); return true; }
@Override protected boolean onResponseReceived(RequestContext context) { GwtUtils.log( getClass(), "onResponseReceived", "service = " + getServiceName() + ", methodName = " + context.getMethodName() + " response.statusCode = " + context.getResponse().getStatusCode()); hideWaitPanelIfRequired(context); return true; }
/** * Returns the title of the <code>WebPage</code> corresponding to the <code>RequestContext</code>. * The page may need to be partially executed. * * @param ctx */ public static String getTitle(WebPage page, RequestContext ctx) throws Exception { // Attach the request context to this thread RequestContext prevCtx = RequestContext.setCurrent(ctx); try { // Check authorization if (page.isAuthorized() == false) { throw new UnauthorizedException(); } page.init(); return page.getTitle(); } finally { // Restore the request context for this thread RequestContext.setCurrent(prevCtx); } }
protected OAuthProvider getOAuthProvider() { // Try requestContext first. Otherwise obtain OAuthProvider via API OAuthProvider provider = requestContext.getOAuthProvider(oauthProviderKey); return provider != null ? provider : PortalRequest.getInstance().getPortal().getOAuthProvider(oauthProviderKey); }
// Read access token from DB and display error message if it's not available protected AccessToken loadAccessTokenOrRedirectToObtainIt( String username, OAuthProvider oauthProvider, RenderRequest request, RenderResponse response) throws IOException, PortletException { // Try requestContext first. Otherwise obtain OAuthProvider via API AccessToken accessToken = requestContext.getAccessToken(oauthProviderKey); if (accessToken == null) { accessToken = oauthProvider.loadAccessToken(username); } if (accessToken == null) { // Will be processed by method AbstractSocialPortlet.actionRedirectToOAuthFlow PortletURL actionURL = response.createActionURL(); actionURL.setParameter( ActionRequest.ACTION_NAME, AbstractSocialPortlet.ACTION_OAUTH_REDIRECT); request.setAttribute( ATTRIBUTE_ERROR_MESSAGE, oauthProvider.getFriendlyName() + " access token not available for you."); request.setAttribute(ATTRIBUTE_OAUTH_PROVIDER, oauthProvider); PortletRequestDispatcher prd = filterConfig.getPortletContext().getRequestDispatcher("/jsp/error/token.jsp"); prd.include(request, response); } return accessToken; }
private void setHeaders(NewPagination newPagination) { requestContext .resourceExtension() .ifPresent( ext -> httpServletResponseAdapter.addContentDispositionHeader( requestContext.getRegisterPrimaryKey() + "-entries." + ext)); if (newPagination.hasNextPage()) { httpServletResponseAdapter.addLinkHeader("next", newPagination.getNextPageLink()); } if (newPagination.hasPreviousPage()) { httpServletResponseAdapter.addLinkHeader("previous", newPagination.getPreviousPageLink()); } }
/** * @param logMessage This is optional * @return */ public WebApplicationException create403RESTException(String logMessage) { Response errorResponse = Response.status(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN).build(); WebApplicationException restException = new WebApplicationException(errorResponse); restException.fillInStackTrace(); // TODO:Future:Open: Need to log all these and add user to // block list if this is deliberate // Get user information UserSessionBase userSession = ContextUtil.getCurrentUserSession(); Long sessionId = null; String loginId = null; String sessionInfo = ""; if (userSession != null) { loginId = userSession.getLoginId(); sessionInfo = userSession.toString(); sessionId = userSession.getSessionId(); } String requestInfo = ""; try { RequestContext reqContext = ContextUtil.getCurrentRequestContext(); if (reqContext != null) { requestInfo = reqContext.toString(); requestInfo += ", timeTaken=" + (System.currentTimeMillis() - reqContext.getStartTime()); } } catch (Throwable contextEx) { logger.error("Error getting request info", contextEx); } logger.error( "Access restricted. SessionId=" + sessionId + ", loginId=" + loginId + ", logMessage=" + logMessage + ", requestInfo=" + requestInfo + ", sessionInfo=" + sessionInfo, restException); return restException; }
/** * Authenticates the administrator. Dervived classes needs to call this method from the dervived * method, <code>handleRequest(RequestContext rc)</code>. Override this method to get user name * and passowrd. * * @param rc Request Context. * @throws CLIException if authentication fails. */ @Override public void handleRequest(RequestContext rc) throws CLIException { super.handleRequest(rc); ssoToken = rc.getCLIRequest().getSSOToken(); if (ssoToken == null) { adminID = getStringOptionValue(AccessManagerConstants.ARGUMENT_ADMIN_ID); adminPassword = getPassword(); } }
public Object visit(KindedPointcut node, Object parent, RequestContext context) { context.kinds &= node.couldMatchKinds(); if (node.getKind().bit == Shadow.FieldGetBit || node.getKind().bit == Shadow.FieldSetBit) { context.targetFilters.add(node.getSignature()); } else { context.thisFilters.add(node.getSignature()); } installIfNotBelowAnd(parent, context); return null; }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (null != request.getAttribute("FLAG")) { chain.doFilter(request, response); return; } request.setAttribute("FLAG", FLAG); String encoding = this.encoding; HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; String resourcePath = req.getServletPath(); RequestContext requestContext = new RequestContext(config.getServletContext(), req, resourcePath); request.setAttribute("context", requestContext); for (Decorator decorator : decorators) { int returned = decorator.parseRequest(req, res, requestContext); switch (returned) { case Decorator.OK: // do nothing break; case Decorator.REDIRECT: res.sendRedirect(requestContext.getResourcePath()); return; case Decorator.MOVED_PERMANENTLY: res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); res.setHeader("Location", requestContext.getResourcePath()); return; default: // do nothing } } if (pattern.matcher(requestContext.getResourcePath()).matches()) { WebContent content = new WebContent(); if (requestContext.getResourcePath().startsWith("/WEB-INF/admin/")) { encoding = "UTF-8"; } ByteArrayResponseWrapper wrapper = new ByteArrayResponseWrapper(res); request.getRequestDispatcher(requestContext.getResourcePath()).include(req, wrapper); wrapper.finish(); content.setWholeContent(wrapper.getString(encoding)); response.setContentType(wrapper.getContentType()); content.finish(); for (Decorator decorator : decorators) { decorator.decorate(requestContext, content, content); content.finish(); } byte[] theContent = content.toString().getBytes(encoding); response.setContentLength(theContent.length); response.getOutputStream().write(theContent); return; } request.getRequestDispatcher(requestContext.getResourcePath()).forward(req, res); }
@Override protected boolean onError(RequestContext context, Throwable exception) { GwtUtils.log( getClass(), "onError", "service = " + getServiceName() + ", methodName = " + context.getMethodName() + " ex.class = " + exception.getClass().getName() + " ex.message = " + exception.getMessage()); hideWaitPanelIfRequired(context); if (getServicePropertyBoolean(context.getMethodName(), "vetoOnFailureCallback", false)) { GwtUtils.log(getClass(), "onError", "vetoOnFailureCallback is ON"); return false; } if (exception.getMessage() != null && exception.getMessage().equals("0")) { return false; } return true; }
// FLICKR AUTHENTICATION HELPER FUNCTIONS // Attempts to authneticate with a given token public void authenticateWithToken(String _token) { AuthInterface authInterface = flickr.getAuthInterface(); // make sure the token is legit try { authInterface.checkToken(_token); } catch (Exception e) { println("Token is bad, getting a new one"); getAuthentication(); return; } auth = new Auth(); RequestContext requestContext = RequestContext.getRequestContext(); requestContext.setSharedSecret(secretKey); requestContext.setAuth(auth); auth.setToken(_token); auth.setPermission(Permission.WRITE); flickr.setAuth(auth); println("Authentication success"); }
private void showWaitPanelIfRequired(RequestContext context) { if (getServicePropertyBoolean(context.getMethodName(), "showWaitPanel", false)) { GwtUtils.log(getClass(), "showWaitPanelIfRequired", "showWaitPanel = true"); if (waitPanel == null) { waitPanel = new PopupPanel(); GwtUtils.setStyleAttribute(waitPanel, "border", "none"); GwtUtils.setStyleAttribute(waitPanel, "background", "transparent"); waitPanel.setGlassEnabled(false); waitPanel.setAnimationEnabled(true); Image waitingImg = new Image(UriUtils.fromTrustedString("/images/commons/transp-loading.gif")); waitPanel.setWidget(waitingImg); } GwtUtils.showWait(waitPanel); } }
protected ChannelBuffer mapSlave(Channel channel, RequestContext slave) { synchronized (connectedSlaveChannels) { // Checking for machineId -1 excludes the "empty" slave contexts // which some communication points pass in as context. if (slave != null && slave.machineId() != RequestContext.EMPTY.machineId()) { Pair<RequestContext, AtomicLong> previous = connectedSlaveChannels.get(channel); if (previous != null) { previous.other().set(System.currentTimeMillis()); } else { connectedSlaveChannels.put( channel, Pair.of(slave, new AtomicLong(System.currentTimeMillis()))); } } } return ChannelBuffers.dynamicBuffer(); }
public Object visit(ConcreteCflowPointcut node, Object parent, RequestContext context) { if (parent instanceof NotPointcut) { if (context.cflowCounterGuard != null) { throw new IllegalArgumentException("More than one cflow per pointcut is not supported"); } // Cheating to extract the counter field since it's not exposed :( try { context.cflowCounterGuard = (Member) cflowFieldField.get(node); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } return null; }
@Override public boolean authenticate(RequestContext context, String header) { if (header == null || "".equals(header)) return false; try { Pair<String, String> credentials = decodeAuthentication(header); if (credentials == null) return false; Long userid = authenticateUser(context, credentials.getFirst(), credentials.getSecond()); if (userid == null) return false; context.setAuthenticatedUser(userid); return true; } catch (Exception e) { log.error("Error during Basic authentication", e); } return false; }
@Override public void doFilter(ActionRequest request, ActionResponse response, FilterChain chain) throws IOException, PortletException { String username = request.getRemoteUser(); OAuthProvider oauthProvider = getOAuthProvider(); AccessToken accessToken; if (username != null && oauthProvider != null) { accessToken = oauthProvider.loadAccessToken(username); } else { accessToken = null; } if (oauthProvider != null) { requestContext.saveOAuthInfo(oauthProvider, accessToken); } chain.doFilter(request, response); }
public void setUp() throws Exception { BaseContext.pushContext(); SecurityContext securityContext = new SecurityContext(null, null); SecurityContext.setSecurityContext(securityContext); RequestContext requestContext = new RequestContext( mockRequest, securityContext, mockService, null, getRequestPath(), null, false, false, true, mockRepository); RequestContext.setRequestContext(requestContext); }
private void handleError(RequestContext ctx, Exception e) throws IOException, ServletException { ctx.getRequest().setAttribute(ExceptionHandler.KEY_IN_REQUEST, e); if (exceptionHandler != null) { try { exceptionHandler.handleError(ctx, e); return; } catch (Exception ex) { e = ex; } } if (e instanceof RuntimeException) { throw (RuntimeException) e; } if (e instanceof IOException) { throw (IOException) e; } if (e instanceof ServletException) { throw (ServletException) e; } throw new ServletException(e); }
@Override public void doFilter(RenderRequest request, RenderResponse response, FilterChain chain) throws IOException, PortletException { String username = request.getRemoteUser(); if (username == null) { request.setAttribute( ATTRIBUTE_ERROR_MESSAGE, "No content available for anonymous user. You need to login first."); PortletRequestDispatcher prd = filterConfig.getPortletContext().getRequestDispatcher("/jsp/error/error.jsp"); prd.include(request, response); return; } OAuthProvider oauthProvider = getOAuthProvider(); if (oauthProvider == null) { String errorMessage = "OAuth provider '" + oauthProviderKey + "' not available"; request.setAttribute(ATTRIBUTE_ERROR_MESSAGE, errorMessage); PortletRequestDispatcher prd = filterConfig.getPortletContext().getRequestDispatcher("/jsp/error/error.jsp"); prd.include(request, response); return; } AccessToken accessToken = loadAccessTokenOrRedirectToObtainIt(username, oauthProvider, request, response); if (accessToken != null) { accessToken = validateAccessToken(request, response, oauthProvider, accessToken); if (accessToken != null) { requestContext.saveOAuthInfo(oauthProvider, accessToken); chain.doFilter(request, response); } } }
/** * Client side only - compose the {@link UpgradeRequest} and store it for further use. * * @return composed {@link UpgradeRequest}. */ public UpgradeRequest prepareRequest() { Map<String, List<String>> requestHeaders = request.getHeaders(); updateHostAndOrigin(request); requestHeaders.put( UpgradeRequest.CONNECTION, Collections.singletonList(UpgradeRequest.UPGRADE)); requestHeaders.put(UpgradeRequest.UPGRADE, Collections.singletonList(UpgradeRequest.WEBSOCKET)); requestHeaders.put( HandshakeRequest.SEC_WEBSOCKET_KEY, Collections.singletonList(secKey.toString())); requestHeaders.put(HandshakeRequest.SEC_WEBSOCKET_VERSION, Collections.singletonList(VERSION)); if (!subProtocols.isEmpty()) { requestHeaders.put( HandshakeRequest.SEC_WEBSOCKET_PROTOCOL, Collections.singletonList(Utils.getHeaderFromList(subProtocols, null))); } if (!extensions.isEmpty()) { requestHeaders.put( HandshakeRequest.SEC_WEBSOCKET_EXTENSIONS, Collections.singletonList( Utils.getHeaderFromList( extensions, new Utils.Stringifier<Extension>() { @Override String toString(Extension extension) { return TyrusExtension.toString(extension); } }))); } return request; }
/** * Routes the current exception to an error endpoint such as a Dead Letter Queue (jms) This method * is only invoked if there is a UMOMassage available to dispatch. The message dispatched from * this method will be an <code>ExceptionMessage</code> which contains the exception thrown the * UMOMessage and any context information. * * @param message the UMOMessage being processed when the exception occurred * @param failedEndpoint optional; the endpoint being dispatched or recieved on when the error * occurred. This is NOT the endpoint that the message will be disptched on and is only * supplied to this method for logging purposes * @param t the exception thrown. This will be sent with the ExceptionMessage * @see ExceptionMessage */ protected void routeException(UMOMessage message, UMOEndpoint failedEndpoint, Throwable t) { UMOEndpoint endpoint = getEndpoint(t); if (endpoint != null) { try { logger.error( "Message being processed is: " + (message == null ? "null" : message.toString())); UMOEventContext ctx = RequestContext.getEventContext(); ExceptionMessage msg = null; if (failedEndpoint != null) { msg = new ExceptionMessage(getErrorMessagePayload(message), endpoint, t, ctx); } else { msg = new ExceptionMessage(getErrorMessagePayload(message), t, ctx); } ctx.sendEvent(new MuleMessage(msg, null), endpoint); logger.debug("routed Exception message via " + endpoint); } catch (UMOException e) { logFatal(message, e); } } else { markTransactionForRollback(); } }
private void hideWaitPanelIfRequired(RequestContext context) { if (getServicePropertyBoolean(context.getMethodName(), "showWaitPanel", false)) { GwtUtils.hideWait(); } }
/** * Invoke an HTTP POST request on a remote host. * * @param path The request path * @param parameters The parameters (collection of Parameter objects) * @return The Response object */ @Override public com.flickr4java.flickr.Response post( String path, Map<String, Object> parameters, String sharedSecret, boolean multipart) { OAuthRequest request = new OAuthRequest(Verb.POST, API_HOST + path); if (multipart) { buildMultipartRequest(parameters, request); } else { buildNormalPostRequest(parameters, request); } RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null) { Token requestToken = new Token(auth.getToken(), auth.getTokenSecret()); OAuthService service = createOAuthService(parameters, sharedSecret); service.signRequest(requestToken, request); } if (multipart) { // Ensure all parameters (including oauth) are added to payload so signature matches parameters.putAll(request.getOauthParameters()); request.addPayload(buildMultipartBody(parameters, getMultipartBoundary())); } if (proxyAuth) { request.addHeader("Proxy-Authorization", "Basic " + getProxyCredentials()); } if (Flickr.debugRequest) { logger.debug("POST: " + request.getCompleteUrl()); } org.scribe.model.Response scribeResponse = request.send(); try { com.flickr4java.flickr.Response response = null; synchronized (mutex) { String strXml = scribeResponse.getBody(); if (Flickr.debugStream) { logger.debug(strXml); } if (strXml.startsWith("oauth_problem=")) { throw new FlickrRuntimeException(strXml); } Document document = builder.parse(new InputSource(new StringReader(strXml))); response = (com.flickr4java.flickr.Response) responseClass.newInstance(); response.parse(document); } return response; } catch (IllegalAccessException e) { throw new FlickrRuntimeException(e); } catch (InstantiationException e) { throw new FlickrRuntimeException(e); } catch (SAXException e) { throw new FlickrRuntimeException(e); } catch (IOException e) { throw new FlickrRuntimeException(e); } }
/** * Determines whether the default processing for this event will be executed. By default, the Mule * server will route events according to a components configuration. The user can override this * behaviour by obtaining a reference to the Event context, either by implementing <code> * org.mule.umo.lifecycle.Callable</code> or calling <code>UMOManager.getEventContext</code> to * obtain the UMOEventContext for the current thread. The user can programmatically control how * events are dispached. * * @param stopFurtherProcessing the value to set. */ public void setStopFurtherProcessing(boolean stopFurtherProcessing) { RequestContext.getEvent().setStopFurtherProcessing(stopFurtherProcessing); }