Java Code Examples for javax.servlet.http.HttpServletResponse

The following are top voted examples for showing how to use javax.servlet.http.HttpServletResponse. 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: iot-server-appliances   File: FireAlarmManagerService.java View source code 9 votes vote down vote up
@Path("/device/remove/{device_id}")
@DELETE
public void removeDevice(@PathParam("device_id") String deviceId,
						 @Context HttpServletResponse response) {

	DeviceManagement deviceManagement = new DeviceManagement();
	DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
	deviceIdentifier.setId(deviceId);
	deviceIdentifier.setType(FireAlarmConstants.DEVICE_TYPE);
	try {
		boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice(
				deviceIdentifier);
		if (removed) {
			response.setStatus(HttpStatus.SC_OK);

		} else {
			response.setStatus(HttpStatus.SC_EXPECTATION_FAILED);

		}
	} catch (DeviceManagementException e) {
		log.error(e.getErrorMessage());

	}

}
 
Example 2
Project: jentrata-msh   File: RepositoryAdaptor.java View source code 7 votes vote down vote up
public String processRequest(HttpServletRequest request,
        HttpServletResponse response) throws RequestListenerException {

    String messageId = request.getParameter("message_id");
    String messageBox = request.getParameter("message_box");

    try {
        RepositoryDAO repositoryDAO = (RepositoryDAO) EbmsProcessor.core.dao
                .createDAO(RepositoryDAO.class);
        RepositoryDVO repositoryDVO = (RepositoryDVO) repositoryDAO
                .createDVO();
        repositoryDVO.setMessageId(messageId);
        repositoryDVO.setMessageBox(messageBox);
        boolean hasExist = repositoryDAO.findRepository(repositoryDVO);

        if (hasExist) {
            response.setCharacterEncoding(null);
            response.setContentType("application/download");
            response
                    .setHeader("Content-Disposition",
                            "attachment;filename=\""
                                    + repositoryDVO.getMessageId()
                                    + ".ebxml\"");

            ByteArrayInputStream bis = new ByteArrayInputStream(
                    repositoryDVO.getContent());

            IOHandler.pipe(bis, response.getOutputStream());
            bis.close();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 3
Project: jbosgi   File: WebBundleServlet.java View source code 7 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    String bundleSource = "";
    ClassLoader classLoader = WebBundleServlet.class.getClassLoader();
    try {
        if (classLoader instanceof BundleReference) {
            Bundle bundle = ((BundleReference)classLoader).getBundle();
            bundleSource = " from " + bundle.getSymbolicName();
        }
    } catch (Throwable th) {
        // ignore because the plain war does not see the OSGi API
    }

    String msg = req.getParameter("input");
    Writer writer = resp.getWriter();
    writer.write(msg + bundleSource);
}
 
Example 4
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 5
Project: gst-foundation   File: AbstractController.java View source code 7 votes vote down vote up
/**
 * Sends the http status code to the user-agent.
 * 
 * 
 * @param code the http response code
 * @return String to stream
 */

protected final String sendError(final int code, final Exception e) {
    LOG.debug(code + " status code sent due to exception " + e.toString(), e);
    if (LOG.isTraceEnabled()) {
        DebugHelper.dumpVars(ics, LOG);
    }
    switch (code) { // all the http status codes, we may restrict the list
    // to error and redirect
        case HttpServletResponse.SC_ACCEPTED:
        case HttpServletResponse.SC_BAD_GATEWAY:
        case HttpServletResponse.SC_BAD_REQUEST:
        case HttpServletResponse.SC_CONFLICT:
        case HttpServletResponse.SC_CONTINUE:
        case HttpServletResponse.SC_CREATED:
        case HttpServletResponse.SC_EXPECTATION_FAILED:
        case HttpServletResponse.SC_FORBIDDEN:
        case HttpServletResponse.SC_FOUND:
        case HttpServletResponse.SC_GATEWAY_TIMEOUT:
        case HttpServletResponse.SC_GONE:
        case HttpServletResponse.SC_HTTP_VERSION_NOT_SUPPORTED:
        case HttpServletResponse.SC_INTERNAL_SERVER_ERROR:
        case HttpServletResponse.SC_LENGTH_REQUIRED:
        case HttpServletResponse.SC_METHOD_NOT_ALLOWED:
        case HttpServletResponse.SC_MOVED_PERMANENTLY:
            // case HttpServletResponse.SC_MOVED_TEMPORARILY : //SC_FOUND is
            // preferred
        case HttpServletResponse.SC_MULTIPLE_CHOICES:
        case HttpServletResponse.SC_NO_CONTENT:
        case HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION:
        case HttpServletResponse.SC_NOT_ACCEPTABLE:
        case HttpServletResponse.SC_NOT_FOUND:
        case HttpServletResponse.SC_NOT_IMPLEMENTED:
        case HttpServletResponse.SC_NOT_MODIFIED:
        case HttpServletResponse.SC_OK:
        case HttpServletResponse.SC_PARTIAL_CONTENT:
        case HttpServletResponse.SC_PAYMENT_REQUIRED:
        case HttpServletResponse.SC_PRECONDITION_FAILED:
        case HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED:
        case HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE:
        case HttpServletResponse.SC_REQUEST_TIMEOUT:
        case HttpServletResponse.SC_REQUEST_URI_TOO_LONG:
        case HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
        case HttpServletResponse.SC_RESET_CONTENT:
        case HttpServletResponse.SC_SEE_OTHER:
        case HttpServletResponse.SC_SERVICE_UNAVAILABLE:
        case HttpServletResponse.SC_SWITCHING_PROTOCOLS:
        case HttpServletResponse.SC_TEMPORARY_REDIRECT:
        case HttpServletResponse.SC_UNAUTHORIZED:
        case HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE:
        case HttpServletResponse.SC_USE_PROXY:
            ics.StreamHeader(STATUS_HEADER, Integer.toString(code));
            break;
        default:
            ics.StreamHeader(STATUS_HEADER, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
            break;
    }
    Unknowndeps.unknonwDeps(ics);// failure case might be corrected on next
    // publish or save
    String element = null;

    if (goodString(ics.GetVar("site")) && ics.IsElement(ics.GetVar("site") + "/ErrorHandler/" + code)) {
        element = ics.GetVar("site") + "/ErrorHandler/" + code;
    } else if (ics.IsElement("GST/ErrorHandler/" + code)) {
        element = "GST/ErrorHandler/" + code;
    } else if (ics.IsElement("GST/ErrorHandler")) {
        element = "GST/ErrorHandler";
    }
    if (element != null) {
        ics.SetObj("com.fatwire.gst.foundation.exception", e);
        ics.CallElement(element, null);
        ics.SetObj("com.fatwire.gst.foundation.exception", null);
    } else {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        pw.flush();

        ics.StreamText("<h1>ERROR "
                + code
                + "</h1><p>An error has been raised. <br/>Please add an element at GST/ErrorHandler to handle the display of this message differently.<br/></br><pre>"
                + sw.toString() + "</pre></p>");
    }
    ics.SetErrno(ftErrors.exceptionerr);

    return null;

}
 
Example 6
Project: iot-server-appliances   File: LogoutServlet.java View source code 6 votes vote down vote up
protected void doPost(HttpServletRequest request,
					  HttpServletResponse response)
		throws ServletException, IOException {
	request.getSession().invalidate();
	response.sendRedirect("index.jsp");

}
 
Example 7
Project: iot-server-appliances   File: FireAlarmControllerService.java View source code 6 votes vote down vote up
@Path("/readcontrols/{owner}/{deviceId}") @GET public String readControls(@PathParam("owner") String owner,
        @PathParam("deviceId") String deviceId, @Context HttpServletResponse response) {
    String result = null;
    LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);

    if (deviceControlList == null) {
        result = "No controls have been set for device " + deviceId + " of owner " + owner;
        response.setStatus(HttpStatus.SC_NO_CONTENT);
    } else {
        try {
            result = deviceControlList.remove();
            response.setStatus(HttpStatus.SC_ACCEPTED);
            response.addHeader("Control", result);
        } catch (NoSuchElementException ex) {
            result = "There are no more controls for device " + deviceId + " of owner " + owner;
            response.setStatus(HttpStatus.SC_NO_CONTENT);
        }
    }
    log.info(result);
    return result;
}
 
Example 8
Project: jena   File: FusekiErrorHandler.java View source code 6 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
{
    AbstractHttpConnection connection = AbstractHttpConnection.getCurrentConnection();
    connection.getRequest().setHandled(true);
    String method = request.getMethod();
 
    if(!method.equals(HttpMethods.GET) && !method.equals(HttpMethods.POST) && !method.equals(HttpMethods.HEAD))
        return;
    
    response.setContentType(MimeTypes.TEXT_PLAIN_UTF_8) ;
    response.setHeader(HttpHeaders.CACHE_CONTROL, "must-revalidate,no-cache,no-store") ;
    
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(1024) ;
    //String writer = IO.UTF8(null) ;
    try(Writer writer = new OutputStreamWriter(bytes, "UTF-8")) {

        handleErrorPage(request, writer, connection.getResponse().getStatus(), connection.getResponse().getReason());

        if ( ! Fuseki.VERSION.equalsIgnoreCase("development") )
        {
            writer.write("\n") ;
            writer.write("\n") ;
            writer.write(format("Fuseki - version %s (Build date: %s)\n", Fuseki.VERSION, Fuseki.BUILD_DATE)) ;
        }
        writer.flush();
    }
    response.setContentLength(bytes.size()) ;
    // Copy
    response.getOutputStream().write(bytes.toByteArray()) ;
}
 
Example 9
Project: virgo.kernel   File: ContentServlet.java View source code 6 votes vote down vote up
private void prepareContentResponse(final HttpServletResponse response, final URL resource) throws IOException {	
	URLConnection resourceConn = resource.openConnection();
	response.setContentType(getResponseMimeType(resource));
	response.setHeader(HTTP_CONTENT_LENGTH_HEADER, Long.toString(resourceConn.getContentLength()));
	response.setDateHeader(HTTP_LAST_MODIFIED_HEADER, resourceConn.getLastModified());
	if (cacheTimeout > 0) {
		configureCaching(response, cacheTimeout);
	}
}
 
Example 10
Project: balerocms-enterprise   File: BlogController.java View source code 6 votes vote down vote up
@RequestMapping(value = "/{permalink}", method = RequestMethod.POST)
String postAddComment(@PathVariable("permalink") String permalink,
                      @RequestParam("content") String content,
                      Locale locale,
                      HttpServletResponse response) {
    log.debug("Request method POST -> /blog/" + permalink);
    String username = userService.getMyUsername();
        Cookie userCookie = new Cookie("commentCookie", "commented");
        response.addCookie(userCookie);
        commentService.createComment(
                content,
                locale.getLanguage(),
                username,
                permalink
        );
    return "redirect:/blog/" + permalink;
}
 
Example 11
Project: richfaces   File: ResourceHandlerImplTest.java View source code 6 votes vote down vote up
public void testReadCacheableResource() throws Exception {
    WebRequest webRequest = new WebRequest(new URL(
        "http://localhost/rfRes/org.richfaces.resource.CacheableResourceImpl.jsf"));

    webRequest.getAdditionalHeaders().put(ECHO_HEADER, "ping?");

    WebResponse webResponse = webClient.loadWebResponse(webRequest);

    assertEquals(HttpServletResponse.SC_OK, webResponse.getStatusCode());
    assertEquals(ResourceUtils.formatHttpDate(lastModified.getTime()), webResponse.getResponseHeaderValue("Last-Modified"));
    assertEquals(ResourceUtils.formatHttpDate(currentTime.getTime()), webResponse.getResponseHeaderValue("Date"));
    assertEquals(ResourceUtils.formatHttpDate(expires.getTime()), webResponse.getResponseHeaderValue("Expires"));
    assertEquals("max-age=1209600", webResponse.getResponseHeaderValue("Cache-Control"));
    assertTrue(webResponse.getResponseHeaderValue("Content-Type").startsWith("text/plain"));
    assertEquals("W/\"" + "ping?".length() + "-" + lastModified.getTime() + "\"",
        webResponse.getResponseHeaderValue("ETag"));
    assertNull(webResponse.getResponseHeaderValue("Pragma"));
    assertEquals("ping?", webResponse.getContentAsString("US-ASCII"));
    webRequest.getAdditionalHeaders().put(ECHO_HEADER, "pong");

    WebResponse cachedWebResponse = webClient.loadWebResponse(webRequest);

    assertEquals(HttpServletResponse.SC_OK, cachedWebResponse.getStatusCode());
    assertEquals("ping?", cachedWebResponse.getContentAsString("US-ASCII"));
    webRequest.getAdditionalHeaders().put(IF_MODIFIED_SINCE, ResourceUtils.formatHttpDate(currentTime));

    WebResponse cachedWebResponse2 = webClient.loadWebResponse(webRequest);

    assertEquals(HttpServletResponse.SC_NOT_MODIFIED, cachedWebResponse2.getStatusCode());
}
 
Example 12
Project: liferay-apps-content-targeting   File: AnalyticsProcessorServlet.java View source code 6 votes vote down vote up
@Override
public void service(
		HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException {

	try {
		processEvents(request, response);
	}
	catch (Exception e) {
		_log.error(e, e);

		PortalUtil.sendError(
			HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e, request,
			response);
	}
}
 
Example 13
Project: richfaces   File: ResourceHandlerImplTest.java View source code 6 votes vote down vote up
public void testMarkerFile() throws Exception {
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

    assertNotNull(Class.forName("org.richfaces.resource.MarkerFileResourceImpl", true, contextClassLoader));
    assertNotNull(contextClassLoader
        .getResource("META-INF/org.richfaces.resource.MarkerFileResourceImpl.resource.properties"));

    WebRequest markerFileWebRequest = new WebRequest(new URL(
        "http://localhost/rfRes/org.richfaces.resource.MarkerFileResourceImpl.jsf"));
    WebResponse markerFileResponse = webClient.loadWebResponse(markerFileWebRequest);

    assertEquals(HttpServletResponse.SC_OK, markerFileResponse.getStatusCode());
    assertNotNull(Class.forName("org.richfaces.resource.NoMarkerFileResourceImpl", true, contextClassLoader));
    assertNull(contextClassLoader
        .getResource("META-INF/org.richfaces.resource.NoMarkerFileResourceImpl.resource.properties"));

    WebRequest noMarkerFileRequestSettings = new WebRequest(new URL(
        "http://localhost/rfRes/org.richfaces.resource.NoMarkerFileResourceImpl.jsf"));
    WebResponse noMarkerResponse = webClient.loadWebResponse(noMarkerFileRequestSettings);

    assertEquals(HttpServletResponse.SC_NOT_FOUND, noMarkerResponse.getStatusCode());
}
 
Example 14
Project: aipo   File: ALBaseFilter.java View source code 6 votes vote down vote up
/**
 * @param request
 * @param response
 * @param filterChain
 * @throws IOException
 * @throws ServletException
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain filterChain) throws IOException, ServletException {
  ServletContext prevServletContext = ServletContextLocator.get();
  HttpServletRequest prevHttpServletRequest = HttpServletRequestLocator.get();
  HttpServletResponse prevHttpServletResponse =
    HttpServletResponseLocator.get();
  if (request instanceof HttpServletRequest) {
    HttpServletRequest hreq = (HttpServletRequest) request;
    if (isInvalid(hreq.getQueryString()) || isInvalid(hreq.getRequestURI())) {
      ((HttpServletResponse) response)
        .sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }
  }
  try {
    DataContext dataContext = null;
    try {
      dataContext =
        Database.createDataContext(getCurrentOrgId(
          (HttpServletRequest) request,
          (HttpServletResponse) response));
    } catch (Exception e) {
      logger.error("ALBaseFilter.doFilter", e);
    }
    ServletContextLocator.set(filterConfig.getServletContext());
    HttpServletRequestLocator.set((HttpServletRequest) request);
    HttpServletResponseLocator.set((HttpServletResponse) response);
    DataContext.bindThreadDataContext(dataContext);
    filterChain.doFilter(request, response);
  } finally {
    ServletContextLocator.set(prevServletContext);
    HttpServletRequestLocator.set(prevHttpServletRequest);
    HttpServletResponseLocator.set(prevHttpServletResponse);
    Database.tearDown();
  }
}
 
Example 15
Project: Jorum-DSpace   File: DAVItem.java View source code 6 votes vote down vote up
@Override
protected void put() throws SQLException, AuthorizeException,
        IOException, DAVStatusException
{
    throw new DAVStatusException(HttpServletResponse.SC_NOT_IMPLEMENTED,
            "PUT is not implemented for Item.");
}
 
Example 16
Project: OAuth2.0ProviderForJava   File: OAuth2Servlet.java View source code 6 votes vote down vote up
public static void handleException(HttpServletRequest request, HttpServletResponse response,
		Exception e, String realm, boolean sendBodyInJson, boolean withAuthHeader)
    throws IOException, ServletException {
	
    if (e instanceof OAuth2ProblemException) {
        OAuth2ProblemException problem = (OAuth2ProblemException) e;

        Object httpCode = getHttpCode(problem);

        response.reset();
        response.setStatus(Integer.parseInt(httpCode.toString()));
        
        
        OAuth2Message message = new OAuth2Message(null, null, problem.getParameters().entrySet()); 	
        if(withAuthHeader){
        	response.addHeader("WWW-Authenticate", message.getWWWAuthenticateHeader(realm));
        }

        List<Map.Entry<String, String>> sendBackErrorParameters = new ArrayList<Map.Entry<String, String>>(SEND_BACK_ERROR_PARAMETERS.size());
        for (Map.Entry parameter : message.getParameters()) {
            if(SEND_BACK_ERROR_PARAMETERS.contains(parameter.getKey()))
            {
                sendBackErrorParameters.add(parameter);
            }
        }

        if (sendBodyInJson) {
            sendFormInJson(response, sendBackErrorParameters);
        }else{
            String redirect_uri = constructErrorRedirectUri(message,sendBackErrorParameters);

        	response.addHeader(OAuth2ProblemException.HTTP_LOCATION,redirect_uri);
        }
    } else if (e instanceof IOException) {
        throw (IOException) e;
    } else if (e instanceof ServletException) {
        throw (ServletException) e;
    } else if (e instanceof RuntimeException) {
        throw (RuntimeException) e;
    } else {
        throw new ServletException(e);
    }
}
 
Example 17
Project: Magnolia   File: RequestHeaderUtil.java View source code 6 votes vote down vote up
public static void setHeader(final HttpServletResponse response, final String name, final Object value) {
    if (value instanceof Long) {
        response.addDateHeader(name, ((Long) value).longValue());
    } else if (value instanceof Integer) {
        response.addIntHeader(name, ((Integer) value).intValue());
    } else if (value instanceof String) {
        response.addHeader(name, (String) value);
    } else {
        throw new IllegalStateException("Unrecognized type for header [" + name + "], value is: " + value);
    }
}
 
Example 18
Project: Magnolia   File: ContentSecurityFilterTest.java View source code 6 votes vote down vote up
@Test
public void testIsAllowedForAnonymous() throws Exception {
    // GIVEN
    when(MgnlContext.getUser().getName()).thenReturn(UserManager.ANONYMOUS_USER);
    when(request.getMethod()).thenReturn("GET");

    final ContentSecurityFilter filter = new ContentSecurityFilter();

    // WHEN
    final boolean result = filter.isAllowed(request, response);

    // THEN
    assertEquals(false, result);
    verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example 19
Project: Jorum-DSpace   File: DAVItem.java View source code 6 votes vote down vote up
@Override
protected int mkcolInternal(String waste) throws DAVStatusException,
        SQLException, AuthorizeException, IOException
{
    throw new DAVStatusException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
            "MKCOL method not allowed for Item.");
}
 
Example 20
Project: Jorum-DSpace   File: EdiauthAuthentication.java View source code 6 votes vote down vote up
/**
    * Returns URL of ediauth-login servlet.
    *
    * @param context
    *            DSpace context, will be modified (EPerson set) upon success.
    *
    * @param request
    *            The HTTP request that started this operation, or null if not applicable.
    *
    * @param response
    *            The HTTP response from the servlet method.
    *
    * @return fully-qualified URL
    */
public String loginPageURL(Context context, 
		                   HttpServletRequest request,
		                   HttpServletResponse response) 
{
	return response.encodeRedirectURL(request.getContextPath() + "/ediauth-login");
}
 
Example 21
Project: Magnolia   File: ContentSecurityFilterTest.java View source code 6 votes vote down vote up
@Test
public void testIsAllowedForOther() throws Exception {
    // GIVEN
    when(MgnlContext.getUser().getName()).thenReturn("AnyAuthenticatedUser");
    when(request.getMethod()).thenReturn("GET");

    final ContentSecurityFilter filter = new ContentSecurityFilter();

    // WHEN
    final boolean result = filter.isAllowed(request, response);

    // THEN
    assertEquals(false, result);
    verify(response).setStatus(HttpServletResponse.SC_FORBIDDEN);
}
 
Example 22
Project: resin   File: HttpResponse.java View source code 6 votes vote down vote up
/**
 * Implementation to write the HTTP headers.  If the length is positive,
 * it's a small request where the buffer contains the entire request,
 * so the length is already known.
 *
 * @param os the output stream to write the headers to.
 * @param length if non-negative, the length of the entire request.
 *
 * @return true if the data in the request should use chunked encoding.
 */
@Override
protected boolean writeHeadersInt(int length,
                                  boolean isHead)
  throws IOException
{
  HttpServletRequestImpl request = _request.getRequestFacade();
  HttpServletResponseImpl response = _request.getResponseFacade();

  if (request == null)
    return false;

  _isChunked = false;

  int version = _request.getVersion();
  boolean debug = log.isLoggable(Level.FINE);

  if (version < HttpRequest.HTTP_1_0) {
    _request.killKeepalive("http client version " + version);
    return false;
  }

  TcpSocketLink tcpConn = null;

  if (_request.getConnection() instanceof TcpSocketLink)
    tcpConn = (TcpSocketLink) _request.getConnection();

  WebApp webApp = request.getWebApp();

  String contentType = response.getContentTypeImpl();
  String charEncoding = response.getCharacterEncodingImpl();

  WriteStream os = getRawWrite();

  int statusCode = response.getStatus();
  if (statusCode == 200) {
    if (version < HttpRequest.HTTP_1_1)
      os.write(_http10ok, 0, _http10ok.length);
    else
      os.write(_http11ok, 0, _http11ok.length);
  } else {
    if (version < HttpRequest.HTTP_1_1)
      os.printLatin1("HTTP/1.0 ");
    else
      os.printLatin1("HTTP/1.1 ");

    os.write((statusCode / 100) % 10 + '0');
    os.write((statusCode / 10) % 10 + '0');
    os.write(statusCode % 10 + '0');
    os.write(' ');
    os.printLatin1(response.getStatusMessage());
  }

  if (debug) {
    log.fine(_request.dbgId() + "HTTP/1.1 " +
             statusCode + " " + response.getStatusMessage());
  }

  boolean isUpgrade = false;

  if (tcpConn != null && tcpConn.isDuplex()) {
    isUpgrade = true;

    String upgrade = getHeader("Upgrade");

    if (upgrade != null) {
      os.printLatin1("\r\nUpgrade: ");
      os.printLatin1NoLf(upgrade);
    }

    os.printLatin1("\r\nConnection: Upgrade");
    _request.killKeepalive("duplex/upgrade");

    if (debug)
      log.fine(_request.dbgId() + "Connection: Upgrade");
  }

  if (! containsHeader("Server")) {
    os.write(_resinServerBytes, 0, _resinServerBytes.length);
  }

  if (statusCode >= 400) {
    removeHeader("ETag");
    removeHeader("Last-Modified");
  }
  else if (statusCode == HttpServletResponse.SC_NOT_MODIFIED
           || statusCode == HttpServletResponse.SC_NO_CONTENT) {
    // php/1b0k

    contentType = null;
  }
  else if (response.isCacheControl()) {
    // application manages cache control
  }
  else if (response.isNoCache()) {
    // server/1b15
    removeHeader("ETag");
    removeHeader("Last-Modified");

    // even in case of 302, this may be needed for filters which
    // automatically set cache headers
    setHeaderImpl("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");

    os.printLatin1("\r\nCache-Control: no-cache");

    if (debug) {
      log.fine(_request.dbgId() + "" +
               "Cache-Control: no-cache");
    }
  }
  else if (response.isNoCacheUnlessVary()
           && ! containsHeader("Vary")) {
    os.printLatin1("\r\nCache-Control: private");

    if (debug) {
      log.fine(_request.dbgId() + "Cache-Control: private");
    }
  }
  else if (response.isPrivateCache()) {
    if (HttpRequest.HTTP_1_1 <= version) {
      // technically, this could be private="Set-Cookie,Set-Cookie2"
      // but caches don't recognize it, so there's no real extra value
      os.printLatin1("\r\nCache-Control: private");

      if (debug)
        log.fine(_request.dbgId() + "Cache-Control: private");
    }
    else {
      setHeaderImpl("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
      os.printLatin1("\r\nCache-Control: no-cache");

      if (debug) {
        log.fine(_request.dbgId() + "CacheControl: no-cache");
      }
    }
  }

  int size = _headerKeys.size();
  for (int i = 0; i < size; i++) {
    String key = (String) _headerKeys.get(i);

    if (isUpgrade && "Upgrade".equalsIgnoreCase(key))
      continue;

    os.write('\r');
    os.write('\n');
    os.printLatin1NoLf(key);
    os.write(':');
    os.write(' ');
    os.printLatin1NoLf((String) _headerValues.get(i));

    if (debug) {
      log.fine(_request.dbgId() + "" +
               key + ": " + _headerValues.get(i));
    }
  }

  long now = Alarm.getCurrentTime();
  ArrayList<Cookie> cookiesOut = response.getCookies();

  if (cookiesOut != null) {
    for (int i = 0; i < cookiesOut.size(); i++) {
      Cookie cookie = cookiesOut.get(i);
      int cookieVersion = cookie.getVersion();

      CharBuffer cb = _cb;
      // XXX:
      fillCookie(cb, cookie, now, cookieVersion, false);
      os.printLatin1("\r\nSet-Cookie: ");
      os.printLatin1(cb.getBuffer(), 0, cb.getLength());
      if (cookieVersion > 0) {
        fillCookie(cb, cookie, now, cookieVersion, true);
        os.printLatin1("\r\nSet-Cookie2: ");
        os.printLatin1(cb.getBuffer(), 0, cb.getLength());
      }

      if (debug)
        log.fine(_request.dbgId() + "Set-Cookie: " + cb);
    }
  }

  if (contentType != null) {
    // server/1b5a
    if (charEncoding == null && contentType.startsWith("text/")) {
      if (webApp != null)
        charEncoding = webApp.getCharacterEncoding();

      // always use a character encoding to avoid XSS attacks (?)
      if (charEncoding == null)
        charEncoding = "utf-8";
    }

    os.write(_contentTypeBytes, 0, _contentTypeBytes.length);
    os.printLatin1(contentType);
    
    if (charEncoding != null) {
      os.write(_charsetBytes, 0, _charsetBytes.length);
      os.printLatin1(charEncoding);
    }

    if (debug) {
      log.fine(_request.dbgId() + "Content-Type: " + contentType
               + "; charset=" + charEncoding);
    }
  }

  if (hasFooter()) {
    _contentLength = -1;
    length = -1;
  }

  boolean hasContentLength = false;
  /*
  if (isHead()) {
    // server/269t, server/0560
    hasContentLength = true;
    os.write(_contentLengthBytes, 0, _contentLengthBytes.length);
    os.print(0);
  }
  else
  */
  if (_contentLength >= 0) {
    os.write(_contentLengthBytes, 0, _contentLengthBytes.length);
    os.print(_contentLength);
    hasContentLength = true;

    if (debug)
      log.fine(_request.dbgId() + "Content-Length: " + _contentLength);
  }
  else if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
    // #3089
    // In the HTTP spec, a 304 has no message body so the content-length
    // is not needed.  The content-length is not explicitly forbidden,
    // but does cause problems with certain clients.
    hasContentLength = true;
    setHead();
  }
  else if (statusCode == HttpServletResponse.SC_NO_CONTENT) {
    hasContentLength = true;
    os.write(_contentLengthBytes, 0, _contentLengthBytes.length);
    os.print(0);
    setHead();

    if (debug)
      log.fine(_request.dbgId() + "Content-Length: 0");
  }
  else if (length >= 0) {
    os.write(_contentLengthBytes, 0, _contentLengthBytes.length);
    os.print(length);
    hasContentLength = true;

    if (debug)
      log.fine(_request.dbgId() + "Content-Length: " + length);
  }

  if (version < HttpRequest.HTTP_1_1) {
    _request.killKeepalive("http response version: " + version);
  }
  else {
    /* XXX: the request processing already processed this header
    CharSegment conn = _request.getHeaderBuffer(_connectionCb,
                                                _connectionCb.length);
    if (conn != null && conn.equalsIgnoreCase(_closeCb)) {
      _request.killKeepalive();
    }
    else
    */

    if (_request.isKeepalive()) {
    }
    else if (isUpgrade) {
      _request.killKeepalive("http response upgrade");
    }
    else {
      os.write(_connectionCloseBytes, 0, _connectionCloseBytes.length);

      if (debug)
        log.fine(_request.dbgId() + "Connection: close");
    }
  }

  if (HttpRequest.HTTP_1_1 <= version
      && ! hasContentLength
      && ! isHead) {
    os.printLatin1("\r\nTransfer-Encoding: chunked");
    _isChunked = true;

    if (debug)
      log.fine(_request.dbgId() + "Transfer-Encoding: chunked");
  }

  if (_lastDate / 1000 != now / 1000) {
    fillDate(now);
  }

  if (_isChunked)
    os.write(_dateBuffer, 0, _dateBufferLength - 2);
  else
    os.write(_dateBuffer, 0, _dateBufferLength);

  return _isChunked;
}
 
Example 23
Project: Magnolia   File: RequestHeaderUtil.java View source code 6 votes vote down vote up
public static void addAndVerifyHeader(HttpServletResponse response, String name, String value) {
    response.addHeader(name, value);
    final boolean containsHeader = response.containsHeader(name);
    if (!containsHeader) {
        throw new IllegalStateException("Failure when attempting to set response header " + name + ": " + value);
    }
}
 
Example 24
Project: virgo.kernel   File: ContentServlet.java View source code 6 votes vote down vote up
private PrintWriter selectOutputStream(final HttpServletRequest request, final HttpServletResponse response, final URL resource) throws IOException {
	String acceptEncoding = request.getHeader("Accept-Encoding");
	String mimeType;
	try {
		mimeType = response.getContentType();
	} catch(UnsupportedOperationException e){
		mimeType = getResponseMimeType(resource);
	}
	if (gzipEnabled && 
			acceptEncoding != null && 
			acceptEncoding.indexOf("gzip") > -1 && 
			matchesCompressedMimeTypes(mimeType)) {
		log.debug("Enabling GZIP compression for the current response.");
		return new PrintWriter(new GZIPResponseStream(response));
	} else {
		return response.getWriter();
	}
}
 
Example 25
Project: Java-Device-Detection   File: ImageOptimizer.java View source code 6 votes vote down vote up
private static void sendResponse(
        HttpServletResponse response, 
        InputStream imageResponse,
        long imageLength) throws IOException {
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Length",
            String.valueOf(imageLength));

    BufferedOutputStream output = null;

    try {
        output = new BufferedOutputStream(
                response.getOutputStream(),
                DEFAULT_BUFFER_SIZE);

        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = imageResponse.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        close(output);
    }
}
 
Example 26
Project: csrf-jhipster   File: GZipServletFilter.java View source code 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (!isIncluded(httpRequest) && acceptsGZipEncoding(httpRequest) && !response.isCommitted()) {
        // Client accepts zipped content
        if (log.isTraceEnabled()) {
            log.trace("{} Written with gzip compression", httpRequest.getRequestURL());
        }

        // Create a gzip stream
        final ByteArrayOutputStream compressed = new ByteArrayOutputStream();
        final GZIPOutputStream gzout = new GZIPOutputStream(compressed);

        // Handle the request
        final GZipServletResponseWrapper wrapper = new GZipServletResponseWrapper(httpResponse, gzout);
        wrapper.setDisableFlushBuffer(true);
        chain.doFilter(request, wrapper);
        wrapper.flush();

        gzout.close();

        // double check one more time before writing out
        // repsonse might have been committed due to error
        if (response.isCommitted()) {
            return;
        }

        // return on these special cases when content is empty or unchanged
        switch (wrapper.getStatus()) {
            case HttpServletResponse.SC_NO_CONTENT:
            case HttpServletResponse.SC_RESET_CONTENT:
            case HttpServletResponse.SC_NOT_MODIFIED:
                return;
            default:
        }

        // Saneness checks
        byte[] compressedBytes = compressed.toByteArray();
        boolean shouldGzippedBodyBeZero = GZipResponseUtil.shouldGzippedBodyBeZero(compressedBytes, httpRequest);
        boolean shouldBodyBeZero = GZipResponseUtil.shouldBodyBeZero(httpRequest, wrapper.getStatus());
        if (shouldGzippedBodyBeZero || shouldBodyBeZero) {
            // No reason to add GZIP headers or write body if no content was written or status code specifies no
            // content
            response.setContentLength(0);
            return;
        }

        // Write the zipped body
        GZipResponseUtil.addGzipHeader(httpResponse);

        response.setContentLength(compressedBytes.length);

        response.getOutputStream().write(compressedBytes);

    } else {
        // Client does not accept zipped content - don't bother zipping
        if (log.isTraceEnabled()) {
            log.trace("{} Written without gzip compression because the request does not accept gzip", httpRequest.getRequestURL());
        }
        chain.doFilter(request, response);
    }
}
 
Example 27
Project: FireflowEngine20   File: GetProcessDefsHandler.java View source code 6 votes vote down vote up
protected void outputRawXml(String processXml,HttpServletResponse resp)
	throws ServletException, IOException {
		// ??contentType
		String encoding = Utils.findXmlCharset(processXml);
//		resp.setContentType("text/xml? charset="+encoding);
		resp.setContentType("text/xml");
		resp.setCharacterEncoding(encoding);

		// ?????????
		resp.setHeader("Pragma", "no-cache");
		resp.setHeader("Cache-Control", "no-cache");
		resp.setIntHeader("Expires", -1);

		
		byte[] byteArr = processXml.getBytes(encoding);
		
		OutputStream outStream = resp.getOutputStream();
		outStream.write(byteArr);
	}
 
Example 28
Project: Katari   File: CasProcessingFilterEntryPoint.java View source code 6 votes vote down vote up
/** Starts the authentication.
 *
 * This method redirects the browser to the cas login page.
 *
 * This method can be called only with a non null servicesUrlBuilder.
 *
 * @param servletRequest The servlet request. This must be an instance of
 * HttpServletRequest. It cannot be null.
 *
 * @param servletResponse The servlet response. This must be an instance of
 * HttpServletResponse. It cann0t be null.
 *
 * @param authenticationException This parameter is not used.
 *
 * @throws IOException in case of an io error.
 *
 * @throws ServletException in case of an unexpected error.
 */
public void commence(final ServletRequest servletRequest, final
    ServletResponse servletResponse, final AuthenticationException
    authenticationException) throws IOException, ServletException {

  log.trace("Entering commence");

  if (servicesUrlBuilder == null) {
    throw new IllegalStateException("CasServicesUrlBuilder must be"
        + " specified");
  }

  if (!(servletRequest instanceof HttpServletRequest)) {
    throw new ServletException("This filter can only be applied to http"
        + " requests.");
  }
  if (!(servletResponse instanceof HttpServletResponse)) {
    throw new ServletException("This filter can only be applied to http"
        + " responses.");
  }

  HttpServletRequest request = (HttpServletRequest) servletRequest;
  HttpServletResponse response = (HttpServletResponse) servletResponse;

  String service = servicesUrlBuilder.buildServiceUrl(request);
  String loginUrl = servicesUrlBuilder.buildLoginUrl(request);

  String urlEncodedService = response.encodeURL(service);

  StringBuffer buffer = new StringBuffer(URL_BUFFER_LENGTH);

  buffer.append(loginUrl);
  buffer.append("?service=");
  buffer.append(URLEncoder.encode(urlEncodedService, "UTF-8"));
  // buffer.append(serviceProperties.isSendRenew() ? "&renew=true" : "");

  response.sendRedirect(buffer.toString());
  log.trace("Leaving commence");
}
 
Example 29
Project: sisu-guice   File: ServletDispatchIntegrationTest.java View source code 6 votes vote down vote up
public void testForwardUsingRequestDispatcher() throws IOException, ServletException {
  Guice.createInjector(new ServletModule() {
    @Override
    protected void configureServlets() {
      serve("/").with(ForwardingServlet.class);
      serve("/blah.jsp").with(ForwardedServlet.class);
    }
  });

  final HttpServletRequest requestMock = createMock(HttpServletRequest.class);
  HttpServletResponse responseMock = createMock(HttpServletResponse.class);
  expect(requestMock.getRequestURI())
      .andReturn("/")
      .anyTimes();
  expect(requestMock.getContextPath())
      .andReturn("")
      .anyTimes();

  requestMock.setAttribute(REQUEST_DISPATCHER_REQUEST, true);
  expect(requestMock.getAttribute(REQUEST_DISPATCHER_REQUEST)).andReturn(true);
  requestMock.removeAttribute(REQUEST_DISPATCHER_REQUEST);

  expect(responseMock.isCommitted()).andReturn(false);
  responseMock.resetBuffer();

  replay(requestMock, responseMock);

  new GuiceFilter()
      .doFilter(requestMock, responseMock,
          createMock(FilterChain.class));

  assertEquals("Incorrect number of forwards", 1, ForwardedServlet.forwardedTo);
  verify(requestMock, responseMock);
}
 
Example 30
Project: iot-server-appliances   File: SenseBotControllerService.java View source code 6 votes vote down vote up
@Path("/pushsonardata") @POST @Consumes(MediaType.APPLICATION_JSON) public String pushSonarData(
        final DeviceJSON dataMsg, @Context HttpServletResponse response) {
    String result = null;

    String sonar = dataMsg.value;                            //TEMP-PIR-SONAR-LDR

    if (sonar.equals("-1")) {
        log.info("Recieved a 'No Obstacle' Sonar value. (Means there are no abstacles within 30cm)");
    } else {
        log.info("Recieved Sonar Sensor Data Value: " + sonar + " cm");

        result = DeviceControllerService
                .pushData(dataMsg.owner, "SenseBot", dataMsg.deviceId, System.currentTimeMillis(), "DeviceData",
                        sonar, "SONAR", response);

        if (response.getStatus() != HttpStatus.SC_ACCEPTED) {
            return result;
        }
    }

    return result;
}
 
Example 31
Project: EECE496   File: AppEngineHttpFetcher.java View source code 6 votes vote down vote up
private static boolean isRedirect(int responseCode) {
  switch (responseCode) {
    case HttpServletResponse.SC_MOVED_PERMANENTLY:
    case HttpServletResponse.SC_MOVED_TEMPORARILY:
    case HttpServletResponse.SC_SEE_OTHER:
    case HttpServletResponse.SC_TEMPORARY_REDIRECT:
      return true;
    default:
      return false;
  }
}
 
Example 32
Project: resin   File: Server.java View source code 6 votes vote down vote up
/**
 * Sets the invocation
 */
@Override
public Invocation buildInvocation(Invocation invocation)
  throws ConfigException
{
  if (_configException != null) {
    invocation.setFilterChain(new ExceptionFilterChain(_configException));
    invocation.setWebApp(getErrorWebApp());
    invocation.setDependency(AlwaysModified.create());

    return invocation;
  }
  else if (_lifecycle.waitForActive(_waitForActiveTime)) {
    return _hostContainer.buildInvocation(invocation);
  }
  else {
    int code = HttpServletResponse.SC_SERVICE_UNAVAILABLE;

    invocation.setFilterChain(new ErrorFilterChain(code));
    invocation.setWebApp(getErrorWebApp());
    invocation.setDependency(AlwaysModified.create());

    return invocation;
  }
}
 
Example 33
Project: Jorum-DSpace   File: DAVCollection.java View source code 6 votes vote down vote up
/**
 * PUT ingests a package as a new Item. Package type (must match pluggable
 * packager name) is in either (a) "package" query arg in URI (b)
 * content-type request header
 * 
 * @throws SQLException the SQL exception
 * @throws AuthorizeException the authorize exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws DAVStatusException the DAV status exception
 */
@Override
protected void put() throws SQLException, AuthorizeException,
        IOException, DAVStatusException
{
    try
    {
        String packageType = this.request.getParameter("package");
        if (packageType == null)
        {
            packageType = this.request.getContentType();
        }
        if (packageType == null)
        {
            throw new DAVStatusException(
                    HttpServletResponse.SC_BAD_REQUEST,
                    "Cannot determine package type,  need content-type header or package param");
        }

        PackageIngester sip = (PackageIngester) PluginManager
                .getNamedPlugin(PackageIngester.class, packageType);
        if (sip == null)
        {
            throw new DAVStatusException(
                    HttpServletResponse.SC_BAD_REQUEST,
                    "Cannot find importer for package type: " + packageType);
        }

        /*
         * Ugh. Servlet container doesn't get end-of-file right on input
         * stream so we have to count it, when possible.
         */
        int contentLength = this.request.getIntHeader("Content-Length");
        InputStream pis = this.request.getInputStream();
        if (contentLength >= 0)
        {
            pis = new CountedInputStream(pis, contentLength);
            log.debug("put: Using CountedInputStream, length="
                    + String.valueOf(contentLength));
        }
        // GWaller 26/08/09 PackageIngester now supports array of Collections - simply wrap this collection in a single item array
        WorkspaceItem wi = sip.ingest(this.context, new Collection[] {this.collection}, pis,
                PackageParameters.create(this.request), null);
        WorkflowItem wfi = WorkflowManager.startWithoutNotify(this.context, wi);

        // get new item's location: if workflow completed, then look
        // for handle (but be ready for disappointment); otherwise,
        // return the workflow item's resource.
        int state = wfi.getState();
        String location = null;
        if (state == WorkflowManager.WFSTATE_ARCHIVE)
        {
            Item ni = wfi.getItem();
            String handle = HandleManager.findHandle(this.context, ni);
            String end = (handle != null) ? DAVDSpaceObject
                    .getPathElt(handle) : DAVItem.getPathElt(ni);
            DAVItem newItem = new DAVItem(this.context, this.request, this.response,
                    makeChildPath(end), ni);
            location = newItem.hrefURL();
        }
        else if (state == WorkflowManager.WFSTATE_SUBMIT
                || state == WorkflowManager.WFSTATE_STEP1POOL)
        {
            location = hrefPrefix() + DAVWorkflow.getPath(wfi);
        }
        else
        {
            throw new DAVStatusException(
                    HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Workflow object in unexpected state, state="
                            + String.valueOf(state) + ", aborting PUT.");
        }

        this.context.commit();
        log.info("Created new Item, location=" + location);
        this.response.setHeader("Location", location);
        this.response.setStatus(HttpServletResponse.SC_CREATED);
    }
    catch (PackageException pe)
    {
        pe.log(log);
        throw new DAVStatusException(
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR, pe.toString());
    }
    catch (CrosswalkException ie)
    {
        String reason = "";
        if (ie.getCause() != null)
        {
            reason = ", Reason: " + ie.getCause().toString();
        }
        log.error(ie.toString() + reason);
        throw new DAVStatusException(
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ie.toString()
                        + reason);
    }
}
 
Example 34
Project: HDP-2.2-Patched   File: TransferFsImage.java View source code 6 votes vote down vote up
/**
 * Requests that the NameNode download an image from this node.
 *
 * @param fsName the http address for the remote NN
 * @param imageListenAddress the host/port where the local node is running an
 *                           HTTPServer hosting GetImageServlet
 * @param storage the storage directory to transfer the image from
 * @param txid the transaction ID of the image to be uploaded
 */
public static void uploadImageFromStorage(String fsName,
    InetSocketAddress imageListenAddress,
    Storage storage, long txid) throws IOException {
  
  String fileid = GetImageServlet.getParamStringToPutImage(
      txid, imageListenAddress, storage);
  // this doesn't directly upload an image, but rather asks the NN
  // to connect back to the 2NN to download the specified image.
  try {
    TransferFsImage.getFileClient(fsName, fileid, null, null, false);
  } catch (HttpGetFailedException e) {
    if (e.getResponseCode() == HttpServletResponse.SC_CONFLICT) {
      // this is OK - this means that a previous attempt to upload
      // this checkpoint succeeded even though we thought it failed.
      LOG.info("Image upload with txid " + txid + 
          " conflicted with a previous image upload to the " +
          "same NameNode. Continuing...", e);
      return;
    } else {
      throw e;
    }
  }
  LOG.info("Uploaded image with txid " + txid + " to namenode at " +
  		fsName);
}
 
Example 35
Project: HDP-2.2-Patched   File: TestAuthenticationFilter.java View source code 6 votes vote down vote up
public void testManagementOperation() throws Exception {
  AuthenticationFilter filter = new AuthenticationFilter();
  try {
    FilterConfig config = Mockito.mock(FilterConfig.class);
    Mockito.when(config.getInitParameter("management.operation.return")).
      thenReturn("false");
    Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).
      thenReturn(DummyAuthenticationHandler.class.getName());
    Mockito.when(config.getInitParameterNames()).thenReturn(
      new Vector<String>(
        Arrays.asList(AuthenticationFilter.AUTH_TYPE,
                      "management.operation.return")).elements());
    filter.init(config);

    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    Mockito.when(request.getRequestURL()).
      thenReturn(new StringBuffer("http://foo:8080/bar"));

    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

    FilterChain chain = Mockito.mock(FilterChain.class);

    filter.doFilter(request, response, chain);
    Mockito.verify(response).setStatus(HttpServletResponse.SC_ACCEPTED);
    Mockito.verifyNoMoreInteractions(response);

    Mockito.reset(request);
    Mockito.reset(response);

    AuthenticationToken token = new AuthenticationToken("u", "p", "t");
    token.setExpires(System.currentTimeMillis() + 1000);
    Signer signer = new Signer("secret".getBytes());
    String tokenSigned = signer.sign(token.toString());
    Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned);
    Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie});

    filter.doFilter(request, response, chain);

    Mockito.verify(response).setStatus(HttpServletResponse.SC_ACCEPTED);
    Mockito.verifyNoMoreInteractions(response);

  } finally {
    filter.destroy();
  }
}
 
