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:com.netflix.conductor.server.JerseyModule.java

@Provides
@Singleton/*from   w  ww.j  av a  2  s . c  om*/
public Filter apiOriginFilter() {
    return new Filter() {

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            HttpServletResponse res = (HttpServletResponse) response;
            if (!res.containsHeader("Access-Control-Allow-Origin")) {
                res.setHeader("Access-Control-Allow-Origin", "*");
            }
            res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
            res.addHeader("Access-Control-Allow-Headers", "Content-Type, api_key, Authorization");

            chain.doFilter(request, response);
        }

        @Override
        public void destroy() {
        }

    };
}

From source file:gov.nih.nci.caarray.web.filter.CacheControlFilter.java

/**
 * {@inheritDoc}/* www . j a v  a2 s . co m*/
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (!(response instanceof HttpServletResponse)) {
        chain.doFilter(request, response);
        return;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    if (StringUtils.substringAfterLast(httpRequest.getRequestURI(), ".").equals(DYNAMIC_URL_EXTENSION)) {
        if (!request.isSecure()) { // workaround for IE files bug http://support.microsoft.com/kb/812935
            httpResponse.addHeader("Cache-control", "no-cache");
            httpResponse.addHeader("Pragma", "no-cache");
        }
        httpResponse.addIntHeader("Expires", 0);
    }
    chain.doFilter(request, response);
}

From source file:net.yacy.http.ProxyHandler.java

private void convertHeaderToJetty(HttpResponse in, HttpServletResponse out) {
    for (Header h : in.getAllHeaders()) {
        out.addHeader(h.getName(), h.getValue());
    }// w w w .  j a v  a  2s . co  m
}

From source file:com.googlecode.jsonplugin.JSONUtil.java

public static void writeJSONToResponse(SerializationParams serializationParams) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    if (TextUtils.stringSet(serializationParams.getSerializedJSON()))
        stringBuilder.append(serializationParams.getSerializedJSON());

    if (TextUtils.stringSet(serializationParams.getWrapPrefix()))
        stringBuilder.insert(0, serializationParams.getWrapPrefix());
    else if (serializationParams.isWrapWithComments()) {
        stringBuilder.insert(0, "/* ");
        stringBuilder.append(" */");
    } else if (serializationParams.isPrefix())
        stringBuilder.insert(0, "{}&& ");

    if (TextUtils.stringSet(serializationParams.getWrapSuffix()))
        stringBuilder.append(serializationParams.getWrapSuffix());

    String json = stringBuilder.toString();

    if (log.isDebugEnabled()) {
        log.debug("[JSON]" + json);
    }/*  w  w  w  .  ja  va 2s.  c  o m*/

    HttpServletResponse response = serializationParams.getResponse();

    //status or error code
    if (serializationParams.getStatusCode() > 0)
        response.setStatus(serializationParams.getStatusCode());
    else if (serializationParams.getErrorCode() > 0)
        response.sendError(serializationParams.getErrorCode());

    //content type
    if (serializationParams.isSmd())
        response.setContentType("application/json-rpc;charset=" + serializationParams.getEncoding());
    else
        response.setContentType(
                serializationParams.getContentType() + ";charset=" + serializationParams.getEncoding());

    if (serializationParams.isNoCache()) {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "0");
        response.setHeader("Pragma", "No-cache");
    }

    if (serializationParams.isGzip()) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        InputStream in = null;
        try {
            out = new GZIPOutputStream(response.getOutputStream());
            in = new ByteArrayInputStream(json.getBytes());
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            if (in != null)
                in.close();
            if (out != null) {
                out.finish();
                out.close();
            }
        }

    } else {
        response.setContentLength(json.getBytes(serializationParams.getEncoding()).length);
        PrintWriter out = response.getWriter();
        out.print(json);
    }
}

From source file:org.energyos.espi.thirdparty.web.BatchRESTController.java

