Java Code Examples for javax.servlet.http.HttpServletRequest

The following are top voted examples for showing how to use javax.servlet.http.HttpServletRequest. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: p4   File: UploadRightsServlet.java View source code 13 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	Part part = request.getPart("owlFile");
	BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream()));
	String line;
	StringBuffer sb = new StringBuffer();
	while ((line = reader.readLine()) != null) {
		sb.append(line);
	}

	logger.debug("Uploaded rights: " + sb.toString());

	request.setAttribute("owl", sb.toString());

	Tools.servletInclude(this, request, response, "body/ingest/rights/set.jsp");
}
 
Example 2
Project: spring-social-live   File: UserCookieGenerator.java View source code 10 votes vote down vote up
public String readCookieValue(HttpServletRequest request) {
	Cookie[] cookies = request.getCookies();
	if (cookies == null) {
		return null;
	}
	for (Cookie cookie : cookies) {
		if (cookie.getName().equals(userCookieGenerator.getCookieName())) {
			return cookie.getValue();
		}
	}
	return null;
}
 
Example 3
Project: jentrata-msh   File: OutboundMessageProcessor.java View source code 9 votes vote down vote up
/**
 * Handle message came from EbmsOutboundListener
 * 
 * @param request
 * @return true if valid message, otherwise false
 * @throws DAOException
 * @throws MessageServiceHandlerException
 * @throws SOAPException
 */
private boolean handleSOAPRequest(SOAPRequest soapRequest, EbxmlMessage ebxmlMsg) 
		throws DAOException,	MessageServiceHandlerException, SOAPException {
	if (!(soapRequest.getSource() instanceof HttpServletRequest)) {
		return false;
	}
	
	HttpServletRequest httpServletRequest = (HttpServletRequest) soapRequest.getSource();
	if (httpServletRequest.getUserPrincipal() == null) {
		return false;
	}
		
	String contentType = httpServletRequest.getHeader("content-type");
	MessageClassifier messageClassifier = new MessageClassifier(ebxmlMsg);
	if (messageClassifier.isMessageOrder()) {
		storeOutgoingOrderedMessage(ebxmlMsg, contentType);
	} else {
		storeOutgoingMessage(ebxmlMsg, contentType);
	}
	
	return true;
}
 
Example 4
Project: jentrata-msh   File: EbmsPropertiesPageletAdaptor.java View source code 8 votes vote down vote up
protected Source getCenterSource(HttpServletRequest request) {

        PropertySheet props;
        PropertyTree resultDom = new PropertyTree();

        try {
            URL systemPropertiesUrl = EbmsProcessor.getModuleGroup()
                    .getSystemModule().getDescriptor();
            systemProperties = new PropertyTree(systemPropertiesUrl);
            URL outboxPropertiesUrl = EbmsProcessor.getModuleGroup().getModule(
                    EbmsProcessor.ACTIVE_MODULE_OUTBOX_COLLECTOR)
                    .getDescriptor();
            outboxProperties = new PropertyTree(outboxPropertiesUrl);
            URL inboxPropertiesUrl = EbmsProcessor.getModuleGroup().getModule(
                    EbmsProcessor.ACTIVE_MODULE_INBOX_COLLECTOR)
                    .getDescriptor();
            inboxProperties = new PropertyTree(inboxPropertiesUrl);
            URL mailPropertiesUrl = EbmsProcessor.getModuleGroup().getModule(
                    EbmsProcessor.ACTIVE_MODULE_MAIL_COLLECTOR).getDescriptor();
            mailProperties = new PropertyTree(mailPropertiesUrl);
            props = getEbmsProperties();

            updateEbmsProperties(request, props);
            resultDom = getProperties(props);
        } catch (Exception e) {
            request.setAttribute(ATTR_MESSAGE,
                    "Unable to process the request: " + e.getMessage());
            throw new RuntimeException(
                    "Error in processing ebms properties pagelet", e);
        }
        return resultDom.getSource();
    }
 
Example 5
Project: jena   File: DumpServlet.java View source code 8 votes vote down vote up
static void printBody(PrintWriter pw, HttpServletRequest req) throws IOException
{
    BufferedReader in = req.getReader() ;
    if ( req.getContentLength() > 0 )
        // Need +2 because last line may not have a CR/LF on it.
        in.mark(req.getContentLength()+2) ;
    else
        // This is a dump - try to do something that works, even if inefficient.
        in.mark(100*1024) ;

    while(true)
    {
        String x = in.readLine() ;
        if ( x == null )
            break ;
        x = x.replaceAll("&", "&") ;
        x = x.replaceAll("<", "&lt;") ;
        x = x.replaceAll(">", "&gt;") ;
        pw.println(x) ;
    }
    try { in.reset() ;} catch (IOException e) { System.out.println("DumpServlet: Reset of content failed: "+e) ; }
}
 
Example 6
Project: browserid-verifier   File: In.java View source code 7 votes vote down vote up
@Override
protected void doPost(final HttpServletRequest req,
		final HttpServletResponse resp) throws ServletException,
		IOException {

	URL url = null;
	try {
		url = new URL(req.getRequestURL().toString());
	} catch (final MalformedURLException ignored) {
	}
	StringBuilder urlBuilder = new StringBuilder()
			.append(url.getProtocol()).append("://").append(url.getHost())
			.append(':').append(url.getPort());
	final String audience = urlBuilder.toString();
	final String assertion = req.getParameter("assertion");
	final Verifier verifier = new Verifier();
	final long verificationTimeOut = 10;
	final BrowserIDResponse personaResponse = verifier.verify(assertion,
			audience, verificationTimeOut, TimeUnit.SECONDS);
	final Status status = personaResponse.getStatus();

	if (status == Status.OK) {
		/* Authentication with Persona was successful */
		final String email = personaResponse.getEmail();
		log.info("Signing in '{}'", email);
		HttpSession session;
		if ((session = req.getSession(false)) != null) {
			// Prevent session hijacking
			session.invalidate();
		}
		session = req.getSession(true);
		session.setAttribute("email", email);

	} else {
		/* Authentication with Persona failed */
		log.info("Sign in failed: {}", personaResponse.getReason());
	}

}
 
Example 7
Project: jentrata-msh   File: AdminPageletAdaptor.java View source code 7 votes vote down vote up
/**
 * Gets the transformation source of the specified menu type.
 * 
 * @param request the servlet request.
 * @param type the menu type.
 * @return the transformation source of the specified menu type.
 */
private Source getMenuComponentSource(HttpServletRequest request, String type) {
    Source componentSource = (Source)request.getAttribute(ATTR_PREFIX + type);
    if (componentSource == null) { 
        Collection tabs = generateMenuComponentSource(request, modules, getModuleId(request), -1, MENU_TYPE_MODULE);
        generateMenuComponentSource(request, tabs, getTabId(request), 12, MENU_TYPE_TAB);
        componentSource = (Source)request.getAttribute(ATTR_PREFIX + type);
    }
    return componentSource;
}
 
Example 8
Project: jbosgi   File: ResourceServlet.java View source code 7 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    String path = req.getPathInfo();
    URL resurl = context.getResource(name + path);
    if (resurl == null) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND, req.getRequestURI());
    }

    // [TODO] MimeType, Content-Length, etc.

    ServletOutputStream out = res.getOutputStream();
    InputStream in = resurl.openStream();
    IOUtils.copyStream(out, in);
}
 