Example 36
Project: multilane   File: TestServer.java View source code 6 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest req, HttpServletResponse res) {
    try {
        String uri = req.getRequestURI();
        if (uri.equals("/204")) {
            res.setStatus(HttpServletResponse.SC_NO_CONTENT);
            res.getWriter().print("");
        } else if (uri.equals("/302")) {
            res.setStatus(HttpServletResponse.SC_FOUND);
            res.setHeader("Location", "/?v=redirected");
            res.getWriter().print("not redirected");
        } else if (uri.equals("/404")) {
            res.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (uri.equals("/500")) {
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } else {
            // blocking simulation
            if (uri.equals("/500ms")) {
                Thread.sleep(500L);
            } else if (uri.equals("/1s")) {
                Thread.sleep(1000L);
            } else if (uri.equals("/2s")) {
                Thread.sleep(2000L);
            } else if (uri.equals("/3s")) {
                Thread.sleep(3000L);
            } else {
                Thread.sleep(100L);
            }
            String v = req.getParameter("v");
            String charset = req.getParameter("charset");

            res.setStatus(HttpServletResponse.SC_OK);
            res.setContentType("text/plain");

            if (charset != null) {
                res.setCharacterEncoding(charset);
            }

            if (v != null) {
                String body = new String(v.getBytes(res.getCharacterEncoding()), res.getCharacterEncoding());
                res.getWriter().print(body);
            } else {
                res.getWriter().print("Nothing");
            }
        }
        baseRequest.setHandled(true);
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}
 
Example 37
Project: rewrite   File: ProxyServlet.java View source code 6 votes vote down vote up
protected boolean doResponseRedirectOrNotModifiedLogic(
         HttpServletRequest servletRequest, HttpServletResponse servletResponse,
         HttpResponse proxyResponse, int statusCode)
         throws ServletException, IOException
{
   /*
    * Check if the proxy response is a redirect. The following code is adapted from
    * org.tigris.noodle.filters.CheckForRedirect
    */
   if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */)
   {
      Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION);
      if (locationHeader == null)
      {
         throw new ServletException("Received status code: " + statusCode
                  + " but no " + HttpHeaders.LOCATION + " header was found in the response");
      }
      /*
       * Modify the redirect to go to this proxy servlet rather that the proxied host
       */
      String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue());

      servletResponse.sendRedirect(locStr);
      return true;
   }
   /*
    * 304 needs special handling. See: http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 . We get a 304
    * whenever passed an 'If-Modified-Since' header and the data on disk has not changed; server responds w/ a 304
    * saying I'm not going to send the body because the file has not changed.
    */
   if (statusCode == HttpServletResponse.SC_NOT_MODIFIED)
   {
      servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
      servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
      return true;
   }
   return false;
}
 
