Example usage for javax.servlet.http HttpServletResponse SC_NO_CONTENT

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

Introduction

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

Prototype

int SC_NO_CONTENT

To view the source code for javax.servlet.http HttpServletResponse SC_NO_CONTENT.

Click Source Link

Document

Status code (204) indicating that the request succeeded but that there was no new information to return.

Usage

From source file:org.codelibs.fess.web.IndexAction.java

@Execute(validator = true, input = "index")
public String go() throws IOException {
    Map<String, Object> doc = null;
    try {// w w w . j a v a  2s. c  o m
        doc = searchService.getDocument(fieldHelper.docIdField + ":" + indexForm.docId,
                queryHelper.getResponseFields(), new String[] { fieldHelper.clickCountField });
    } catch (final Exception e) {
        logger.warn("Failed to request: " + indexForm.docId, e);
    }
    if (doc == null) {
        errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                "errors.docid_not_found", indexForm.docId);
        return "error.jsp";
    }
    final Object urlObj = doc.get(fieldHelper.urlField);
    if (urlObj == null) {
        errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                "errors.document_not_found", indexForm.docId);
        return "error.jsp";
    }
    final String url = urlObj.toString();

    if (Constants.TRUE.equals(crawlerProperties.getProperty(Constants.SEARCH_LOG_PROPERTY, Constants.TRUE))) {
        final String userSessionId = userInfoHelper.getUserCode();
        if (userSessionId != null) {
            final SearchLogHelper searchLogHelper = ComponentUtil.getSearchLogHelper();
            final ClickLog clickLog = new ClickLog();
            clickLog.setUrl(url);
            LocalDateTime now = systemHelper.getCurrentTime();
            clickLog.setRequestedTime(now);
            clickLog.setQueryRequestedTime(LocalDateTime
                    .ofInstant(Instant.ofEpochMilli(Long.parseLong(indexForm.rt)), ZoneId.systemDefault()));
            clickLog.setUserSessionId(userSessionId);
            clickLog.setDocId(indexForm.docId);
            long clickCount = 0;
            final Object count = doc.get(fieldHelper.clickCountField);
            if (count instanceof Long) {
                clickCount = ((Long) count).longValue();
            }
            clickLog.setClickCount(clickCount);
            searchLogHelper.addClickLog(clickLog);
        }
    }

    String hash;
    if (StringUtil.isNotBlank(indexForm.hash)) {
        final String value = URLUtil.decode(indexForm.hash, Constants.UTF_8);
        final StringBuilder buf = new StringBuilder(value.length() + 100);
        for (final char c : value.toCharArray()) {
            if (CharUtil.isUrlChar(c) || c == ' ') {
                buf.append(c);
            } else {
                try {
                    buf.append(URLEncoder.encode(String.valueOf(c), Constants.UTF_8));
                } catch (final UnsupportedEncodingException e) {
                    // NOP
                }
            }
        }
        hash = buf.toString();
    } else {
        hash = StringUtil.EMPTY;
    }

    if (isFileSystemPath(url)) {
        if (Constants.TRUE
                .equals(crawlerProperties.getProperty(Constants.SEARCH_FILE_PROXY_PROPERTY, Constants.TRUE))) {
            final CrawlingConfigHelper crawlingConfigHelper = ComponentUtil.getCrawlingConfigHelper();
            try {
                crawlingConfigHelper.writeContent(doc);
                return null;
            } catch (final Exception e) {
                logger.error("Failed to load: " + doc, e);
                errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                        "errors.not_load_from_server", url);
                return "error.jsp";
            }
        } else if (Constants.TRUE
                .equals(crawlerProperties.getProperty(Constants.SEARCH_DESKTOP_PROPERTY, Constants.FALSE))) {
            final String path = url.replaceFirst("file:/+", "//");
            final File file = new File(path);
            if (!file.exists()) {
                errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                        "errors.not_found_on_file_system", url);
                return "error.jsp";
            }
            final Desktop desktop = Desktop.getDesktop();
            try {
                desktop.open(file);
            } catch (final Exception e) {
                errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                        "errors.could_not_open_on_system", url);
                logger.warn("Could not open " + path, e);
                return "error.jsp";
            }

            ResponseUtil.getResponse().setStatus(HttpServletResponse.SC_NO_CONTENT);
            return null;
        } else {
            ResponseUtil.getResponse().sendRedirect(url + hash);
        }
    } else {
        ResponseUtil.getResponse().sendRedirect(url + hash);
    }
    return null;
}

From source file:com.imaginary.home.device.hue.HueMethod.java

