Example usage for javax.servlet.http HttpServletResponse SC_OK

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

Introduction

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

Prototype

int SC_OK

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

Click Source Link

Document

Status code (200) indicating the request succeeded normally.

Usage

From source file:io.seldon.api.controller.TokenController.java

@RequestMapping(method = RequestMethod.POST)
public @ResponseBody ResourceBean createToken(HttpServletRequest req, HttpServletResponse resp) {
    Date start = new Date();
    ResourceBean res = null;/*from  ww w .  j  ava2 s .  c  o  m*/
    try {
        /*resp.setContentType(Constants.CONTENT_TYPE_JSON);
        resp.setHeader(Constants.CACHE_CONTROL, Constants.NO_CACHE);*/
        //retrieve token
        Token token = authorizationServer.getToken(req);
        //if successful
        resp.setStatus(HttpServletResponse.SC_OK);
        TokenBean bean = new TokenBean(token);
        MemCachePeer.put(MemCacheKeys.getTokenBeanKey(bean.getAccess_token()), bean,
                (int) bean.getExpires_in());
        res = bean;
    } catch (APIException e) {
        ApiLoggerServer.log(this, e);
        ErrorBean bean = new ErrorBean(e);
        resp.setStatus(e.getHttpResponse());
        res = bean;
    } catch (Exception e) {
        ApiLoggerServer.log(this, e);
        APIException apiEx = new APIException(APIException.GENERIC_ERROR);
        ErrorBean bean = new ErrorBean(apiEx);
        resp.setStatus(apiEx.getHttpResponse());
        res = bean;
        e.printStackTrace();
    }
    ApiLogger.log("token", start, new Date(), res, res, req);
    return res;
}

From source file:com.google.appinventor.server.WebAppLaunchServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    String userId = userInfoProvider.getUserId();
    String launchFile;// www . j  av  a 2 s . c  om

    try {
        String uri = req.getRequestURI();
        // First, call split with no limit parameter.
        String[] uriComponents = uri.split("/");
        String launchKind = uriComponents[REQUEST_INDEX];

        if (launchKind.equals(ServerLayout.WEBAPP_FILE)) {
            uriComponents = uri.split("/", SPLIT_LIMIT_FILE);
            if (FILE_PATH_INDEX > uriComponents.length) {
                throw CrashReport.createAndLogError(LOG, req, null,
                        new IllegalArgumentException("Missing web app file path."));
            }
            String fileName = uriComponents[FILE_PATH_INDEX];
            launchFile = storageIo.downloadUserFile(userId, fileName, "UTF-8");

        } else {
            throw CrashReport.createAndLogError(LOG, req, null,
                    new IllegalArgumentException("Unknown launch kind: " + launchKind));
        }

    } catch (IllegalArgumentException e) {
        throw CrashReport.createAndLogError(LOG, req, null, e);
    }

    byte[] content = launchFile.getBytes();
    // Set http response information
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.setContentType("text/html");
    resp.setContentLength(launchFile.length());

    // Attach download data
    ServletOutputStream out = resp.getOutputStream();
    out.write(content);
    out.close();
}

From source file:com.app.inventario.controlador.Controlador.java

@RequestMapping(value = "/agregar-usuario", method = RequestMethod.POST)
public @ResponseBody Map agregarUsuario(@ModelAttribute("usuario") Usuario usuario, HttpServletRequest request,
        HttpServletResponse response) {/*from   w  w w  .  ja  va 2 s . co m*/
    Map map = new HashMap();
    try {
        this.usuarioServicio.guardar(usuario);
        response.setStatus(HttpServletResponse.SC_OK);
        map.put("Status", "OK");
        map.put("Message", "Agregado Correctamente");
    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        map.put("Status", "FAIL");
        map.put("Message", ex.getCause().getCause().getCause().getMessage());
    }
    return map;
}

From source file:edu.umn.msi.tropix.transfer.http.server.HttpTransferControllerImpl.java