Example 38
Project: abiquo   File: VersionCheckerFilter.java View source code 6 votes vote down vote up
public UnsupportedVersionInHeaderException(final String header)
{
    if (header.equals(HttpHeaders.ACCEPT))
    {
        errorStatus = HttpServletResponse.SC_NOT_ACCEPTABLE;
        errorDetails = APIError.STATUS_NOT_ACCEPTABLE_VERSION;
    }
    else if (header.equals(HttpHeaders.CONTENT_TYPE))
    {
        errorStatus = HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE;
        errorDetails = APIError.STATUS_UNSUPPORTED_MEDIA_TYPE_VERSION;
    }
    else
    {
        throw new IllegalArgumentException("Unsupported header: " + header);
    }
}
 
Example 39
Project: OpenClinica   File: LocaleFilter.java View source code 6 votes vote down vote up
private void updateLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    if(locale != null) {
        HttpSession session = request.getSession(false);
        if(session != null) {
            session.setAttribute(LocaleResolver.getLocaleSessionAttributeName(), locale);
            Config.set(session, Config.FMT_LOCALE, locale);
            if(response != null)    response.setLocale(locale);
        } else {
            logger.debug("Locale can not be saved into session because session is null.");
        }
    } else {
        logger.debug("No Locale updating has been done because passed Locale is null.");
    }
}
 
