Example usage for javax.servlet.http HttpServletResponse SC_BAD_REQUEST

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

Introduction

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

Prototype

int SC_BAD_REQUEST

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

Click Source Link

Document

Status code (400) indicating the request sent by the client was syntactically incorrect.

Usage

From source file:com.cognifide.cq.cache.plugins.statistics.action.ShowKeysAction.java

@Override
public void exectue() {
    String cacheName = request.getParameter(Statistics.CACHE_NAME_PARAMETER);
    if (StringUtils.isNotEmpty(cacheName)) {
        logger.info("Keys from {} cache will be collected", cacheName);
        try {/*from w ww. j av a  2  s .c o m*/
            readKeysFrom(cacheName);
        } catch (IOException x) {
            logger.error("Error while generating markup.", x);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    } else {
        logger.error("Request does not contain [cacheName] parameter.");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:gov.redhawk.rap.internal.PluginProviderServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final Path path = new Path(req.getRequestURI());
    String pluginId = path.lastSegment();
    if (pluginId.endsWith(".jar")) {
        pluginId = pluginId.substring(0, pluginId.length() - 4);
    }/* ww  w  .  j av a2 s. c o m*/
    final Bundle b = Platform.getBundle(pluginId);
    if (b == null) {
        final String protocol = req.getProtocol();
        final String msg = "Plugin does not exist: " + pluginId;
        if (protocol.endsWith("1.1")) {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
        } else {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        }
        return;
    }
    final File file = FileLocator.getBundleFile(b);
    resp.setContentType("application/octet-stream");

    if (file.isFile()) {
        final String contentDisposition = "attachment; filename=\"" + file.getName() + "\"";
        resp.setHeader("Content-Disposition", contentDisposition);
        resp.setContentLength((int) file.length());
        final FileInputStream istream = new FileInputStream(file);
        try {
            IOUtils.copy(istream, resp.getOutputStream());
        } finally {
            istream.close();
        }
        resp.flushBuffer();
    } else {
        final String contentDisposition = "attachment; filename=\"" + file.getName() + ".jar\"";
        resp.setHeader("Content-Disposition", contentDisposition);
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        final Manifest man = new Manifest(new FileInputStream(new File(file, "META-INF/MANIFEST.MF")));
        final JarOutputStream out = new JarOutputStream(outputStream, man);
        final File binDir = new File(file, "bin");

        if (binDir.exists()) {
            addFiles(out, Path.ROOT, binDir.listFiles());
            for (final File f : file.listFiles()) {
                if (!f.getName().equals("bin")) {
                    addFiles(out, Path.ROOT, f);
                }
            }
        } else {
            addFiles(out, Path.ROOT, file.listFiles());
        }
        out.close();
        outputStream.close();
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        resp.setContentLength(outputStream.size());
        try {
            IOUtils.copy(inputStream, resp.getOutputStream());
        } finally {
            inputStream.close();
        }
        resp.flushBuffer();
    }

}

From source file:net.myrrix.web.servlets.EstimateForAnonymousServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    CharSequence pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No path");
        return;//from   w  w  w  .  ja  v a2  s .  c o  m
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    long toItemID;
    Pair<long[], float[]> itemIDsAndValue;
    try {
        toItemID = Long.parseLong(pathComponents.next());
        itemIDsAndValue = RecommendToAnonymousServlet.parseItemValuePairs(pathComponents);
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    } catch (NumberFormatException nfe) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nfe.toString());
        return;
    }

    if (itemIDsAndValue.getFirst().length == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No items");
        return;
    }

    long[] itemIDs = itemIDsAndValue.getFirst();
    float[] values = itemIDsAndValue.getSecond();

    MyrrixRecommender recommender = getRecommender();
    try {
        float estimate = recommender.estimateForAnonymous(toItemID, itemIDs, values);
        Writer out = response.getWriter();
        out.write(Float.toString(estimate));
        out.write('\n');
    } catch (NotReadyException nre) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, nre.toString());
    } catch (NoSuchItemException nsie) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, nsie.toString());
    } catch (TasteException te) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString());
        getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te);
    }
}