Example 9
Project: jena   File: DataValidator.java View source code 7 votes vote down vote up
@SuppressWarnings("deprecation")
private Tokenizer createTokenizer(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws Exception
{
    Reader reader = null ;  
    String[] args = httpRequest.getParameterValues(paramData) ;
    if ( args == null || args.length == 0 )
    {
        // Not a form?
        reader = httpRequest.getReader() ;
    }
    else if ( args.length > 1 )
    {
        httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Too many parameters for '"+paramData+"='") ;
        return null ;
    }
    else
    {
        reader = new StringReader(args[0]) ;
    }
    
    if ( reader == null )
    {
        httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Can't find data to validate") ;
        return null ;
    }
    
    return TokenizerFactory.makeTokenizer(reader) ;
}
 
Example 10
Project: jentrata-msh   File: AS2RequestAdaptor.java View source code 7 votes vote down vote up
/**
 * processRequest
 * @param request
 * @param response
 * @return String
 * @throws RequestListenerException
 * @see hk.hku.cecid.piazza.commons.servlet.http.HttpRequestListener#processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
public String processRequest(HttpServletRequest request,
        HttpServletResponse response) throws RequestListenerException {
    try {
        Headers headers = new Headers(request, response);
        
        InternetHeaders requestHeaders = headers.getInternetHeaders();
        InputStream requestStream = request.getInputStream();
        AS2Message requestMessage = new AS2Message(requestHeaders, requestStream);
        
        if (requestMessage.getFromPartyID() == null || requestMessage.getToPartyID() == null) {
            response.sendError(HttpURLConnection.HTTP_BAD_REQUEST, "Invalid AS2 Message");
            return null;
        }
        
        AS2Request as2request = new AS2Request(request);
        as2request.setMessage(requestMessage);
        AS2Response as2response = new AS2Response(response);
        
        processRequest(as2request, as2response);
        
        AS2Message responseMessage = as2response.getMessage();
        if (responseMessage == null) {
            return null;
        }
        
        InternetHeaders responseHeaders = responseMessage.getHeaders();
        headers.putInternetHeaders(responseHeaders);
        
        InputStream contentStream= responseMessage.getContentStream();
        OutputStream responseStream= response.getOutputStream();
        IOHandler.pipe(contentStream, responseStream);
        
        return null;
    }
    catch (Exception e) {
        throw new RequestListenerException("Error in processing AS2 request", e);
    }
}
 
Example 11
Project: richfaces   File: ImageManager.java View source code 7 votes vote down vote up
private String createServerURL(HttpServletRequest request) {
    StringBuffer url = new StringBuffer();

    if (request != null) {
        String name = request.getServerName();
        String protocol = (request.getProtocol().split(Constants.SLASH))[0].toLowerCase();

        int port = request.getServerPort();

        url.append(protocol);
        url.append("://");
        url.append(name);
        url.append(":");
        url.append(Integer.toString(port));
    }

    return url.toString();
}
 
Example 12
Project: richfaces   File: FileUploadRendererBase.java View source code 7 votes vote down vote up
@Override
protected void doDecode(FacesContext context, UIComponent component) {
    final AbstractFileUpload fileUpload = (AbstractFileUpload) component;
    final ExternalContext externalContext = context.getExternalContext();

    Object request = externalContext.getRequest();

    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if (httpRequest.getContentType() != null && httpRequest.getContentType().startsWith("multipart/")) {
            String uid = MultipartRequestParser.getParameterValueFromQueryString(httpRequest.getQueryString());

            if (uid != null) {
                long contentLength = Long.parseLong(httpRequest.getHeader("Content-Length"));

                long maxRequestSize = fileUpload.getMaxFileSize() != 0 ? fileUpload.getMaxFileSize()
                    : getMaxRequestSize(httpRequest.getServletContext());

                if (maxRequestSize != 0 && contentLength > maxRequestSize) {
                    externalContext.setResponseStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
                    return;
                }

                Iterable<UploadedFile> uploadedFiles = initializeUploadedFiles(externalContext, httpRequest, uid);

                for (UploadedFile file : uploadedFiles) {
                    if (fileUpload.acceptsFile(file)) {
                        fileUpload.queueEvent(new FileUploadEvent(fileUpload, file));
                    }
                }
            }
        }
    }
}
 
Example 13
Project: resin   File: IfAuthType.java View source code 7 votes vote down vote up
/**
 * True if the predicate matches.
 *
 * @param request the servlet request to test
 */
@Override
public boolean isMatch(HttpServletRequest request)
{
  String authType = request.getAuthType();

  if (authType == null)
    authType = "none";

  if (_authType != null)
    return _authType.equalsIgnoreCase(authType);
  else
    return "none".equalsIgnoreCase(authType);
}
 
Example 14
Project: Java-Device-Detection   File: Gallery.java View source code 7 votes vote down vote up
/**
 * Processes requests for both HTTP
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();

    // Start writing HTML code
    out.println("<html>");
    out.println("<head>");
    out.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">");
    out.println("<script src=\"51D/core.js\" type=\"text/javascript\"></script>");
    out.println("<title>51Degrees Example Servlet</title>");
    out.println("<style type=\"text/css\">");
    out.println("body {font-size: 12pt; font-family: Arial;}");
    out.println(".heading {font-weight: bold;}");
    out.println(".list {list-style: none; padding: 0; margin: 0 0 0 1em;}");
    out.println(".list a {color: #777777}");
    out.println(".item {margin: 1em 0; color: #777777; text-decoration: none;}");
    out.println(".property {display: inline-block;}");
    out.println(".value {font-weight: bold; color: #333333}");
    out.println(".title {text-decoration: underline}");
    out.println(".image .value {text-align: center;}");
    out.println(".image {display: inline-block; margin: 1em;}");
    out.println("</style>");

    out.println("</head>");
    out.println("<body>");

    // Display the name and published date of the dataset being used.
    String dataInfo = String.format(
            "<h4 class=\"heading\">'%s' data published on '%tc' containing '%d' properties in use</h4>",
            super.getProvider(request).dataSet.getName(),
            super.getProvider(request).dataSet.published,
            super.getProvider(request).dataSet.getProperties().size());

    String mainImage = null;
    if (request.getQueryString() != null) {
        List<String> params = new ArrayList<String>();
        StringTokenizer ps = new StringTokenizer(request.getQueryString(), "&", false);
        while (ps.hasMoreTokens()) {
            params.add(ps.nextToken());
        }
        Map<String, String> map = new HashMap<String, String>();
        for (String param : params) {
            StringTokenizer st = new StringTokenizer(param, "=", false);
            map.put(st.nextToken(), st.nextToken());
        }
        mainImage = map.get("image");
    }

    if (mainImage != null) {
        out.printf("<div><img src=\"51D%s?w=600\"/><p>%s</P></div>", mainImage, mainImage);
    } else {
        ServletContext context = request.getServletContext();
        if (context != null) {
            Set<String> images = context.getResourcePaths("/images");
            for (String image : images) {
                if (image.endsWith(".jpg")) {
                    out.printf(
                            "<div style=\"width: 200px;\"><a href=\"?image=%s\"><img src=\"51D/Empty.gif\" data-src=\"51D%s?w=auto\"/></a><p>%s</P></div>",
                            image, image, image);
                }
            }
        }
    }

    // Display the name and published date of the dataset being used.
    out.println(dataInfo);
    
    // Add the call to the automatic image optimiser.
    out.println("<script type=\"text/javascript\">FODIO('w', 'h');</script>");

    out.println("</body>");
    
    // For each of the components display the available properties.
    out.close();
}
 
Example 15
Project: jena   File: ActionLib.java View source code 6 votes vote down vote up
public static String actionURI(HttpServletRequest request) {
//      Log.info(this, "URI                     = '"+request.getRequestURI()) ;
//      Log.info(this, "Context path            = '"+request.getContextPath()+"'") ;
//      Log.info(this, "Servlet path            = '"+request.getServletPath()+"'") ;
//      ServletContext cxt = this.getServletContext() ;
//      Log.info(this, "ServletContext path     = '"+cxt.getContextPath()+"'") ;
        
        String contextPath = request.getServletContext().getContextPath() ;
        String uri = request.getRequestURI() ;
        if ( contextPath == null )
            return uri ;
        if ( contextPath.isEmpty())
            return uri ;
        String x = uri ;
        if ( uri.startsWith(contextPath) )
            x = uri.substring(contextPath.length()) ;
        //log.info("uriWithoutContextPath: uri = "+uri+" contextPath="+contextPath+ "--> x="+x) ;
        return x ;
    }
 
Example 16
Project: webstart   File: DownloadRequest.java View source code 6 votes vote down vote up
public DownloadRequest( ServletContext context, HttpServletRequest request )
{
    _context = context;
    _httpRequest = request;
    _path = request.getRequestURI();
    _encoding = request.getHeader( ACCEPT_ENCODING );
    String context_path = request.getContextPath();
    if ( context_path != null )
    {
        _path = _path.substring( context_path.length() );
    }
    if ( _path == null )
    {
        _path = request.getServletPath(); // This works for *.<ext> invocations
    }
    if ( _path == null )
    {
        _path = "/"; // No path given
    }
    _path = _path.trim();
    if ( _context != null && !_path.endsWith( "/" ) )
    {
        String realPath = _context.getRealPath( _path );
        // fix for 4474021 - getRealPath might returns NULL
        if ( realPath != null )
        {
            File f = new File( realPath );
            if ( f.exists() && f.isDirectory() )
            {
                _path += "/";
            }
        }
    }
    // Append default file for a directory
    if ( _path.endsWith( "/" ) )
    {
        _path += "launch.jnlp";
    }
    _version = getParameter( request, ARG_VERSION_ID );
    _currentVersionId = getParameter( request, ARG_CURRENT_VERSION_ID );
    _os = getParameterList( request, ARG_OS );
    _arch = getParameterList( request, ARG_ARCH );
    _locale = getParameterList( request, ARG_LOCALE );
    _knownPlatforms = getParameterList( request, ARG_KNOWN_PLATFORMS );
    String platformVersion = getParameter( request, ARG_PLATFORM_VERSION_ID );
    _isPlatformRequest = ( platformVersion != null );
    if ( _isPlatformRequest )
    {
        _version = platformVersion;
    }
    _query = request.getQueryString();
    _testJRE = getParameter( request, TEST_JRE );
}
 
Example 17
Project: richfaces   File: PushFilter.java View source code 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
    ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpResp = (HttpServletResponse) response;

        if ("GET".equals(httpReq.getMethod()) && httpReq.getQueryString() != null
            && httpReq.getQueryString().contains("__richfacesPushAsync")) {
            if (pushServlet == null) {
                pushServlet = new PushServlet();
                pushServlet.init(servletConfig);
            }
            pushServlet.doGet(httpReq, httpResp);
            return;
        }
    }

    chain.doFilter(request, response);
}
 
Example 18
Project: jentrata-msh   File: PropertiesPageletAdaptor.java View source code 6 votes vote down vote up
protected PropertyTree getPropertiesForDisplayAndUpdate(HttpServletRequest request,
		PropertyTree dom) {

	PropertySheet props = getProperties();

	String action = request.getParameter(REQ_PARAM_ACTION);
	if (request.getMethod().equalsIgnoreCase("post")) {
		if ("update".equalsIgnoreCase(action)) {
			Enumeration names = request.getParameterNames();
			while (names.hasMoreElements()) {
				String name = names.nextElement().toString();
				if (name.startsWith(REQ_PARAM_PROPERTY)) {
					props.setProperty(name.substring(REQ_PARAM_PROPERTY
							.length()), request.getParameter(name));
				}
			}
			try {
				if (props instanceof PersistentComponent) {
					if (((PersistentComponent) props).getURL() != null) {
						props.store();
					}
				}
				request.setAttribute(ATTR_MESSAGE,
						"Properties updated successfully");
			} catch (Exception e) {
				request.setAttribute(ATTR_MESSAGE,
						"Unable to update properties: " + e);
			}
		}
	}

	String[] keys = (String[]) ArrayUtilities.toArray(
			props.propertyNames(), new String[] {});
	Arrays.sort(keys);

	for (int i = 0, pi = 0; i < keys.length; i++) {
		String value = props.getProperty(keys[i], "");
		if (value.indexOf('\n') == -1 && value.indexOf('\r') == -1) {
			pi++;
			dom.setProperty("property[" + pi + "]/name", keys[i]);
			dom.setProperty("property[" + pi + "]/value", props
					.getProperty(keys[i]));
		}
	}

	return dom;

}
 
Example 19
Project: richfaces   File: ResourceServlet.java View source code 6 votes vote down vote up
private static String decodeResourceURL(HttpServletRequest request) {
    String resourceName = null;
    String facesMapping = getMappingForRequest(request);

    if (facesMapping != null) {
        if (facesMapping.startsWith("/")) {

            // prefix mapping
            resourceName = request.getPathInfo();

        } else {
            String requestServletPath = request.getServletPath();

            resourceName = requestServletPath.substring(0, requestServletPath.length() - facesMapping.length());
        }
    }

    return resourceName;
}
 
Example 20
Project: ilarkesto   File: OpenId.java View source code 6 votes vote down vote up
public static String getIdentifierFromCallback(HttpServletRequest request) {
	log.info("Reading OpenID response");
	ParameterList openidResp = new ParameterList(request.getParameterMap());
	for (Iterator iterator = openidResp.getParameters().iterator(); iterator.hasNext();) {
		Parameter param = (Parameter) iterator.next();
		log.info("   ", param.getKey(), "->", param.getValue());
	}
	HttpSession session = request.getSession();
	DiscoveryInformation discovered = (DiscoveryInformation) session.getAttribute("openIdDiscovered");

	// extract the receiving URL from the HTTP request
	StringBuffer receivingURL = request.getRequestURL();
	String queryString = request.getQueryString();
	if (queryString != null && queryString.length() > 0) receivingURL.append("?").append(request.getQueryString());

	// verify the response
	VerificationResult verification;
	try {
		verification = getConsumerManager(session).verify(receivingURL.toString(), openidResp, discovered);
	} catch (Exception ex) {
		throw new RuntimeException("Reading OpenID response data failed.", ex);
	}

	Identifier verifiedId = verification.getVerifiedId();
	return verifiedId == null ? null : verifiedId.getIdentifier();
}
 
Example 21
Project: jena   File: SPARQL_ServletBase.java View source code 6 votes vote down vote up
/**
 * Initiates the response, by setting common headers such as Access-Control-Allow-Origin and Server, and
 * the Vary header if the request method used was a GET.
 * @param request HTTP request
 * @param response HTTP response
 */
private void initResponse(HttpServletRequest request, HttpServletResponse response)
{
    setCommonHeaders(response) ;
    String method = request.getMethod() ;
    // All GET and HEAD operations are sensitive to conneg so ...
    if ( HttpNames.METHOD_GET.equalsIgnoreCase(method) || HttpNames.METHOD_HEAD.equalsIgnoreCase(method) )
        setVaryHeader(response) ;
}
 
Example 22
Project: ilarkesto   File: Servlet.java View source code 6 votes vote down vote up
public static Map<String, String> getHeaders(HttpServletRequest r) {
	Map<String, String> result = new HashMap<String, String>();
	Enumeration names = r.getHeaderNames();
	while (names.hasMoreElements()) {
		String name = (String) names.nextElement();
		String value = r.getHeader(name);
		result.put(name, value);
	}
	return result;
}
 
Example 23
Project: iot-server-appliances   File: LoginServlet.java View source code 6 votes vote down vote up
protected void doPost(HttpServletRequest request,
					  HttpServletResponse response)
		throws ServletException, IOException {
	String username=request.getParameter("username");
	String password=request.getParameter("password");

	//UserAgent + ClientIP + '
	String userAgent=request.getHeader("User-Agent");
	if(userAgent==null){
		userAgent=username;

	}
	String ipAddress = request.getHeader("X-FORWARDED-FOR");
	if (ipAddress == null) {
		ipAddress = request.getRemoteAddr();
	}
	String salt=UUID.randomUUID().toString();
	String instanceId=userAgent+ipAddress+salt;
	AccessTokenClient client = new AccessTokenClient();
	AccessTokenInfo accessTokenInfo;
	try {
		accessTokenInfo=client.getAccessToken(username,password,instanceId);
		if(accessTokenInfo!=null) {
			request.getSession(true).setAttribute("token", accessTokenInfo.getAccess_token());
			request.getSession(true).setAttribute("username", username);
			request.getSession(true).removeAttribute("password");

			request.getRequestDispatcher("control.jsp").forward(request, response);
		}else{
			request.setAttribute("errMsg","Invalid Credential");
			request.getRequestDispatcher("index.jsp").forward(request, response);
		}
	} catch (AccessTokenException e) {
		request.setAttribute("errMsg","Invalid Credential");
		request.getRequestDispatcher("index.jsp").forward(request, response);
	}



}
 
Example 24
Project: OpenClinica   File: SetUpUserInterceptor.java View source code 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

    Locale locale = ResourceBundleProvider.localeMap.get(Thread.currentThread());
    if (locale == null) {
        ResourceBundleProvider.updateLocale(httpServletRequest.getLocale());
    }

    //Set up the user account bean: check the Session first
    HttpSession currentSession = httpServletRequest.getSession();
    UserAccountBean userBean = (UserAccountBean) currentSession.getAttribute("userBean");
    String userName = "";
    boolean userBeanIsInvalid;
    UserAccountDAO userAccountDAO = new UserAccountDAO(dataSource);

    if (userBean == null) {

        userName = httpServletRequest.getRemoteUser();
        userBeanIsInvalid = "".equalsIgnoreCase(userName);
        if (!userBeanIsInvalid) {
            userBean = (UserAccountBean) userAccountDAO.findByUserName(userName);
            userBeanIsInvalid = (userBean == null);
            if (!userBeanIsInvalid) {
                currentSession.setAttribute(USER_BEAN_NAME, userBean);
            }

        }
    }

    //The user bean could still be null at this point
    if (userBean == null) {
        userBean = new UserAccountBean();
        userBean.setName("unknown");
        currentSession.setAttribute(USER_BEAN_NAME, userBean);
    }

    userBean = userBean.getId() > 0 ? (UserAccountBean) userAccountDAO.findByPK(userBean.getId()) : userBean;

    SetUpStudyRole setupStudy = new SetUpStudyRole(dataSource);
    setupStudy.setUp(currentSession, userBean);

    return true;
}
 