Example 40
Project: cms-ce   File: HttpServletRangeUtil.java View source code 6 votes vote down vote up
/**
 * Check <code>If-Match</code> header contains "*" or ETag.
 *
 * @param request HttpServletRequest
 * @param eTag    ETag issue
 * @return success code (0), otherwise <code>412</code> indicating that the precondition given in one or more of the request-header fields evaluated to false when it was tested on the server
 */
private static int checkIfMatch( final HttpServletRequest request, final String eTag )
{
    final String ifMatch = request.getHeader( HttpHeaders.IF_MATCH );

    return ( ifMatch != null && !HttpServletUtil.checkHeaderContainsETag( ifMatch, eTag ) )
        ? HttpServletResponse.SC_PRECONDITION_FAILED
        : 0;
}
 
Example 41
Project: appengine-java-vm-runtime   File: VmRuntimeJettyKitchenSinkTest.java View source code 6 votes vote down vote up
public void testShutDown() throws Exception {

    int code = fetchResponseCode(createUrl("/_ah/health"));
    assertEquals(HttpServletResponse.SC_OK, code);

    // Send a request to /_ah/stop to trigger lameduck.
    String[] lines = fetchUrl(createUrl("/_ah/stop"));
    assertEquals(1, lines.length);
    assertEquals("ok", lines[0].trim());

    code = fetchResponseCode(createUrl("/_ah/health"));
    assertEquals(HttpServletResponse.SC_BAD_GATEWAY, code);
  }
 