From source file:com.vmware.lightwaveui.Login.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *///from  w  ww  .  ja v  a 2  s .  co m
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        String[] tenant = request.getParameterValues("tenant");
        String tenantName = "";
        if (tenant != null && tenant.length > 0) {
            tenantName = tenant[0];
        }
        if (tenantName == null || tenantName == "") {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No tenant specifed.");
            return;
        }
        tenantName = tenantName.toLowerCase();
        String uri = request.getRequestURL().toString();
        String protocol = uri.split("://")[0];
        String hostname = uri.split("://")[1].split("/")[0];
        String client_id = getClientId(tenantName);
        String redirect_uri = protocol + "://" + hostname + "/lightwaveui/Home";
        String openIdConnectUri = protocol + "://" + hostname + "/openidconnect/oidc/authorize/" + tenantName;
        String args = "?response_type=id_token%20token&response_mode=form_post&client_id=" + client_id
                + "&redirect_uri=" + redirect_uri
                + "&state=_state_lmn_&nonce=_nonce_lmn_&scope=openid%20rs_admin_server%20rs_vmdir";
        String authorizeUri = openIdConnectUri + args;
        response.sendRedirect(authorizeUri);
    } catch (Exception exc) {
        String message = " Message: " + exc.getMessage();
        String querystring = "?" + request.getQueryString();
        String uri = request.getRequestURL().toString();
        response.getWriter().append("Error: ").append(uri + querystring + message);
    }
}

From source file:com.thinkberg.moxo.dav.CopyMoveBase.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    boolean overwrite = getOverwrite(request);
    FileObject object = getResourceManager().getFileObject(request.getPathInfo());
    FileObject targetObject = getDestination(request);

    try {/*from   ww w.j ava  2 s.c o  m*/
        // check that we can write the target
        LockManager.getInstance().checkCondition(targetObject, getIf(request));
        // if we move, check that we can actually write on the source
        if ("MOVE".equals(request.getMethod())) {
            LockManager.getInstance().checkCondition(object, getIf(request));
        }
    } catch (LockException e) {
        if (e.getLocks() != null) {
            response.sendError(SC_LOCKED);
        } else {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
        return;
    }

    if (null == targetObject) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (object.equals(targetObject)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (targetObject.exists()) {
        if (!overwrite) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else {
        FileObject targetParent = targetObject.getParent();
        if (!targetParent.exists() || !FileType.FOLDER.equals(targetParent.getType())) {
            response.sendError(HttpServletResponse.SC_CONFLICT);
        }
        response.setStatus(HttpServletResponse.SC_CREATED);
    }

    copyOrMove(object, targetObject, getDepth(request));
}

From source file:com.mengka.diamond.server.controller.ConfigController.java

/**
 * ???/*from w  w  w.j  a v  a 2s . c om*/
 * 
 * @param request
 * @param dataId
 * @param group
 *            ?
 * @return
 */
@RequestMapping(method = RequestMethod.GET)
public String getConfig(HttpServletRequest request, HttpServletResponse response, String dataId, String group) {
    response.setHeader("Content-Type", "text/html;charset=utf-8");
    final String address = getRemortIP(request);
    if (address == null) {
        // ?400
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "400";
    }

    if (GlobalCounter.getCounter().decrementAndGet() >= 0) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return "503";
    }

    String md5 = this.configService.getContentMD5(dataId, group);
    if (md5 == null) {
        return "404";
    }

    response.setHeader(Constants.CONTENT_MD5, md5);

    // 304???double-check??
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    String path = configService.getConfigInfoPath(dataId, group);
    // ?
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    // ?
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");
    return "forward:" + path;
}

From source file:org.craftercms.security.utils.handlers.AbstractRestHandlerBase.java

protected <T> void sendObject(int status, T responseBody, RequestContext context) throws IOException {
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();

    response.setStatus(status);/*from  www.j a  va 2 s.co m*/

    try {
        responseWriter.writeWithMessageConverters(responseBody, request, response);
    } catch (HttpMediaTypeNotAcceptableException e) {
        logger.error(e.getMessage(), e);

        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    }
}

From source file:eu.webteq.web.scripts.bean.YubicoLoginPost.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
    Content c = req.getContent();/*w w  w. j a v a 2  s.  c  om*/
    if (c == null) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Missing POST body.");
    }

    JSONObject json;
    try {
        json = new JSONObject(c.getContent());
        String username = json.getString("username");
        String password = json.getString("password");

        if (username == null || username.length() == 0) {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Username not specified");
        }

        if (password == null) {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Password not specified");
        }

        // Extract the OTP from the password field.
        String deviceid = yubikeyService.getDevice(username);
        if (deviceid == null || deviceid.length() == 0) {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "No device id");
        }

        int idx = password.indexOf(deviceid);
        if (idx == -1) {
            // Either the user is using the wrong key or no OTP has been included
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Failed to extract OTP");
        }
        String otp = password.substring(idx);

        if (!yubikeyService.isOwner(username, YubicoClient.getPublicId(otp))) {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "User does not own this device");
        }

        YubicoResponse response = yubikeyService.verify(otp);
        if (response == null || response.getStatus() != YubicoResponseStatus.OK) {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Invalid OTP");
        }

        return login(username, password.substring(0, idx));
    } catch (JSONException jErr) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST,
                "Unable to parse JSON POST body: " + jErr.getMessage());
    } catch (IOException ioErr) {
        throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR,
                "Unable to retrieve POST body: " + ioErr.getMessage());
    }
}