Example 25
Project: dataverse   File: ApiRouter.java View source code 6 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse sr1, FilterChain fc) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    String requestUri = request.getRequestURI();
    if ( requestUri.startsWith("/api/v1/") ) {
        fc.doFilter(req, sr1);
    } else {
        String newRequestUri = "/api/v1" + requestUri.substring(4);
        RequestDispatcher dsp = request.getRequestDispatcher(newRequestUri);
        dsp.forward(req, sr1);
    }
}
 
Example 26
Project: webstart   File: JnlpFileHandler.java View source code 6 votes vote down vote up
private String getUrlPrefix( HttpServletRequest req )
{
    StringBuilder url = new StringBuilder();
    String scheme = req.getScheme();
    int port = req.getServerPort();
    url.append( scheme );        // http, https
    url.append( "://" );
    url.append( req.getServerName() );
    if ( ( scheme.equals( "http" ) && port != 80 ) || ( scheme.equals( "https" ) && port != 443 ) )
    {
        url.append( ':' );
        url.append( req.getServerPort() );
    }
    return url.toString();
}
 
Example 27
Project: jentrata-msh   File: HttpDispatcher.java View source code 6 votes vote down vote up
/**
 * Sets the defaults for this HttpDispatcher. The servlet config will be
 * stored as a request attribute and the encodings of the request and
 * response will be set to what defined in the dispatcher context.
 * 
 * @param request the servlet request.
 * @param response the servlet response.
 */