Example 42
Project: cms-ce   File: HttpServletRangeUtilTest.java View source code 6 votes vote down vote up
@Test
public void test_bad_symbols_in_range()
    throws Exception
{
    final MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
    httpServletRequest.setMethod( "GET" );
    httpServletRequest.setPathInfo( "/input.dat" );
    httpServletRequest.addHeader( HttpHeaders.RANGE, "bytes=bad" );

    final MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
    HttpServletRangeUtil.processRequest( httpServletRequest, mockHttpServletResponse, "input.dat", "application/pdf", INPUT_FILE,
                                         false );

    assertEquals( "", mockHttpServletResponse.getContentAsString() );

    assertEquals( HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE, mockHttpServletResponse.getStatus() );
}
 
Example 43
Project: cms-ce   File: HttpServletRangeUtilTest.java View source code 6 votes vote down vote up
@Test
public void test_process_request_multipart_zero_to_zero()
    throws Exception
{
    final MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
    httpServletRequest.setMethod( "GET" );
    httpServletRequest.setPathInfo( "/input.dat" );
    httpServletRequest.addHeader( HttpHeaders.RANGE, "bytes=0-0,-1" );

    final MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
    HttpServletRangeUtil.processRequest( httpServletRequest, mockHttpServletResponse, "input.dat", "application/pdf", INPUT_FILE,
                                         false );

    assertEquals( readFromFile( "response1.dat" ), mockHttpServletResponse.getContentAsString() );

    assertEquals( HttpServletResponse.SC_PARTIAL_CONTENT, mockHttpServletResponse.getStatus() );
    assertEquals( "multipart/byteranges; boundary=THIS_STRING_SEPARATES", mockHttpServletResponse.getContentType() );
    assertEquals( "attachment;filename=\"input.dat\"", mockHttpServletResponse.getHeader( HttpHeaders.CONTENT_DISPOSITION ) );

}
 