From source file:com.cloudera.oryx.kmeans.serving.web.AddServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

    KMeansGenerationManager generationManager = getGenerationManager();
    Generation generation = generationManager.getCurrentGeneration();
    if (generation == null) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "API method unavailable until model has been built and loaded");
        return;/*from   w  w w.j  a v a  2  s  . c  o  m*/
    }

    for (CharSequence line : CharStreams.readLines(request.getReader())) {
        generationManager.append(line);

        RealVector vec = generation.toVector(DelimitedDataUtils.decode(line));
        if (vec == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong column count");
            return;
        }

        // TODO update the centers, along the lines of Meyerson et al.
    }

}

From source file:com.examples.abelanav2.BucketNotificationServlet.java

@Override
public final void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    // Decode the name and bucket of the notification
    BucketNotification notification;/*from  www.  j  av  a 2 s .c om*/
    try {
        String jsonString = IOUtils.toString(req.getInputStream());
        notification = new Gson().fromJson(jsonString, BucketNotification.class);
    } catch (IOException e) {
        log("Failed to decode the notification: " + e.getMessage());
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    try {
        if (!req.getHeader("X-Goog-Channel-Token").equals(ConfigurationConstants.SECRET_NOTIF_TOKEN)) {
            resp.setStatus(HttpStatusCodes.STATUS_CODE_FORBIDDEN);
            return;
        }

        if (!req.getHeader("X-Goog-Resource-State").equals("exists")) {
            resp.getWriter().write("This is not a new photo addition.");
            resp.setStatus(HttpStatusCodes.STATUS_CODE_OK);
            return;
        }

        // Handle duplicated notifications, drop keys after 5 minutes
        Boolean inCache = false;
        Cache cache = null;
        try {
            CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
            Map<Object, Object> properties = new HashMap<>();
            properties.put(GCacheFactory.EXPIRATION_DELTA, TimeUnit.MINUTES.toSeconds(5));
            properties.put(MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT, true);
            cache = cacheFactory.createCache(properties);
            inCache = (Boolean) cache.get(notification.getName());
        } catch (CacheException e) {
            log("Failed to instantiate the Memcache, risk of duplicate notifications: " + e.getMessage());
        }

        if (inCache == null || !inCache) {
            // Add a new task to the queue
            Queue queue = QueueFactory.getDefaultQueue();
            queue.add(TaskOptions.Builder.withUrl("/notice/incoming-image")
                    .param("bucket", notification.getBucket()).param("name", notification.getName()));
            if (cache != null) {
                cache.put(notification.getName(), true);
            }
            resp.getWriter().write("Task added to the queue");
            log("Task created for bucket " + notification.getBucket() + " and file " + notification.getName());
        } else {
            resp.getWriter().write("This is a duplicate notification");
            log("Duplicate notification for bucket " + notification.getBucket() + " and file "
                    + notification.getName());
        }
        resp.setStatus(HttpStatusCodes.STATUS_CODE_OK);

    } catch (IOException e) {
        log("Error while writing the response");
        resp.setStatus(HttpStatusCodes.STATUS_CODE_SERVER_ERROR);
    }
}