private void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException {
    LOG.info("doPost called");
    final String uploadKey = request.getParameter(ServerConstants.KEY_PARAMETER_NAME);
    LOG.info("Key is " + uploadKey);
    try {/*from   w  w  w .  j a v a  2 s.  c om*/
        fileKeyResolver.handleUpload(uploadKey, request.getInputStream());
        response.flushBuffer();
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (final Exception e) {
        throw new ServletException(e);
    }
}

From source file:net.skhome.roborace.web.controller.UserController.java

@RequestMapping(method = RequestMethod.PUT)
public void updateUserAccount(@RequestBody @Valid final UserAccount account,
        final HttpServletResponse response) {

    try {//ww w .ja v a2  s .com
        service.updateUserAccount(account);
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (DataAccessException ex) {
        throw new ResourceNotFoundException(account.getId());
    }

}

From source file:de.elomagic.mag.ServletMock.java

@Override
protected void doHead(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getRequestURI().endsWith("TestFile.pdf")) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {//  ww w.j  a v a 2 s .c o m
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.gc.GoogleController.java

/**
 * Service that start oauth authentication flow with Google,
 * building a state token and login url.
 * //w  w  w . ja va 2 s  .  c o  m
 * @param response : instance of {@link HttpServletResponse}
 * @param request : instance of {@link HttpServletRequest}
 * @return string : Google login url
 */
@RequestMapping(value = "/auth", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public String socialGooglePlus(HttpServletResponse response, HttpServletRequest request) {
    logger.info("****** Google auth ******");

    String token = auth.getStateToken();
    String loginURL = auth.buildLoginUrl();

    //save in session
    request.getSession().setAttribute("state", token);
    response.setStatus(HttpServletResponse.SC_OK);

    if (token != null && loginURL != null) {
        return loginURL;
    } else {
        return null;
    }
}

From source file:com.ebay.pulsar.metric.servlet.MetricRestServlet.java

private void ping(HttpServletRequest request, String pathInfo, HttpServletResponse response) {
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:com.imaginary.home.cloud.api.call.DeviceCall.java

@Override
public void get(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("GET " + req.getRequestURI());
    }//  w w w  .  ja  v a 2 s  .c  o m
    try {
        String deviceId = (path.length > 1 ? path[1] : null);

        if (logger.isDebugEnabled()) {
            logger.debug("deviceId=" + deviceId);
        }
        if (deviceId != null) {
            Device device = Device.getDevice(deviceId);

            if (device == null) {
                throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT,
                        "The device " + deviceId + " does not exist.");
            }
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().println((new JSONObject(toJSON(device))).toString());
            resp.getWriter().flush();
        } else {
            String locationId = req.getParameter("locationId");
            String deviceType = req.getParameter("deviceType");
            String tmp = req.getParameter("includeChildren");
            boolean includeChildren = (tmp != null && tmp.equalsIgnoreCase("true"));

            if (logger.isDebugEnabled()) {
                logger.debug("Params=" + locationId + " / " + deviceType + " / " + includeChildren);
            }
            User user = (userId != null ? User.getUserByUserId(userId) : null);
            ControllerRelay relay = (user == null
                    ? ControllerRelay.getRelay((String) headers.get(RestApi.API_KEY))
                    : null);
            Location location = (locationId == null ? null : Location.getLocation(locationId));

            if (locationId != null && location == null) {
                throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_ACTION,
                        "You do not have access to those resources");
            }
            if (user == null && relay == null) {
                throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_ACTION,
                        "Cannot request devices without a proper authentication context");
            }
            if (relay != null && location != null) {
                if (!relay.getLocationId().equals(location.getLocationId())) {
                    throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_ACTION,
                            "You do not have access to those resources");
                }
            }
            Collection<ControllerRelay> relays;

            if (relay != null) {
                relays = Collections.singletonList(relay);
            } else {
                if (location != null) {
                    boolean allowed = location.getOwnerId().equals(user.getUserId());

                    if (!allowed) {
                        for (String id : user.getLocationIds()) {
                            if (id.equals(location.getLocationId())) {
                                allowed = true;
                                break;
                            }
                        }
                        if (!allowed) {
                            throw new RestException(HttpServletResponse.SC_FORBIDDEN,
                                    RestException.INVALID_ACTION, "You do not have access to those resources");
                        }
                    }
                    relays = ControllerRelay.findRelaysInLocation(location);
                } else {
                    relays = new ArrayList<ControllerRelay>();
                    for (Location l : user.getLocations()) {
                        relays.addAll(ControllerRelay.findRelaysInLocation(l));
                    }
                }

            }
            if (logger.isDebugEnabled()) {
                logger.debug("relays=" + relays);
            }
            ArrayList<Device> devices = new ArrayList<Device>();

            for (ControllerRelay r : relays) {
                if (deviceType == null) {
                    devices.addAll(Device.findDevicesForRelay(r));
                } else if (deviceType.equals("powered")) {
                    if (includeChildren) {
                        PoweredDevice.findPoweredDevicesForRelayWithChildren(r, devices);
                    } else {
                        devices.addAll(PoweredDevice.findPoweredDevicesForRelay(r));
                    }
                } else if (deviceType.equals("light")) {
                    devices.addAll(Light.findPoweredDevicesForRelay(r));
                } else {
                    throw new RestException(HttpServletResponse.SC_BAD_REQUEST,
                            RestException.INVALID_DEVICE_TYPE, "Invalid device type: " + deviceType);
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug("devices=" + devices);
            }
            ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

            for (Device d : devices) {
                list.add(toJSON(d));
            }
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().println((new JSONArray(list)).toString());
            resp.getWriter().flush();
        }
    } catch (PersistenceException e) {
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                e.getMessage());
    }
}