Example 44
Project: cpf   File: SimpleContentGenerator.java View source code 6 votes vote down vote up
private void handleError(final String methodName, Throwable e) throws IOException {

      logger.error(methodName + ": " + e.getMessage(), e);

      String msg = e.getLocalizedMessage();
      if (e instanceof QueryTimeoutException ||
          e instanceof TimeoutException) 
//          ||
//          (e instanceof RuntimeException &&
//              StringUtils.containsIgnoreCase(e.getClass().getName(), "timeout"))) 
      {
        getResponse().sendError(HttpServletResponse.SC_REQUEST_TIMEOUT, msg);
      }
      else {// default to 500
        getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
      }
    }
 
Example 45
Project: airlift   File: TestHttpServerProvider.java View source code 6 votes vote down vote up
@Test
public void testFilter()
        throws Exception
{
    createServer();
    server.start();

    try (JettyHttpClient client = new JettyHttpClient()) {
        StatusResponse response = client.execute(prepareGet().setUri(httpServerInfo.getHttpUri().resolve("/filter")).build(), createStatusResponseHandler());

        assertEquals(response.getStatusCode(), HttpServletResponse.SC_PAYMENT_REQUIRED);
        assertEquals(response.getStatusMessage(), "filtered");
    }
}
 
Example 46
Project: kurento-java   File: RepositoryHttpServlet.java View source code 6 votes vote down vote up
private void logResponse(HttpServletResponse resp) {

		Collection<String> headerNames = resp.getHeaderNames();
		for (String headerName : headerNames) {
			Collection<String> values = resp.getHeaders(headerName);
			log.info("  Header {}: {}", headerName, values);
		}
	}
 