public JSONObject put(@Nonnull String resource, JSONObject body) throws HueException {
    Logger std = Hue.getLogger(HueMethod.class);
    Logger wire = Hue.getWireLogger(HueMethod.class);

    if (std.isTraceEnabled()) {
        std.trace("enter - " + HueMethod.class.getName() + ".put(" + resource + ")");
    }/*from w w  w.  j av  a  2  s. c  o  m*/
    if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug(">>> [PUT (" + (new Date()) + ")] -> " + hue.getAPIEndpoint() + resource);
    }
    try {
        HttpClient client = getClient();
        HttpPut method = new HttpPut(hue.getAPIEndpoint() + resource);

        method.addHeader("Content-Type", "application/json");

        try {
            if (body != null) {
                //noinspection deprecation
                method.setEntity(new StringEntity(body.toString(), "application/json", "UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            throw new HueException(e);
        }
        if (wire.isDebugEnabled()) {
            wire.debug(method.getRequestLine().toString());
            for (Header header : method.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (body != null) {
                try {
                    wire.debug(EntityUtils.toString(method.getEntity()));
                } catch (IOException ignore) {
                }

                wire.debug("");
            }
        }
        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(method);
            status = response.getStatusLine();
        } catch (IOException e) {
            std.error("PUT: Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
            if (std.isTraceEnabled()) {
                e.printStackTrace();
            }
            throw new HueException(e);
        }
        if (std.isDebugEnabled()) {
            std.debug("PUT: HTTP Status " + status);
        }
        Header[] headers = response.getAllHeaders();

        if (wire.isDebugEnabled()) {
            wire.debug(status.toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }
        if (status.getStatusCode() == HttpServletResponse.SC_NO_CONTENT) {
            return null;
        } else if (status.getStatusCode() != HttpServletResponse.SC_OK
                && status.getStatusCode() != HttpServletResponse.SC_CREATED
                && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) {
            std.error("PUT: Expected NO_CONTENT or CREATED or OK or ACCEPTED for PUT request, got "
                    + status.getStatusCode());

            HttpEntity entity = response.getEntity();

            if (entity == null) {
                throw new HueException(status.getStatusCode(), "An error was returned without explanation");
            }
            String json;

            try {
                json = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new HueException(status.getStatusCode(), e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(json);
                wire.debug("");
            }
            throw new HueException(status.getStatusCode(), json);
        } else {
            try {
                String json = EntityUtils.toString(response.getEntity());

                if (wire.isDebugEnabled()) {
                    wire.debug(json);
                    wire.debug("");
                }
                if (json.startsWith("[")) {
                    JSONArray arr = new JSONArray(json);

                    if (arr.length() > 0) {
                        JSONObject ob = arr.getJSONObject(0);

                        if (ob.has("error")) {
                            ob = ob.getJSONObject("error");
                            if (ob.has("description")) {
                                throw new HueException(ob.getString("description"));
                            }
                        }
                        return ob;
                    }
                    return null;
                }
                return new JSONObject(json);
            } catch (IOException e) {
                throw new HueException(status.getStatusCode(), e.getMessage());
            } catch (JSONException e) {
                throw new HueException(status.getStatusCode(), e.getMessage());
            }
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + HueMethod.class.getName() + ".put()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("<<< [PUT (" + (new Date()) + ")] -> " + hue.getAPIEndpoint() + resource
                    + " <--------------------------------------------------------------------------------------");
            wire.debug("");
        }
    }
}

From source file:com.iorga.webappwatcher.EventLogManager.java

public void writeEventLogToHttpServletResponse(final HttpServletResponse httpResponse) throws IOException {
    synchronized (objectOutputStreamLogLock) {
        if (objectOutputStreamLog != null) {
            // before trying to download the log, we must first flush it
            // warning : as the footer of the xz will never be written, that file will be inconsistent for properly reading it
            flushLog();//from  w ww.j a  v  a 2s .  c om
        }
        if (logFile != null && logFile.exists()) {
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            httpResponse.setContentType("application/x-gzip");
            httpResponse.setHeader("Content-Disposition",
                    "attachment; filename=\"" + logFile.getName() + ".gz\"");

            final FileInputStream inputStream = new FileInputStream(logFile);
            final OutputStream outputStream = new GZIPOutputStream(httpResponse.getOutputStream());
            try {
                IOUtils.copy(inputStream, outputStream);
            } finally {
                inputStream.close();
                outputStream.close();
            }
        } else {
            httpResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
            final PrintWriter writer = httpResponse.getWriter();
            writer.write("No log available at the moment.");
        }
    }
}

From source file:com.orange.api.atmosdav.AtmosDavServlet.java

/**
 * Process a PUT request for the specified resource.
 *
 * Note: PUT method currently does not support Content-Range parameter.
 * It will throw a 501 error if Content-Range is present in the header,
 * as expected by RFC.// w w w  .j a  v  a2 s.  com
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 */
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    AtmosApi api = getAPIFromAuthent(req, resp);
    ObjectPath obj_path = getAtmosPath(getPathFromReq(req), api);

    UploadHelper up_helper = new UploadHelper(api.api);
    up_helper.setMinReadSize(UploadHelper.DEFAULT_BUFFSIZE);

    // first test if object exists
    AtmosType obj_type = getObjectType(getObjectMetadata(api.api, obj_path));
    boolean partial = false;

    // RFC says we MUST reject request containing Content-Range if we don't support it
    if (req.getHeader("Content-Range") != null) {
        resp.sendError(resp.SC_NOT_IMPLEMENTED);
        return;
    }

    if (!partial) {
        if (obj_type == AtmosType.NON_EXISTENT) {
            up_helper.createObjectOnPath(obj_path, req.getInputStream(), null, null, false);
            resp.setStatus(HttpServletResponse.SC_CREATED);
        } else if (obj_type == AtmosType.REGULAR) {
            up_helper.updateObject(obj_path, req.getInputStream(), null, null, false);
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); // Cannot PUT on a directory
        }
    } else {
        resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
        //                    if (!exists)
        //                        api.createObjectOnPath(obj_path, null, null, null, null);
        //                    Extent extent = new Extent(range.start, range.length);
        //                    api.updateObject(obj_path, null, null, extent, content, null);
    }
}

From source file:se.tillvaxtverket.ttsigvalws.ttwebservice.TTSigValServlet.java

private static void nullResponse(HttpServletResponse response) {
    try {//from  ww w  . j a v  a2s.c  o m
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        response.getWriter().write("");
        response.getWriter().close();
    } catch (Exception ex) {
    }
}

From source file:org.osaf.cosmo.cmp.CmpServlet.java

private void processUserDelete(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String username = usernameFromPathInfo(req.getPathInfo());
    if (username == null) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;/*  w w w. j  a v a  2  s  .  com*/
    }
    if (username.equals(User.USERNAME_OVERLORD)) {
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    userService.removeUser(username);
    resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
}

From source file:lucee.runtime.net.rpc.server.RPCServer.java

/**
 * write a message to the response, set appropriate headers for content
 * type..etc./*from w  ww. j  ava  2s. c o m*/
 * @param res   response
 * @param responseMsg message to write
 * @throws AxisFault
 * @throws IOException if the response stream can not be written to
 */
private void sendResponseX(String contentType, HttpServletResponse res, Message responseMsg)
        throws AxisFault, IOException {
    if (responseMsg == null) {
        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
        if (isDebug) {
            log.debug("NO AXIS MESSAGE TO RETURN!");
        }
    } else {
        if (isDebug) {
            log.debug("Returned Content-Type:" + contentType);
        }

        try {

            res.setContentType(contentType);
            responseMsg.writeTo(res.getOutputStream());
        } catch (SOAPException e) {
            logException(e);
        }
    }

    if (!res.isCommitted()) {
        res.flushBuffer(); // Force it right now.
    }
}

From source file:org.ednovo.gooru.controllers.v2.api.LibraryRestV2Controller.java

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_LIBRARY_DELETE })
@RequestMapping(value = "/{libraryId}", method = RequestMethod.DELETE)
public void deleteAssocCollectionLibrary(@PathVariable(value = LIBRARY_ID) String libraryId,
        @RequestParam(value = CODE_ID) String codeId, @RequestParam(value = GOORU_OID) String gooruOid,
        HttpServletRequest request, HttpServletResponse response) {
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    this.getFeaturedService().deleteLibraryCollectionAssoc(libraryId, codeId, gooruOid);
}