@RequestMapping(value = Routes.BATCH_DOWNLOAD_MY_DATA_COLLECTION, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody/* w w w  .j av a 2s.  c  om*/
public void download_collection(HttpServletResponse response, @PathVariable Long retailCustomerId,
        @RequestParam Map<String, String> params) throws IOException, FeedException {

    response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
    response.addHeader("Content-Disposition", "attachment; filename=GreenButtonDownload.xml");
    try {
        // TODO -- need authorization hook
        exportService.exportUsagePointsFull(0L, retailCustomerId, response.getOutputStream(),
                new ExportFilter(params));

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

}

From source file:application.controllers.admin.EditEmotion.java

/**
 * lay du lieu truc tiep tu views list emotions de hien thi
 *
 * @param request//from   w  w w.  j  a  v a2 s .com
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    response.addHeader("Content-Type", "text/html");
    View layout = new View("Index.xtm");
    View view = new View("admin", "EditEmotion.xtm");

    TemplateDataDictionary listEmotionView = view.addSection("listEmotion");
    //get list emotion in group
    String groupId = request.getParameter("groupId");
    List<EmotionPOJO> listEmotionInGroup = (List<EmotionPOJO>) Memcached.get("listEmotionInGroup" + groupId);
    List<GroupEmotionPOJO> listGroupEmotion = (List<GroupEmotionPOJO>) Memcached.get("listGroupEmotion");

    //get id from href location 
    int indexEmotionSelected = Integer.parseInt(request.getParameter("id"));
    emotionSelected = listEmotionInGroup.get(indexEmotionSelected);
    //show image khong co trong database de add
    TemplateDataDictionary emotionItem = listEmotionView.addSection("emotionItem");
    emotionItem.setVariable("imageId", Integer.toString(1));
    emotionItem.setVariable("imageLink", listEmotionInGroup.get(indexEmotionSelected).linkImage);
    emotionItem.setVariable("descriptionEmotion", listEmotionInGroup.get(indexEmotionSelected).description);
    for (int i = 0; i < listGroupEmotion.size(); i++) {
        TemplateDataDictionary emotionSelect = emotionItem.addSection("emotionSelect");
        emotionSelect.setVariable("groupEmotionId", Integer.toString(listGroupEmotion.get(i).id));
        emotionSelect.setVariable("groupEmotionName", listGroupEmotion.get(i).name);

    }
    //Tao view
    String content = view.render();
    layout.setVariable("content", content);
    //Tao view
    String resourceHost = "";
    resourceHost += Registry.get("Host");
    resourceHost = resourceHost + "/resources";
    layout.setVariable("hostResource", resourceHost);
    String mainView = layout.render();
    response.getWriter().write(mainView);

}

From source file:agk.chatbot.web.MainServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/* w  w  w.  j  a va 2 s.  c o m*/
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    int status = 200;
    String result = "";
    JSONObject json = new JSONObject();
    response.addHeader("Content-Type", "application/json");

    if (initialised) {
        if (request.getHeader("Content-Type").startsWith("application/x-www-form-urlencoded")) {
            String chat = request.getParameter("c");
            if (chat.length() == 0 || chat.length() > 140) {
                status = 400;
                result = "Bad request. Invalid chat message.";
            } else {
                try {
                    CBRQuery query = bot.strToQuery(chat);
                    bot.cycle(query);
                    ChatResponse resp = bot.getLastResponse();
                    status = 200;
                    result = resp.getText().toString();
                } catch (ExecutionException e) {
                    status = 500;
                    result = "An error occurred.";
                    e.printStackTrace();
                }
            }
        } else {
            status = 400;
            result = "Bad request. Requires Content-Type: application/x-www-form-urlencoded";
        }
    } else {
        status = 503;
        result = "Bot is still initialising.";
    }

    try {
        json.put("status", 400);
        json.put("result", result);
    } catch (JSONException e) {
        status = 500;
        e.printStackTrace();
    }
    response.setStatus(status);
    response.getWriter().print(json.toString());
}

From source file:com.sammyun.controller.console.CommonController.java

/**
 * ??/* www .j a  v  a  2  s.com*/
 */
@RequestMapping("/unauthorized")
public String unauthorized(HttpServletRequest request, HttpServletResponse response) {
    String requestType = request.getHeader("X-Requested-With");
    if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
        response.addHeader("loginStatus", "unauthorized");
        try {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    return "/console/common/unauthorized";
}

From source file:org.atlasapi.application.SourceRequestsController.java

@RequestMapping(value = "/4/sources/{sid}/requests", method = RequestMethod.POST)
public void storeSourceRequest(HttpServletRequest request, HttpServletResponse response,
        @PathVariable String sid, @RequestParam String appId, @RequestParam String appUrl,
        @RequestParam String reason, @RequestParam String usageType, @RequestParam String licenseAccepted)
        throws IOException {

    response.addHeader("Access-Control-Allow-Origin", "*");
    try {//  w  ww . j av a2 s  .  co  m
        Optional<Publisher> source = sourceIdCodec.decode(sid);
        if (!source.isPresent()) {
            throw new NotFoundException(null);
        }
        Id applicationId = Id.valueOf(idCodec.decode(appId));
        UsageType usageTypeRequested = UsageType.valueOf(usageType.toUpperCase());
        User user = userFetcher.userFor(request).get();
        sourceRequestManager.createOrUpdateRequest(source.get(), usageTypeRequested, applicationId, appUrl,
                user.getEmail(), reason, Boolean.valueOf(licenseAccepted));
    } catch (Exception e) {
        ErrorSummary summary = ErrorSummary.forException(e);
        new ErrorResultWriter().write(summary, null, request, response);
    }
}

From source file:ca.uhn.fhir.rest.server.servlet.ServletRestfulResponse.java

@Override
public Writer getResponseWriter(int theStatusCode, String theStatusMessage, String theContentType,
        String theCharset, boolean theRespondGzip) throws UnsupportedEncodingException, IOException {
    addHeaders();/*from  ww  w .j a v a 2s .  com*/
    HttpServletResponse theHttpResponse = getRequestDetails().getServletResponse();
    theHttpResponse.setCharacterEncoding(theCharset);
    theHttpResponse.setStatus(theStatusCode);
    theHttpResponse.setContentType(theContentType);
    if (theRespondGzip) {
        theHttpResponse.addHeader(Constants.HEADER_CONTENT_ENCODING, Constants.ENCODING_GZIP);
        return new OutputStreamWriter(new GZIPOutputStream(theHttpResponse.getOutputStream()),
                Constants.CHARSET_NAME_UTF8);
    } else {
        return theHttpResponse.getWriter();
    }
}