Example 47
Project: compose-idm   File: SimpleCORSFilter.java View source code 6 votes vote down vote up
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
	HttpServletResponse response = (HttpServletResponse) res;
	if(response.getHeader("Access-Control-Allow-Origin")==null)
		response.setHeader("Access-Control-Allow-Origin", "*");
	response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
	response.setHeader("Access-Control-Max-Age", "3600");
	response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
	chain.doFilter(req, res);
}
 
Example 48
Project: aipo   File: NTLMSessionValidator.java View source code 5 votes vote down vote up
/**
 * Extracts user name from http headers
 * 
 * @param data
 * @return
 * @exception Exception
 */
private String getRemoteUser(RunData data) throws Exception {
  HttpServletRequest request = data.getRequest();
  HttpServletResponse response = data.getResponse();

  if (data.getUser().hasLoggedIn()
    && request.getMethod().equalsIgnoreCase("get")) {
    return data.getUser().getUserName();
  }

  String auth = request.getHeader("Authorization");
  if (auth == null) {
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.setHeader("WWW-Authenticate", "NTLM");
    response.flushBuffer();

    return null;
  }
  if (auth.startsWith("NTLM ")) {

    byte[] msg = Base64.decodeBase64(auth.substring(5).getBytes());
    int off = 0, length, offset;

    if (msg[8] == 1) {
      response.setHeader("WWW-Authenticate", encodedMsg1);
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

      return null;
    } else if (msg[8] == 3) {
      if (data.getUser().hasLoggedIn()) {
        return data.getUser().getUserName();
      }

      off = 30;

      // length = msg[off + 17] * 256 + msg[off + 16];
      // offset = msg[off + 19] * 256 + msg[off + 18];
      // String remoteHost = new String(msg, offset, length);

      // length = msg[off + 1] * 256 + msg[off];
      // offset = msg[off + 3] * 256 + msg[off + 2];
      // String domain = new String(msg, offset, length);

      length = msg[off + 9] * 256 + msg[off + 8];
      offset = msg[off + 11] * 256 + msg[off + 10];
      String username = new String(msg, offset, length);

      return username;
    }

  }

  return null;
}
 