private void setDefaults(HttpServletRequest request,
        HttpServletResponse response) {
    try {
        request.setAttribute(CONFIG_KEY, servletConfig);

        if (dispatcherContext.getResponseEncoding() != null) {
            String enc = dispatcherContext.getResponseEncoding();
            if (enc.indexOf(';')!=-1) {
                response.setContentType(enc);
            }
            else {
                response.setCharacterEncoding(enc);
            }
        }
        if (dispatcherContext.getRequestEncoding() != null) {
            request.setCharacterEncoding(dispatcherContext.getRequestEncoding());
        }
    }
    catch (Exception e) {
        Sys.main.log.error("Unable to set servlet default encoding", e);
    }
}
 
Example 28
Project: aipo   File: ALEipManager.java View source code 6 votes vote down vote up
public void removeProfile(ProfileLocator locator) {
  HttpServletRequest request = HttpServletRequestLocator.get();
  String key = getUserProfileKey(locator);
  if (request != null && key != null) {
    request.removeAttribute(key);
  }
}
 
Example 29
Project: jena   File: ServletBase.java View source code 6 votes vote down vote up
/**
 * Returns the HTTP request URL, appended with any additional URL parameters used.
 *
 * @param request HTTP request
 * @return complete request URL
 */
protected static String wholeRequestURL(HttpServletRequest request)
{
    StringBuffer sb = request.getRequestURL() ;
    String queryString = request.getQueryString() ;
    if ( queryString != null )
    {
        sb.append("?") ;
        sb.append(queryString) ;
    }
    return sb.toString() ;
}
 
Example 30
Project: jena   File: WebLib.java View source code 6 votes vote down vote up
/** Migrate to WebLib */
public static String getAccept(HttpServletRequest httpRequest)
{
    // There can be multiple accept headers -- note many tools don't allow these to be this way (e.g. wget, curl)
    Enumeration<String> en = httpRequest.getHeaders(HttpNames.hAccept) ;
    if ( ! en.hasMoreElements() )
        return null ;
    StringBuilder sb = new StringBuilder() ;
    String sep = "" ;
    for ( ; en.hasMoreElements() ; )
    {
        String x = en.nextElement() ;
        sb.append(sep) ;
        sep = ", " ;
        sb.append(x) ;
    }
    return sb.toString() ;
}
 
