Example usage for javax.servlet.http HttpServletResponse addHeader

List of usage examples for javax.servlet.http HttpServletResponse addHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse addHeader.

Prototype

public void addHeader(String name, String value);

Source Link

Document

Adds a response header with the given name and value.

Usage

From source file:edu.umn.cs.spatialHadoop.visualization.HadoopvizServer.java

/**
 * The handler for all requests./*from   w w w . j  a  v a 2s  .  c o  m*/
 */
@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
        throws IOException, ServletException {
    // Bypass cross-site scripting (XSS)
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Credentials", "true");
    ((Request) request).setHandled(true);

    try {
        LOG.info("Received request: '" + request.getRequestURL() + "'");
        if (target.endsWith("/generate_dataset.cgi")) {
            handleGenerateDataset(request, response);
        } else if (target.endsWith("/visualize.cgi")) {
            handlePlot(request, response);
        } else if (target.endsWith("/generate_output_list.cgi")) {
            handleGenerateOutputList(request, response);
        } else if (target.endsWith("/fetch_result.cgi")) {
            handleOutput(request, response);
        } else if (target.startsWith("/hdfs/")) {
            handleHDFSFetch(request, response);
        } else if (target.endsWith("/get_output_info.cgi")) {
            handleOutputInfo(request, response);
        } else {
            if (target.equals("/"))
                target = "/index.html";
            tryToLoadStaticResource(target, response);
        }
    } catch (Exception e) {
        e.printStackTrace();
        reportError(response, "Error placing the request", e);
    }
}

From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.BaseRestController.java

/**
 * @should return unauthorized if not logged in
 * @should return forbidden if logged in
 *//*from   ww  w.  j a v a2  s . co m*/
@ExceptionHandler(APIAuthenticationException.class)
@ResponseBody
public SimpleObject apiAuthenticationExceptionHandler(Exception ex, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    int errorCode;
    String errorDetail;
    if (Context.isAuthenticated()) {
        // user is logged in but doesn't have the relevant privilege -> 403 FORBIDDEN
        errorCode = HttpServletResponse.SC_FORBIDDEN;
        errorDetail = "User is logged in but doesn't have the relevant privilege";
    } else {
        // user is not logged in -> 401 UNAUTHORIZED
        errorCode = HttpServletResponse.SC_UNAUTHORIZED;
        errorDetail = "User is not logged in";
        if (shouldAddWWWAuthHeader(request)) {
            response.addHeader("WWW-Authenticate",
                    "Basic realm=\"OpenMRS at " + RestConstants.URI_PREFIX + "\"");
        }
    }
    response.setStatus(errorCode);
    return RestUtil.wrapErrorResponse(ex, errorDetail);
}

From source file:org.energyos.espi.datacustodian.web.api.BatchRESTController.java

/**
 * Produce a Subscription for the requester. The resultant response will
 * contain a <feed> of the Usage Point(s) associated with the subscription.
 * /*from   w w  w .  j  a va  2 s.co m*/
 * Requires Authorization: Bearer [{data_custodian_access_token} |
 * {access_token}]
 * 
 * @param response
 *            HTTP Servlet Response
 * @param subscriptionId
 *            Long identifying the Subscription.id of the desired
 *            Authorization
 * @param usagePointId
 *            Long identifying the UsagePoint.id of the desired
 *            Authorization
 * @param params
 *            HTTP Query Parameters
 * @throws IOException
 * @throws FeedException
 * 
 * @usage GET /espi/1_1/resource/Batch/Subscription/{subscriptionId}
 */