From source file:com.imaginary.home.controller.CloudService.java

public boolean hasCommands() throws CommunicationException, ControllerException {
    HttpClient client = getClient(endpoint, proxyHost, proxyPort);
    HttpHead method = new HttpHead(endpoint + "/command");
    long timestamp = System.currentTimeMillis();

    method.addHeader("Content-Type", "application/json");
    method.addHeader("x-imaginary-version", VERSION);
    method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp));
    method.addHeader("x-imaginary-api-key", serviceId);

    if (token == null) {
        authenticate();/*www . ja  v  a2 s.co m*/
    }
    String stringToSign = "head:/command:" + serviceId + ":" + token + ":" + timestamp + ":" + VERSION;

    try {
        method.addHeader("x-imaginary-signature", sign(apiKeySecret.getBytes("utf-8"), stringToSign));
    } catch (Exception e) {
        throw new ControllerException(e);
    }

    HttpResponse response;
    StatusLine status;

    try {
        response = client.execute(method);
        status = response.getStatusLine();
    } catch (IOException e) {
        e.printStackTrace();
        throw new CommunicationException(e);
    }
    if (status.getStatusCode() != HttpServletResponse.SC_NO_CONTENT) {
        parseError(response); // this will throw an exception
    }
    Header h = response.getFirstHeader("x-imaginary-has-commands");
    String val = (h == null ? "false" : h.getValue());

    return (val != null && val.equalsIgnoreCase("true"));
}

From source file:com.iorga.webappwatcher.EventLogManager.java

public void writeEventLogsToHttpServletResponse(final HttpServletResponse httpResponse,
        final Iterable<String> fileNames) throws IOException {
    // First, we check if the given paths are in the log path
    final Set<String> eventLogs = Sets.newHashSet(listEventLogsNameInThePath());
    ArchiveOutputStream outputStream = null;
    try {//ww  w. j  a  v a 2 s.  c o  m
        for (final String fileName : fileNames) {
            if (eventLogs.contains(fileName) && new File(getLogPathDirectory(), fileName).exists()) {
                outputStream = writeEventLogToHttpServletResponse(httpResponse, fileName, outputStream);
            }
        }
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    if (outputStream == null) {
        // No file were appended
        httpResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
        final PrintWriter writer = httpResponse.getWriter();
        writer.write("No log available at the moment.");
    }
}