Example 31
Project: richfaces   File: FileUploadRendererBase.java View source code 6 votes vote down vote up
private Iterable<UploadedFile> initializeUploadedFiles(ExternalContext context, HttpServletRequest request, String uploadId) {
    try {
        List<UploadedFile> files = new LinkedList<UploadedFile>();

        // check if Servlet 3.0+ is being used
        if (request.getParts().size() > 0) {
            Collection<Part> parts = request.getParts();

            for (Part part : parts) {
                String contentDisposition = part.getHeader("Content-Disposition");
                String filename = MultipartRequestParser.parseFileName(contentDisposition);
                if (filename != null) {
                    // RF-14092: request encoded in UTF8 (XHR2 default) will be parsed as Latin1 (HTTP default)
                    // on Tomcat it can be any encoding (org.apache.catalina.filters.SetCharacterEncodingFilter)
                    String encoding = request.getCharacterEncoding();
                    if (encoding == null) {
                        encoding = "iso-8859-1";
                    }
                    files
                        .add(new UploadedFile30(part.getName(), new String(filename.getBytes(encoding), "utf-8"), part));
                }
            }
        } else {
            boolean createTempFiles = isCreateTempFiles(request.getServletContext());
            String tempFilesDirectory = getTempFilesDirectory(request.getServletContext());
            MultipartRequestParser requestParser = new MultipartRequestParser(request, createTempFiles, tempFilesDirectory);
            MultipartRequest multipartRequest = new MultipartRequest25(request, uploadId, requestParser);

            files = (List<UploadedFile>) multipartRequest.getUploadedFiles();
        }
        return files;
    } catch (Exception e) {
        context.setResponseStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw new FileUploadException("couldn't parse request parts", e);
    }
}
 
Example 32
Project: visuwall   File: InsertTag.java View source code 6 votes vote down vote up
/**
 * Process nested &lg;put&gt; tag.
 * Method calls by nested &lg;put&gt; tags.
 * Nested list is added to current list.
 * If role is defined, it is checked immediately.
 */
public void processNestedTag(PutTag nestedTag) throws JspException {
    // Check role
    HttpServletRequest request =
        (HttpServletRequest) pageContext.getRequest();
    String role = nestedTag.getRole();
    if (role != null && !request.isUserInRole(role)) {
        // not allowed : skip attribute
        return;
    }

    putAttribute(nestedTag.getName(), nestedTag.getRealValue());
}
 
Example 33
Project: OpenClinica   File: Validator.java View source code 6 votes vote down vote up
public Validator(HttpServletRequest request) {
    validations = new HashMap();
    errors = new HashMap();
    this.request = request;
    if ( request != null){locale = request.getLocale();}
    resformat = ResourceBundleProvider.getFormatBundle(locale);
    restext = ResourceBundleProvider.getTextsBundle(locale);
    resexception = ResourceBundleProvider.getExceptionsBundle(locale);
    resword = ResourceBundleProvider.getWordsBundle(locale);
    lastField = "";
}
 
Example 34
Project: Jorum-DSpace   File: DSpaceCocoonServletFilter.java View source code 6 votes vote down vote up
/**
    * Before passing off a request to the cocoon servlet check to see if there is a request that 
    * should be resumed? If so replace the real request with a faked request and pass that off to 
    * cocoon.
    */
public void doFilter(ServletRequest request, ServletResponse response,
		FilterChain arg2) throws IOException, ServletException { 
   
	HttpServletRequest realRequest = (HttpServletRequest)request;
	HttpServletResponse realResponse = (HttpServletResponse) response;
   	
	// GWaller 22/3/10 IssueID #230 Need to catch exceptions from cocoon calls e.g. doFilter below!
       // If an exception was thrown, the conext was not closed which caused a hung connection. Use finally block to do this.
       try{
	
		// Check if there is a request to be resumed.
        realRequest = AuthenticationUtil.resumeRequest(realRequest);

        // Send the real request or the resumed request off to
        // cocoon....

        // if force ssl is on and the user has authenticated and the request is not secure redirect to https
        if ((ConfigurationManager.getBooleanProperty("xmlui.force.ssl")) && (realRequest.getSession().getAttribute("dspace.current.user.id")!=null) && (!realRequest.isSecure())) {
                StringBuffer location = new StringBuffer("https://");
                location.append(ConfigurationManager.getProperty("dspace.hostname")).append(realRequest.getContextPath()).append(realRequest.getServletPath()).append(
                        realRequest.getQueryString() == null ? ""
                                : ("?" + realRequest.getQueryString()));
                realResponse.sendRedirect(location.toString());
        }

       	arg2.doFilter(realRequest, realResponse);
       	
    
       	
       } catch (Exception e){
       	ContextUtil.abortContext(realRequest);
       	ExceptionLogger.logException(logger, e);
       	
       } finally{
       	// Close out the DSpace context no matter what.
       	ContextUtil.closeContext(realRequest);
       }
   }
 
Example 35
Project: ilarkesto   File: AWebSession.java View source code 6 votes vote down vote up
public AWebSession(Context parentContext, HttpServletRequest initialRequest) {
	this.initialRemoteHost = initialRequest == null ? "localhost" : initialRequest.getRemoteHost();

	context = parentContext.createSubContext(toString());
	context.addBeanProvider(this);

	userAgent = initialRequest == null ? "unknown" : Servlet.getUserAgent(initialRequest);
	shitBrowser = userAgent != null && userAgent.contains("MSIE 6");

	touch();
}
 
Example 36
Project: ilarkesto   File: Servlet.java View source code 6 votes vote down vote up
public static Map<String, Object> getAttributes(HttpServletRequest r) {
	Map<String, Object> result = new HashMap<String, Object>();
	Enumeration names = r.getAttributeNames();
	while (names.hasMoreElements()) {
		String name = (String) names.nextElement();
		Object value = r.getAttribute(name);
		result.put(name, value);
	}
	return result;
}
 
Example 37
Project: sockjs-servlet   File: SockJsServlet.java View source code 6 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    log.log(Level.FINE, "SockJsServlet#service for {0} {1}", new Object[] {req.getMethod(), req.getPathInfo()});
    AsyncContext asyncContext = req.startAsync();
    asyncContext.setTimeout(0); // no timeout
    SockJsServletRequest sockJsReq = new SockJsServletRequest(req);
    SockJsServletResponse sockJsRes = new SockJsServletResponse(res, asyncContext);
    try {
        sockJsServer.dispatch(sockJsReq, sockJsRes);
    } catch (SockJsException ex) {
        throw new ServletException("Error during SockJS request:", ex);
    }
    if ("application/x-www-form-urlencoded".equals(req.getHeader("Content-Type"))) {
        // Let the servlet parse data and just pretend like we did
        sockJsReq.onAllDataRead();
    } else if (req.isAsyncStarted()) {
        req.getInputStream().setReadListener(sockJsReq);
    }
}
 
Example 38
Project: visuwall   File: IncludeTag.java View source code 6 votes vote down vote up
/**
 * Add a session id cookie if appropriate. Can be overloaded to support a
 * cluster.
 *
 * @param conn
 * @param urlString
 * @param request
 * @since Struts 1.2.0
 */