@Transactional(readOnly = true)
@RequestMapping(value = Routes.BATCH_SUBSCRIPTION_USAGEPOINT_MEMBER, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody
public void subscriptionUsagePointMember(HttpServletResponse response, @PathVariable Long subscriptionId,
        @PathVariable Long usagePointId, @RequestParam Map<String, String> params)
        throws IOException, FeedException {

    response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
    response.addHeader("Content-Disposition", "attachment; filename=GreenButtonDownload.xml");
    try {
        exportService.exportBatchSubscriptionUsagePoint(subscriptionId, usagePointId,
                response.getOutputStream(), new ExportFilter(params));

    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

}

From source file:org.energyos.espi.datacustodian.web.api.BatchRESTController.java

/**
 * Supports Green Button Download My Data A DMD file for a particular Usage
 * Point will be produced and returned to the Retail Customer
 * //ww w  . ja v  a  2s  .  c  o  m
 * Requires Authorization: Bearer [{data_custodian_access_token} |
 * {upload_access_token}]
 * 
 * @param response
 *            HTTP Servlet Response
 * @param retailCustomerId
 *            The locally unique identifier of a Retail Customer - NOTE PII
 * @param usagePointId
 *            The locally unique identifier of a UsagePoint.id
 * @param params
 *            params HTTP Query Parameters
 * @throws IOException
 * @throws FeedException
 * 
 * @usage GET
 *        /espi/1_1/resource/Batch/RetailCustomer/{retailCustomerId}/UsagePoint
 *        /{usagePointId}
 */
@RequestMapping(value = Routes.BATCH_DOWNLOAD_MY_DATA_MEMBER, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody
public void download_member(HttpServletResponse response, @PathVariable Long retailCustomerId,
        @PathVariable Long usagePointId, @RequestParam Map<String, String> params)
        throws IOException, FeedException {

    response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
    response.addHeader("Content-Disposition", "attachment; filename=GreenButtonDownload.xml");
    try {

        exportService.exportUsagePointFull(0L, retailCustomerId, usagePointId, response.getOutputStream(),
                new ExportFilter(params));

    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

}

From source file:org.opendatakit.aggregate.servlet.GetGrantedRolesServlet.java

/**
 * Handler for HTTP Get request that returns the list of roles assigned to this user.
 * //from  ww w . ja v  a 2 s . c o  m
 * Assumed to return a entity body that is a JSON serialization of a list.
 *
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    CallingContext cc = ContextFactory.getCallingContext(this, req);

    Set<GrantedAuthority> grants = cc.getCurrentUser().getDirectAuthorities();
    RoleHierarchy rh = (RoleHierarchy) cc.getBean(SecurityBeanDefs.ROLE_HIERARCHY_MANAGER);
    Collection<? extends GrantedAuthority> roles = rh.getReachableGrantedAuthorities(grants);
    ArrayList<String> roleNames = new ArrayList<String>();
    for (GrantedAuthority a : roles) {
        if (a.getAuthority().startsWith(GrantedAuthorityName.ROLE_PREFIX)) {
            roleNames.add(a.getAuthority());
        }
    }

    resp.addHeader(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION);
    resp.addHeader("Access-Control-Allow-Origin", "*");
    resp.addHeader("Access-Control-Allow-Credentials", "true");
    resp.addHeader(HttpHeaders.HOST, cc.getServerURL());
    resp.setContentType(HtmlConsts.RESP_TYPE_JSON);
    resp.setCharacterEncoding(HtmlConsts.UTF8_ENCODE);

    PrintWriter out = resp.getWriter();
    out.write(mapper.writeValueAsString(roleNames));
    out.flush();

    resp.setStatus(HttpStatus.SC_OK);
}

From source file:com.google.cloud.examples.coinflow.frontend.CoinflowServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    LOG.info("In CoinflowServlet doGet");

    if (req.getRequestURI().equals("/favicon.ico"))
        return;//from  w w w  .  j ava 2  s . c o  m

    try (Table t = BigtableHelper.getConnection().getTable(TABLE)) {

        DateTime dateTime = new DateTime().minusHours(4);
        long before_ts = dateTime.getMillis();
        long now_ts = new DateTime().getMillis();

        String beforeRowKey = "match_" + before_ts;
        String afterRowKey = "match_" + now_ts;

        Scan scan = new Scan(beforeRowKey.getBytes(), afterRowKey.getBytes());
        ResultScanner rs = t.getScanner(scan);
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.setContentType("text/plain");

        List<PriceTimestamp> prices = new ArrayList<>();
        for (Result r : rs) {
            String data = new String(r.getValue(Schema.CF.getBytes(), Schema.QUALIFIER.getBytes()));
            CoinbaseData coinData = objectMapper.readValue(data, CoinbaseData.class);
            PriceTimestamp priceTimestamp = new PriceTimestamp(Float.parseFloat(coinData.getPrice()),
                    DateHelpers.convertDateToTime(coinData.getTime()));
            prices.add(priceTimestamp);
        }
        String pricesStr = objectMapper.writeValueAsString(prices);
        resp.getWriter().println(pricesStr);
    }

}

From source file:eu.freme.broker.security.AuthenticationFilter.java

private void processUsernamePasswordAuthentication(HttpServletResponse httpResponse, Optional<String> username,
        Optional<String> password) throws IOException {
    Authentication resultOfAuthentication = tryToAuthenticateWithUsernameAndPassword(username, password);
    SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication);
    httpResponse.setStatus(HttpServletResponse.SC_OK);
    Token token = (Token) resultOfAuthentication.getDetails();
    TokenResponse tokenResponse = new TokenResponse(token.getToken());
    String tokenJsonResponse = new ObjectMapper().writeValueAsString(tokenResponse);
    httpResponse.addHeader("Content-Type", "application/json");
    httpResponse.getWriter().print(tokenJsonResponse);
}

From source file:at.gv.egovernment.moa.id.auth.servlet.VerifyAuthenticationBlockServlet.java

/**
 * GET requested by security layer implementation to verify
 * that data URL resource is available.//w w w.  j  a  v  a  2 s .  co  m
 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse)
 */
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    //doPost(req, resp);

    Logger.debug("GET VerifyAuthenticationBlock");

    resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES);
    resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA);
    resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL);
    resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE);

}

From source file:de.iteratec.iteraplan.presentation.responsegenerators.GraphicsResponseGenerator.java

private void prepareResponse(HttpServletResponse response, GraphicalReport reportType, Content content,
        long fileLength) {
    response.setContentType(getContentType());
    response.setHeader("Content-disposition", getContentDisposition(reportType, content));

    // ITERAPLAN-1732: add the length of the file to the header of the response to make IE happy
    response.addHeader("Content-Length", Long.toString(fileLength));
}