Example 49
Project: jentrata-msh   File: HttpDispatcher.java View source code 5 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.
 */
protected void processRequest(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    dispatcherContext.acquire();

    try {
        /*
         * Generate an HTTP request event and look for its listener
         */
        String pathInfo = dispatcherContext.getPathInfo(request);
        HttpRequestEvent event = new HttpRequestEvent(pathInfo, request, response);
        HttpRequestListener listener = dispatcherContext.getListener(pathInfo);

        /*
         * Send an HTTP NOT FOUND error if no listener found for the event.
         */
        if (listener == null) {
            Sys.main.log.debug(event + " has no listener.");
            response.sendError(HttpURLConnection.HTTP_NOT_FOUND, pathInfo);
            return;
        }
        /*
         * Process the event if there is a corresponding listener.
         */
        else {
            String path = null;
            try {
                setDefaults(request, response);

                /*
                 * Fire a request accepted event and invokes the listener to
                 * process it if it should be accepted.
                 */
                if (fireRequestAcceptedEvent(event)) {
                    Sys.main.log.debug(event + " is being processed by "
                            + listener);

                    /*
                     * Process the request and time it.
                     */
                    long start = new Date().getTime();
                    if (listener.doStartRequest(request, response)) {
                        path = listener.processRequest(request, response);
                        listener.doEndRequest(request, response);
                    }
                    long end = new Date().getTime();

                    Sys.main.log.debug(event
                            + " had been processed successfully for "
                            + (end - start) + " ms");

                    fireRequestProcessedEvent(event);
                }
                /*
                 * Send an HTTP BAD REQUEST error if the request has been
                 * rejected.
                 */
                else {
                    Sys.main.log.debug(event + " is rejected.");
                    if (!response.isCommitted()) {
                        response.sendError(
                                HttpURLConnection.HTTP_BAD_REQUEST,
                                pathInfo);
                    }
                    return;
                }
            }
            /*
             * Send an HTTP INTERNAL ERROR error if there is any unhandled
             * or unexpected server error.
             */
            catch (Throwable e) {
                Sys.main.log.error("Error in processing HTTP request", e);
                String errMsg = (e instanceof RequestListenerException ? e
                        .getMessage() : e.getClass().getName() + ": "
                        + e.getMessage());
                response.sendError(HttpURLConnection.HTTP_INTERNAL_ERROR,
                        errMsg);
                return;
            }

            /*
             * Forward the request to the path, if any, returned by the
             * listener after processing the request.
             */
            if (path != null) {
                if (path.startsWith("&")) {
                    String returnCode = path.substring(1);
                    Properties params = listener.getParameters();
                    path = params == null? null : params.getProperty(
                            "return-code:" + returnCode);
                    if (path == null) {
                        return;
                    }
                }

                Sys.main.log.debug(event + " is being forwarded to '" + path + "'");

                RequestDispatcher dispatcher = getServletContext()
                        .getRequestDispatcher(path);
                dispatcher.forward(request, response);
            }
        }
    }
    finally {
        dispatcherContext.release();
    }
}