protected void addCookie(URLConnection conn, String urlString,
    HttpServletRequest request) {
    if ((conn instanceof HttpURLConnection)
        && urlString.startsWith(request.getContextPath())
        && (request.getRequestedSessionId() != null)
        && request.isRequestedSessionIdFromCookie()) {
        StringBuffer sb = new StringBuffer("JSESSIONID=");

        sb.append(request.getRequestedSessionId());
        conn.setRequestProperty("Cookie", sb.toString());
    }
}
 
Example 39
Project: appengine-java-vm-runtime   File: OpenFilesServlet.java View source code 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  int numberOfFiles = Integer.valueOf(request.getParameter("num"));

  File file = new File(request.getRealPath("WEB-INF/web.xml"));
  List<InputStream> streams = new ArrayList<InputStream>(numberOfFiles);
  for (int i = 0; i < numberOfFiles; i++) {
    try {
      streams.add(new FileInputStream(file));
    } catch (FileNotFoundException ex) {
      logger.log(Level.WARNING, "Could not open " + file + " after " + streams.size(), ex);
      break;
    }
  }

  if (streams.size() != numberOfFiles) {
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
  } else {
    response.getWriter().println("Opened " + streams.size() + " FD's.");
  }

  for (InputStream is : streams) {
    is.close();
  }
}
 
Example 40
Project: entando-core   File: OAuthConsumerManager.java View source code 6 votes vote down vote up
public void handleException(Exception e, HttpServletRequest request,
        HttpServletResponse response, boolean sendBody)
        throws IOException, ServletException {
    String realm = (request.isSecure()) ? "https://" : "http://";
    realm += request.getLocalName();
    OAuthServlet.handleException(response, e, realm, sendBody);
}
 
Example 41
Project: openmrs_gsoc   File: DWRMessageService.java View source code 6 votes vote down vote up
public boolean sendFeedback(String sender, String subject, String content) {
	
	HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
	
	if (!Context.isAuthenticated()) {
		try {
			MessageService messageService = Context.getMessageService();
			
			String recipients = NotificationConstants.FEEDBACK_EMAIL_ADDRESS;
			if (subject == null || subject.equals(""))
				subject = NotificationConstants.FEEDBACK_EMAIL_SUBJECT;
			
			String referer = request.getPathTranslated();
			String userName = "an Anonymous User";
			if (Context.isAuthenticated())
				userName = Context.getAuthenticatedUser().getPersonName().toString();
			
			content += "\n\n This email sent from: " + referer + " by: " + userName;
			
			messageService.sendMessage(recipients, sender, subject, content);
			
			return true;
			
		}
		catch (Exception e) {
			log.error("Error sending feedback", e);
		}
	}
	
	return false;
}
 
Example 42
Project: OpenClinica   File: LocaleResolver.java View source code 6 votes vote down vote up
/**
 * Find Locale basing on order of accept languages and availability of i18n properties files.
 *
 * @param request
 * @return
 */
public final static Locale resolveLocale(HttpServletRequest request) {
	if(request != null) {
		for(@SuppressWarnings("unchecked")
		Enumeration<Locale> locales = request.getLocales(); locales.hasMoreElements();) {
			Locale locale = locales.nextElement();
			ResourceBundleProvider.updateLocale(locale);
			if(isQualifiedLocale(locale)) {
			    locale = ResourceBundleProvider.getFormatBundle(locale).getLocale();
                   return locale;
			} else if(getDefaultLocale().getLanguage().equalsIgnoreCase(locale.getLanguage())) {
			    break;
			}
		}
       }
	return getDefaultLocale();
}
 
Example 43
Project: Portofino   File: ApplicationInterceptor.java View source code 6 votes vote down vote up
public Resolution intercept(ExecutionContext context) throws Exception {
    logger.debug("Retrieving Stripes objects");
    ActionBeanContext actionContext = context.getActionBeanContext();

    logger.debug("Retrieving Servlet API objects");
    HttpServletRequest request = actionContext.getRequest();

    if (request.getDispatcherType() == DispatcherType.REQUEST) {
        logger.debug("Starting page response timer");
        StopWatch stopWatch = new StopWatch();
        // There is no need to stop this timer.
        stopWatch.start();
        request.setAttribute(RequestAttributes.STOP_WATCH, stopWatch);
    }

    Resolution resolution = dispatch(actionContext);
    return resolution != null ? resolution : context.proceed();
}
 
Example 44
Project: aipo   File: JetspeedPortletStatsService.java View source code 6 votes vote down vote up
/**
 * Formats log message
 * 
 * @param data
 * @param portlet
 * @param statusCode
 * @param time
 * @return Formatted message
 * @exception Exception
 */
protected String getLogMessage(RunData data, Portlet portlet, String statusCode, long time) 
throws Exception
{        
 
    HttpServletRequest req = data.getRequest();
    Object[] args = {
        req.getRemoteAddr(),
        "-",
        data.getUser().getUserName(),
        this.formatter.format(new Date()),
        req.getMethod(),
        req.getContextPath(),
        portlet.getName(),
        req.getProtocol(),
        statusCode,
        this.logLoadTime == true ? String.valueOf(time) : "-"
    }; 

    return MessageFormat.format(defaultLogFormat, args).toString();

}
 
Example 45
Project: keycloak   File: ProtectedServlet.java View source code 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String realm = req.getPathInfo().split("/")[1];
    if (realm.contains("?")) {
        realm = realm.split("\\?")[0];
    }

    if (req.getPathInfo().contains("logout")) {
        req.logout();
        resp.sendRedirect(req.getContextPath() + "/" + realm);
        return;
    }

    KeycloakPrincipal principal = (KeycloakPrincipal) req.getUserPrincipal();

    resp.setContentType("text/html");
    PrintWriter writer = resp.getWriter();

    writer.write("Realm: ");
    writer.write(principal.getKeycloakSecurityContext().getRealm());

    writer.write("<br/>User: ");
    writer.write(principal.getKeycloakSecurityContext().getIdToken().getPreferredUsername());

    writer.write(String.format("<br/><a href=\"/multitenant/%s/logout\">Logout</a>", realm));
}
 
Example 46
Project: gluu-opendj   File: HTTPClientConnection.java View source code 6 votes vote down vote up
/**
 * Constructs an instance of this class.
 *
 * @param connectionHandler
 *          the connection handler that accepted this connection
 * @param request
 *          represents this client connection.
 */
public HTTPClientConnection(HTTPConnectionHandler connectionHandler,
    HttpServletRequest request)
{
  this.connectionHandler = connectionHandler;

  // memoize all the fields we need from the request before Grizzly decides to
  // recycle it
  this.clientAddress = request.getRemoteAddr();
  this.clientPort = request.getRemotePort();
  this.serverAddress = request.getLocalAddr();
  this.serverPort = request.getLocalPort();
  this.remoteAddress = toInetAddress(request.getRemoteAddr());
  this.localAddress = toInetAddress(request.getLocalAddr());
  this.isSecure = request.isSecure();
  this.securityStrengthFactor =
      calcSSF(request.getAttribute(SERVLET_SSF_CONSTANT));
  this.method = request.getMethod();
  this.query = computeQuery(request);
  this.protocol = request.getProtocol();
  this.userAgent = request.getHeader("User-Agent");

  this.statTracker = this.connectionHandler.getStatTracker();

  this.keepStats = connectionHandler.keepStats();
  if (this.keepStats)
  {
    this.statTracker.updateConnect();
    this.useNanoTime = DirectoryServer.getUseNanoTime();
  }

  this.connectionID = DirectoryServer.newConnectionAccepted(this);
}
 