From source file:net.siegmar.japtproxy.fetcher.FetcherHttp.java

/**
 * {@inheritDoc}/*w  w  w .ja v a 2 s.  c  om*/
 */
@Override
public FetchedResourceHttp fetch(final URL targetResource, final long lastModified,
        final String originalUserAgent) throws IOException, ResourceUnavailableException {

    final HttpGet httpGet = new HttpGet(targetResource.toExternalForm());

    httpGet.addHeader(HttpHeaderConstants.USER_AGENT,
            StringUtils.trim(StringUtils.defaultString(originalUserAgent) + " " + Util.USER_AGENT));

    if (lastModified != 0) {
        final String lastModifiedSince = Util.getRfc822DateFromTimestamp(lastModified);
        LOG.debug("Setting If-Modified-Since: {}", lastModifiedSince);
        httpGet.setHeader(HttpHeaderConstants.IF_MODIFIED_SINCE, lastModifiedSince);
    }

    CloseableHttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(httpGet);

        if (LOG.isDebugEnabled()) {
            logResponseHeader(httpResponse.getAllHeaders());
        }

        final int retCode = httpResponse.getStatusLine().getStatusCode();
        if (retCode == HttpServletResponse.SC_NOT_FOUND) {
            httpGet.releaseConnection();
            throw new ResourceUnavailableException("Resource '" + targetResource + " not found");
        }

        if (retCode != HttpServletResponse.SC_OK && retCode != HttpServletResponse.SC_NOT_MODIFIED) {
            throw new IOException("Invalid status code returned: " + httpResponse.getStatusLine());
        }

        final FetchedResourceHttp fetchedResourceHttp = new FetchedResourceHttp(httpResponse);
        fetchedResourceHttp.setModified(lastModified == 0 || retCode != HttpServletResponse.SC_NOT_MODIFIED);

        if (LOG.isDebugEnabled()) {
            final long fetchedTimestamp = fetchedResourceHttp.getLastModified();
            if (fetchedTimestamp != 0) {
                LOG.debug("Response status code: {}, Last modified: {}", retCode,
                        Util.getSimpleDateFromTimestamp(fetchedTimestamp));
            } else {
                LOG.debug("Response status code: {}", retCode);
            }
        }

        return fetchedResourceHttp;
    } catch (final IOException e) {
        // Closing only in case of an exception - otherwise closed by FetchedResourceHttp
        if (httpResponse != null) {
            httpResponse.close();
        }

        throw e;
    }
}