Example 47
Project: NewPOS   File: TerracottaSessionIdManager.java View source code 6 votes vote down vote up
public String newSessionId(HttpServletRequest request, long created)
{
    // Generate a unique cluster id. This id must be unique across all nodes in the cluster,
    // since it is stored in the distributed shared session ids set.

    // A requested session ID can only be used if it is in use already.
    String requested_id = request.getRequestedSessionId();
    if (requested_id != null && idInUse(requested_id))
        return requested_id;

    // Else reuse any new session ID already defined for this request.
    String new_id = (String)request.getAttribute(__NEW_SESSION_ID);
    if (new_id != null && idInUse(new_id))
        return new_id;

    // pick a new unique ID!
    String id = null;
    while (id == null || id.length() == 0 || idInUse(id))
    {
        long r = _weakRandom
                ? (hashCode() ^ Runtime.getRuntime().freeMemory() ^ _random.nextInt() ^ (((long)request.hashCode()) << 32))
                : _random.nextLong();
        r ^= created;
        if (request.getRemoteAddr() != null) r ^= request.getRemoteAddr().hashCode();
        if (r < 0) r = -r;
        id = Long.toString(r, 36);
    }

    request.setAttribute(__NEW_SESSION_ID, id);
    return id;
}
 
Example 48
Project: wildfly-custom-login-module   File: LoginServlet.java View source code 6 votes vote down vote up
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (username != null && password != null) {
            request.login(username, password);
        }

        CustomPrincipal principal = (CustomPrincipal) request.getUserPrincipal();
        response.getWriter().println("principal=" + request.getUserPrincipal().getClass().getSimpleName());
        response.getWriter().println("username=" + sampleEJB.getPrincipalName());
        response.getWriter().println("description=" + principal.getDescription());

    } catch (ServletException e) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}
 
Example 49
Project: molgenis   File: SecurityUtils.java View source code 6 votes vote down vote up
/**
 * Checks if client session is expired (by checking the requested sessionId).
 * 
 * 
 * @param request
 * @return true if session is expired
 */
public static boolean isSessionExpired(HttpServletRequest request)
{
	return request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid();

}
 
Example 50
Project: resin   File: IfAuthType.java View source code 6 votes vote down vote up
/**
 * Sets the auth-type value to match against.
 */
@Configurable
public void setValue(String authType)
{
  if ("NONE".equalsIgnoreCase(authType))
    _authType = null;
  else if (HttpServletRequest.BASIC_AUTH.equalsIgnoreCase(authType))
    _authType = HttpServletRequest.BASIC_AUTH;
  else if (HttpServletRequest.CLIENT_CERT_AUTH.equalsIgnoreCase(authType))
    _authType = HttpServletRequest.CLIENT_CERT_AUTH;
  else if (HttpServletRequest.DIGEST_AUTH.equalsIgnoreCase(authType))
    _authType = HttpServletRequest.DIGEST_AUTH;
  else if (HttpServletRequest.FORM_AUTH.equalsIgnoreCase(authType))
    _authType = HttpServletRequest.FORM_AUTH;
  else
    throw new ConfigException(L.l("auth-type expects a 'value' of BASIC, CLIENT-CERT, DIGEST, FORM, or NONE"));
}
 
Example 51
Project: wildfly-custom-login-module   File: AuthenticateServlet.java View source code 6 votes vote down vote up
private void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/html;charset=UTF-8");

    try (PrintWriter out = response.getWriter()) {
        request.authenticate(response);
        out.println("Authenticate Successful");
    }
}
 
Example 52
Project: easyrec-on-github   File: AsyncStockServlet.java View source code 6 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    if (req.isAsyncStarted()) {
        req.getAsyncContext().complete();
    } else if (req.isAsyncSupported()) {
        AsyncContext actx = req.startAsync();
        actx.addListener(this);
        resp.setContentType("text/plain");
        clients.add(actx);
        if (clientcount.incrementAndGet()==1) {
            ticker.addTickListener(this);
        }
    } else {
        new Exception("Async Not Supported").printStackTrace();
        resp.sendError(400,"Async is not supported.");
    }
}
 
Example 53
Project: J2EP   File: MaxForwardRequestHandler.java View source code 6 votes vote down vote up
/**
 * Sets the headers and does some checking for if this request
 * is meant for the server or for the proxy. This check is done
 * by looking at the Max-Forwards header.
 * 
 * @see net.sf.j2ep.model.RequestHandler#process(javax.servlet.http.HttpServletRequest, java.lang.String)
 */
public HttpMethod process(HttpServletRequest request, String url) throws IOException {
    HttpMethodBase method;
    
    if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
        method = new OptionsMethod(url);
    } else if (request.getMethod().equalsIgnoreCase("TRACE")) {
        method = new TraceMethod(url);
    } else {
        return null;
    }
    
    try {
        int max = request.getIntHeader("Max-Forwards");
        if (max == 0 || request.getRequestURI().equals("*")) {
            setAllHeaders(method, request);
            method.abort();
        } else if (max != -1) {
            setHeaders(method, request);
            method.setRequestHeader("Max-Forwards", "" + max);
        } else {
            setHeaders(method, request);
        }
    } catch (NumberFormatException ignored) {}
    
    return method;
}
 
Example 54
Project: Magnolia   File: SecurityCallbackFilter.java View source code 6 votes vote down vote up
protected HttpClientCallback selectClientCallback(HttpServletRequest request) {
    for (HttpClientCallback clientCallback : clientCallbacks) {
        if (clientCallback.accepts(request)) {
            return clientCallback;
        }
    }
    throw new IllegalStateException("No configured callback accepted this request " + request.toString());
}
 
Example 55
Project: webstart   File: JnlpDownloadServlet.java View source code 5 votes vote down vote up
private void handleRequest( HttpServletRequest request, HttpServletResponse response, boolean isHead )
    throws IOException
{
    String requestStr = request.getRequestURI();
    if ( request.getQueryString() != null )
    {
        requestStr += "?" + request.getQueryString().trim();
    }

    // Parse HTTP request
    DownloadRequest dreq = new DownloadRequest( getServletContext(), request );
    if ( _log.isInformationalLevel() )
    {
        _log.addInformational( "servlet.log.info.request", requestStr );
        _log.addInformational( "servlet.log.info.useragent", request.getHeader( "User-Agent" ) );
    }
    if ( _log.isDebugLevel() )
    {
        _log.addDebug( dreq.toString() );
    }

    long ifModifiedSince = request.getDateHeader( "If-Modified-Since" );

    // Check if it is a valid request
    try
    {
        // Check if the request is valid
        validateRequest( dreq );

        // Decide what resource to return
        JnlpResource jnlpres = locateResource( dreq );
        _log.addDebug( "JnlpResource: " + jnlpres );

        if ( _log.isInformationalLevel() )
        {
            _log.addInformational( "servlet.log.info.goodrequest", jnlpres.getPath() );
        }

        DownloadResponse dres;

        if ( isHead )
        {

            int cl = jnlpres.getResource().openConnection().getContentLength();

            // head request response
            dres = DownloadResponse.getHeadRequestResponse( jnlpres.getMimeType(), jnlpres.getVersionId(),
                                                            jnlpres.getLastModified(), cl );

        }
        else if ( ifModifiedSince != -1 && ( ifModifiedSince / 1000 ) >= ( jnlpres.getLastModified() / 1000 ) )
        {
            // We divide the value returned by getLastModified here by 1000
            // because if protocol is HTTP, last 3 digits will always be 
            // zero.  However, if protocol is JNDI, that's not the case.
            // so we divide the value by 1000 to remove the last 3 digits
            // before comparison

            // return 304 not modified if possible
            _log.addDebug( "return 304 Not modified" );
            dres = DownloadResponse.getNotModifiedResponse();

        }
        else
        {

            // Return selected resource
            dres = constructResponse( jnlpres, dreq );
        }

        dres.sendRespond( response );

    }
    catch ( ErrorResponseException ere )
    {
        if ( _log.isInformationalLevel() )
        {
            _log.addInformational( "servlet.log.info.badrequest", requestStr );
        }
        if ( _log.isDebugLevel() )
        {
            _log.addDebug( "Response: " + ere.toString() );
        }
        // Return response from exception
        ere.getDownloadResponse().sendRespond( response );
    }
    catch ( Throwable e )
    {
        _log.addFatal( "servlet.log.fatal.internalerror", e );
        response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
    }
}
 
Example 56
Project: Hphoto   File: ApiServlet.java View source code 5 votes vote down vote up
public void addCategory(Document doc,Element channel,HttpServletRequest request){
 assert(request.getParameter("user") != null);
 
 String requestUrl = request.getRequestURL().toString();
 String base = "http://" +request.getServerName() + (request.getLocalPort() == 80 ? "" : ":"+Integer.toString(request.getLocalPort())); 
 Category[] categories = null;
 UserProfile[] users = null;
 String owner = request.getParameter("user") ;
 String feed = request.getParameter("feed");
 String language = request.getParameter("hl");
 String kind = request.getParameter("kind");
 String albumid = request.getParameter("albumid");
 //Local local = language == null ? request.getLocale() : new Locale(language);
 boolean all = request.getParameter("acess") != null && request.getParameter("acess").equals("all");
 boolean api = feed != null && feed.equals("api");
 
 
 try {
  users = server.getUser(owner,1);
  categories = server.getCategories(owner);
 } catch (IOException e) {		 
  e.printStackTrace();
  return;
 }
 
 if(users ==null ||  users.length == 0){
  return;
 }
 
 addNode(doc, channel, "atom","id",base+"/feed/"+feed+"/user/"+owner);
 addNode(doc, channel, "lastBuildDate",(new Date()).toString());
 addNode(doc, channel, "title", owner +" "+ I18nUtil.getText(key,"title",request.getLocale()));
    addNode(doc, channel, "description", "");
    //add base,not complete
    addNode(doc, channel, "link", base + "/" + owner);
    addNode(doc, channel, "managingEditor" , owner);
    addNode(doc, channel, "generator", "hphoto.com");
    addNode(doc, channel, "opensearch", "totalResults", ""+(categories != null?categories.length:0));
    //addNode(doc, channel, "opensearch", "startIndex", ""+1);
    //addNode(doc, channel, "opensearch", "itemsPerPage", ""+1000);
    Element image = addNode(doc, channel, "image");
    addNode(doc, image, "url", base + "/image/"+owner+"/"+"AHHYILU"+"/s48-c/"+owner);
    addNode(doc, image, "title", owner + " " + I18nUtil.getText(key,"title",request.getLocale()));
    addNode(doc, image, "link",base + "/" + owner);
    
 //channel
 if(categories != null){
  for(Category category:categories){
	  if(!all){
		  if(!category.isOpened() || category.getCount() < 1){
			  continue;
		  }
	  }
	  Element item = addNode(doc, channel, "item");
   	  addNode(doc, item, "pubDate" , category.getCreatdate().toString());
   	  addNode(doc, item, "atom", "updated", category.getLastupload().toString() );
   	  addNode(doc, item, "title", category.getName());
   	  addNode(doc, item, "description", getDescription(api,base,owner,category,I18nUtil.getLoacl(request)));
   	  addNode(doc, item, "link", "");
   	  addNode(doc, item, "author",owner);
   	  if(api){
   		  //api data here
   	  }	    	  
   	  Element media = addNode(doc,item,"media:group");
   	  Element title = addNode(doc, media, "media", "title", category.getName());
   	  addAttribute(doc, title, "type" , "plain");
   	  
   	  Element descript = addNode(doc, media, "media", "descript", "");
   	  addAttribute(doc, descript, "type" , "plain");
   	  
   	  addNode(doc, media, "media", "keywords", "");
   	  
	  String lablename = category.getLablename();
	  String imgurl = category.getImgurl();
	  String id = imgurl.substring(imgurl.lastIndexOf('/')+1,imgurl.lastIndexOf('.'));
	  String img = "/image/"+owner+"/"+lablename+"/"+id+".jpg";
	  String thumbnailImg = "/image/"+owner+"/"+lablename+"/s"+160+"-c/"+id+".jpg";
   	  Element content = addNode(doc, media, "media", "content", "");
   	  addAttribute(doc, content, "url" , base+img);
   	  addAttribute(doc, content, "type", "image/jpeg");
   	  addAttribute(doc, content, "medium", "image");
   	  
   	  Element thum = addNode(doc, media, "media", "thumbnail", "");
   	  addAttribute(doc, thum, "url" , base+thumbnailImg);
   	  addAttribute(doc, thum, "height", "160");
   	  addAttribute(doc, thum, "width", "160");
   	  
   	  addNode(doc, media, "media", "credit", owner);
	  
  }	    	  
   	 
 }
 
}
 
Example 57
Project: resin   File: HttpProxyServlet.java View source code 5 votes vote down vote up
/**
 * Handle the request.
 */
@Override
public void service(ServletRequest request, ServletResponse response)
  throws ServletException, IOException
{
  HttpServletRequest req = (HttpServletRequest) request;
  HttpServletResponse res = (HttpServletResponse) response;
  CauchoRequest cReq = null;

  if (req instanceof CauchoRequest)
    cReq = (CauchoRequest) req;

  String sessionId = req.getRequestedSessionId();

  String uri;
  if (req.isRequestedSessionIdFromURL()) {
    uri =  (req.getRequestURI() + ";jsessionid=" +
            req.getRequestedSessionId());
  }
  else
    uri = req.getRequestURI();

  String queryString = null;

  if (cReq != null)
    queryString = cReq.getPageQueryString();
  else {
    queryString
      = (String) req.getAttribute(RequestDispatcher.INCLUDE_QUERY_STRING);

    if (queryString == null)
      queryString = req.getQueryString();
  }

  if (queryString != null)
    uri += '?' + queryString;

  ClientSocket stream = _loadBalancer.openSticky(sessionId, request, null);

  try {
    long startRequestTime = Alarm.getCurrentTime();
    
    if (stream == null) {
      log.warning(L.l("{0}: no backend servers available to process {1}",
                      this, req.getRequestURI()));

      res.sendError(503); // send a busy
    }
    else if (handleRequest(req, res, uri, stream)) {
      stream.free(startRequestTime);
      stream = null;
      return;
    }
  } finally {
    if (stream != null)
      stream.close();
  }
}