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.apache.openaz.xacml.rest.XACMLPapServlet.java

/**
 * Called by: - PDP nodes to register themselves with the PAP, and - Admin Console to make changes in the
 * PDP Groups.//from ww  w . j  av a 2  s  .c o m
 *
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {

        XACMLRest.dumpRequest(request);

        // since getParameter reads the content string, explicitly get the content before doing that.
        // Simply getting the inputStream seems to protect it against being consumed by getParameter.
        request.getInputStream();

        //
        // Is this from the Admin Console?
        //
        String groupId = request.getParameter("groupId");
        if (groupId != null) {
            //
            // this is from the Admin Console, so handle separately
            //
            doACPost(request, response, groupId);
            return;
        }

        //
        // Request is from a PDP.
        // It is coming up and asking for its config
        //

        //
        // Get the PDP's ID
        //
        String id = this.getPDPID(request);
        logger.info("doPost from: " + id);
        //
        // Get the PDP Object
        //
        PDP pdp = this.papEngine.getPDP(id);
        //
        // Is it known?
        //
        if (pdp == null) {
            logger.info("Unknown PDP: " + id);
            try {
                this.papEngine.newPDP(id, this.papEngine.getDefaultGroup(), id, "Registered on first startup");
            } catch (NullPointerException | PAPException e) {
                logger.error("Failed to create new PDP", e);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
                return;
            }
            // get the PDP we just created
            pdp = this.papEngine.getPDP(id);
            if (pdp == null) {
                String message = "Failed to create new PDP for id: " + id;
                logger.error(message);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
                return;
            }
        }
        //
        // Get the PDP's Group
        //
        PDPGroup group = this.papEngine.getPDPGroup(pdp);
        if (group == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                    "PDP not associated with any group, even the default");
            return;
        }
        //
        // Determine what group the PDP node is in and get
        // its policy/pip properties.
        //
        Properties policies = group.getPolicyProperties();
        Properties pipconfig = group.getPipConfigProperties();
        //
        // Get the current policy/pip configuration that the PDP has
        //
        Properties pdpProperties = new Properties();
        pdpProperties.load(request.getInputStream());
        logger.info("PDP Current Properties: " + pdpProperties.toString());
        logger.info("Policies: " + (policies != null ? policies.toString() : "null"));
        logger.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
        //
        // Validate the node's properties
        //
        boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
        //
        // Send back current configuration
        //
        if (!isCurrent) {
            //
            // Tell the PDP we are sending back the current policies/pip config
            //
            logger.info("PDP configuration NOT current.");
            if (policies != null) {
                //
                // Put URL's into the properties in case the PDP needs to
                // retrieve them.
                //
                this.populatePolicyURL(request.getRequestURL(), policies);
                //
                // Copy the properties to the output stream
                //
                policies.store(response.getOutputStream(), "");
            }
            if (pipconfig != null) {
                //
                // Copy the properties to the output stream
                //
                pipconfig.store(response.getOutputStream(), "");
            }
            //
            // We are good - and we are sending them information
            //
            response.setStatus(HttpServletResponse.SC_OK);
            // TODO - Correct?
            setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
        } else {
            //
            // Tell them they are good
            //
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);

            // TODO - Correct?
            setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);

        }
        //
        // tell the AC that something changed
        //
        notifyAC();
    } catch (PAPException e) {
        logger.debug("POST exception: " + e, e);
        response.sendError(500, e.getMessage());
        return;
    }
}

From source file:org.opencastproject.scheduler.endpoint.SchedulerRestService.java

@PUT
@Produces(MediaType.TEXT_PLAIN)//from   w  w  w . jav a  2  s  .co m
@Path("bulkaction")
@RestQuery(name = "bulkaction", description = "Updates the dublin core catalog of a set of recordings.", returnDescription = "No body returned.", restParameters = {
        @RestParameter(name = "idlist", description = "JSON Array of ids.", isRequired = true, type = Type.STRING),
        @RestParameter(name = "dublinecore", description = "The dublin core catalog of updated fields", isRequired = true, type = Type.STRING) }, reponses = {
                @RestResponse(responseCode = HttpServletResponse.SC_NO_CONTENT, description = "Events were updated successfully.") })
public Response bulkUpdate(@FormParam("idlist") String idList, @FormParam("dublincore") String dublinCore) {
    JSONParser parser = new JSONParser();
    JSONArray ids = new JSONArray();
    DublinCoreCatalog eventCatalog;
    try {
        if (idList != null && !idList.isEmpty()) {
            ids = (JSONArray) parser.parse(idList);
        }
    } catch (ParseException e) {
        logger.warn("Unable to parse json id list: {}", e);
        return Response.status(Status.BAD_REQUEST).build();
    }
    if (StringUtils.isNotEmpty(dublinCore)) {
        try {
            eventCatalog = parseDublinCore(dublinCore);
        } catch (Exception e) {
            logger.warn("Could not parse Dublin core catalog: {}", e);
            return Response.status(Status.BAD_REQUEST).build();
        }
    } else {
        logger.warn("Cannot add event without dublin core catalog.");
        return Response.status(Status.BAD_REQUEST).build();
    }
    if (!ids.isEmpty() && eventCatalog != null) {
        try {
            service.updateEvents(mlist(ids).map(Misc.<Object, Long>cast()).value(), eventCatalog);
            return Response.noContent().type("").build(); // remove content-type, no message-body.
        } catch (Exception e) {
            logger.warn("Unable to update event with id " + ids.toString() + ": {}", e);
            return Response.serverError().build();
        }
    } else {
        return Response.status(Status.BAD_REQUEST).build();
    }
}

From source file:org.alfresco.repo.webdav.auth.BaseAuthenticationFilter.java

/**
 * Handles the login form directly, allowing management of the session user.
 * /*from  w ww.  j a  v  a 2s . c om*/
 * @param req
 *            the request
 * @param res
 *            the response
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ServletException
 *             on error
 */
protected boolean handleLoginForm(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException {
    if (getLogger().isDebugEnabled())
        getLogger().debug("Handling the login form.");
    // Invalidate current session
    HttpSession session = req.getSession(false);
    if (session != null) {
        session.invalidate();
    }
    StringBuilder out = new StringBuilder(1024);
    Reader in = req.getReader();
    char[] buff = new char[1024];
    int charsRead;
    while ((charsRead = in.read(buff)) != -1) {
        out.append(buff, 0, charsRead);
    }
    in.close();

    try {
        JSONObject json = new JSONObject(out.toString());
        String username = json.getString("username");
        String password = json.getString("password");

        if (username == null || username.length() == 0) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Username not specified in the login form.");
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Username not specified");
            return false;
        }

        if (password == null) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Password not specified in the login form.");
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Password not specified");
            return false;
        }

        authenticationService.authenticate(username, password.toCharArray());
        session = req.getSession();
        createUserEnvironment(session, username, authenticationService.getCurrentTicket(), false);
        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
        return true;
    } catch (AuthenticationException e) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Login failed", e);
        res.sendError(HttpServletResponse.SC_FORBIDDEN, "Login failed");
    } catch (JSONException jErr) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Unable to parse JSON POST body", jErr);
        res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Unable to parse JSON POST body: " + jErr.getMessage());
    }
    return false;
}

From source file:org.sakaiproject.nakamura.files.pool.ContentPoolCommentServlet.java

@Override
protected void doDelete(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    String commentId = request.getParameter("commentId");

    Session adminSession = null;// w  w w. j  a v  a  2 s  .c o  m
    try {
        // check that user is a manager of the content item
        adminSession = repository.loginAdministrative();
        Resource resource = request.getResource();
        Content poolItem = resource.adaptTo(Content.class);
        AuthorizableManager authorizableManager = adminSession.getAuthorizableManager();
        User user = (User) authorizableManager.findAuthorizable(request.getRemoteUser());

        // stop now if no comment ID is provided
        if (StringUtils.isBlank(commentId)) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "'commentId' must be provided.");
            return;
        }

        String path = poolItem.getPath() + "/" + COMMENTS + "/" + commentId;
        ContentManager contentManager = adminSession.getContentManager();
        Content comment = contentManager.get(path);
        if (!isManager(poolItem, user, authorizableManager)
                && !user.getId().equals(comment.getProperty("author"))) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "Must be a manager of the pooled content item or author of the comment to delete a comment.");
            return;
        }
        contentManager.delete(path);
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } catch (AccessDeniedException e) {
        LOGGER.warn(e.getMessage(), e);
        throw new ServletException(e.getMessage(), e);
    } catch (StorageClientException e) {
        LOGGER.warn(e.getMessage(), e);
        throw new ServletException(e.getMessage(), e);
    } finally {
        if (adminSession != null) {
            try {
                adminSession.logout();
            } catch (ClientPoolException e) {
                LOGGER.warn(e.getMessage(), e);
            }
        }
    }
}

From source file:org.apache.openaz.xacml.admin.XacmlAdminUI.java

/**
 * An Update Notification has arrived from the PAP.
 * Tell the Vaadin users to change their data.
 * /* ww w.  j  a v  a  2  s .co  m*/
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
public static void doPAPNotification(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        //
        // Notify all user instances to update groups
        //
        PAPNotificationBroadcaster.updateAllGroups();
    } catch (Exception e) {
        logger.error("Unable to process PAP request: " + e, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}

From source file:com.xqdev.jam.MLJAM.java

private static void sendNoResponse(HttpServletResponse res) {
    res.setStatus(HttpServletResponse.SC_NO_CONTENT);
}

From source file:org.apache.openaz.xacml.rest.XACMLPdpServlet.java

/**
 * Parameters: type=hb|config|Status 1. HeartBeat Status HeartBeat OK - All Policies are Loaded, All PIPs
 * are Loaded LOADING_IN_PROGRESS - Currently loading a new policy set/pip configuration
 * LAST_UPDATE_FAILED - Need to track the items that failed during last update LOAD_FAILURE - ??? Need to
 * determine what information is sent and how 2. Configuration 3. Status return the StdPDPStatus object in
 * the Response content/*from w  ww .j  a  v a 2  s.c o m*/
 *
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    XACMLRest.dumpRequest(request);
    //
    // What are they requesting?
    //
    boolean returnHB = false;
    response.setHeader("Cache-Control", "no-cache");
    String type = request.getParameter("type");
    // type might be null, so use equals on string constants
    if ("config".equals(type)) {
        response.setContentType("text/x-java-properties");
        try {
            String lists = XACMLProperties.PROP_ROOTPOLICIES + "="
                    + XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES, "");
            lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "="
                    + XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "") + "\n";
            try (InputStream listInputStream = new ByteArrayInputStream(lists.getBytes());
                    InputStream pipInputStream = Files.newInputStream(XACMLPdpLoader.getPIPConfig());
                    OutputStream os = response.getOutputStream()) {
                IOUtils.copy(listInputStream, os);
                IOUtils.copy(pipInputStream, os);
            }
            response.setStatus(HttpServletResponse.SC_OK);
        } catch (Exception e) {
            logger.error("Failed to copy property file", e);
            response.sendError(400, "Failed to copy Property file");
        }

    } else if ("hb".equals(type)) {
        returnHB = true;
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);

    } else if ("Status".equals(type)) {
        // convert response object to JSON and include in the response
        synchronized (pdpStatusLock) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), status);
        }
        response.setStatus(HttpServletResponse.SC_OK);

    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "type not 'config' or 'hb'");
    }
    if (returnHB) {
        synchronized (pdpStatusLock) {
            response.addHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString());
        }
    }
}

From source file:com.imaginary.home.cloud.CloudTest.java

private void setupDevices() throws Exception {
    if (token == null) {
        setupToken();//  www  . j a  va 2  s. co  m
    }
    HashMap<String, Object> action = new HashMap<String, Object>();

    action.put("action", "update");

    HashMap<String, Object> relay = new HashMap<String, Object>();

    ArrayList<Map<String, Object>> devices = new ArrayList<Map<String, Object>>();

    {
        HashMap<String, Object> device = new HashMap<String, Object>();

        device.put("systemId", "2");
        device.put("deviceId", "999");
        device.put("model", "XYZ900");
        device.put("on", false);
        device.put("deviceType", "powered");
        device.put("name", "Manipulation Test");
        device.put("description", "A test thing that turns off and on and will be manipulated by tests");
        devices.add(device);
    }
    relay.put("devices", devices);
    action.put("relay", relay);

    HttpClient client = getClient();

    HttpPut method = new HttpPut(cloudAPI + "/relay/" + relayKeyId);
    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", relayKeyId);
    method.addHeader("x-imaginary-signature", CloudService.sign(relayKeySecret.getBytes("utf-8"),
            "put:/relay/" + relayKeyId + ":" + relayKeyId + ":" + token + ":" + timestamp + ":" + VERSION));

    //noinspection deprecation
    method.setEntity(new StringEntity((new JSONObject(action)).toString(), "application/json", "UTF-8"));

    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) {
        Assert.fail("Failed to update state for relay  (" + status.getStatusCode() + ": "
                + EntityUtils.toString(response.getEntity()));
    }

    HttpGet get = new HttpGet(cloudAPI + "/device?locationId=" + URLEncoder.encode(locationId, "utf-8"));

    timestamp = System.currentTimeMillis();

    get.addHeader("Content-Type", "application/json");
    get.addHeader("x-imaginary-version", VERSION);
    get.addHeader("x-imaginary-timestamp", String.valueOf(timestamp));
    get.addHeader("x-imaginary-api-key", apiKeyId);
    get.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"),
            "get:/device:" + apiKeyId + ":" + timestamp + ":" + VERSION));

    try {
        response = client.execute(get);
        status = response.getStatusLine();
    } catch (IOException e) {
        e.printStackTrace();
        throw new CommunicationException(e);
    }
    if (status.getStatusCode() == HttpServletResponse.SC_OK) {
        String json = EntityUtils.toString(response.getEntity());
        JSONArray list = new JSONArray(json);

        for (int i = 0; i < list.length(); i++) {
            JSONObject device = list.getJSONObject(i);

            out("device -> " + device.toString());
            if (device.has("systemId") && device.getString("systemId").equals("2")) {
                if (device.has("vendorDeviceId") && device.getString("vendorDeviceId").equals("999")) {
                    testDeviceId = device.getString("deviceId");
                    break;
                }
            }
        }
    } else {
        Assert.fail("Failed to list devices  (" + status.getStatusCode() + ": "
                + EntityUtils.toString(response.getEntity()));
    }
    Assert.assertNotNull("Test device could not be found during setup", testDeviceId);
}

From source file:org.sakaiproject.sdata.tool.JCRHandler.java

@Override
public void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*  w  w w.ja v a2s  . co m*/
        snoopRequest(request);

        ResourceDefinition rp = resourceDefinitionFactory.getSpec(request);
        String mimeType = ContentTypes.getContentType(rp.getRepositoryPath(), request.getContentType());
        String charEncoding = null;
        if (mimeType.startsWith("text")) {
            charEncoding = request.getCharacterEncoding();
        }
        Node n = jcrNodeFactory.getNode(rp.getRepositoryPath());
        boolean created = false;
        if (n == null) {
            n = jcrNodeFactory.createFile(rp.getRepositoryPath(), mimeType);
            created = true;
            if (n == null) {
                throw new RuntimeException(
                        "Failed to create node at " + rp.getRepositoryPath() + " type " + JCRConstants.NT_FILE);
            }
        } else {
            NodeType nt = n.getPrimaryNodeType();
            if (!JCRConstants.NT_FILE.equals(nt.getName())) {
                response.reset();
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Content Can only be put to a file, resource type is " + nt.getName());
                return;
            }
        }

        GregorianCalendar gc = new GregorianCalendar();
        long lastMod = request.getDateHeader(LAST_MODIFIED);
        if (lastMod > 0) {
            gc.setTimeInMillis(lastMod);
        } else {
            gc.setTime(new Date());
        }

        InputStream in = request.getInputStream();
        saveStream(n, in, mimeType, charEncoding, gc);

        in.close();
        if (created) {
            response.setStatus(HttpServletResponse.SC_CREATED);
        } else {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    } catch (UnauthorizedException ape) {
        // catch any Unauthorized exceptions and send a 401
        response.reset();
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ape.getMessage());
    } catch (PermissionDeniedException pde) {
        // catch any permission denied exceptions, and send a 403
        response.reset();
        response.sendError(HttpServletResponse.SC_FORBIDDEN, pde.getMessage());
    } catch (SDataException e) {
        sendError(request, response, e);
        LOG.error("Failed  To service Request " + e.getMessage());
    } catch (Exception e) {
        sendError(request, response, e);
        snoopRequest(request);
        LOG.error("Failed  TO service Request ", e);
    }
}

From source file:org.dasein.cloud.nimbula.NimbulaMethod.java

public @Nonnegative int get(@Nonnull String target) throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + NimbulaMethod.class.getName() + ".get(" + target + ")");
    }/*from w  w w.  j  a v  a  2  s  .c  o  m*/
    try {
        authenticate();

        if (!target.startsWith("/")) {
            target = getUrl(url, target);
        } else {
            target = url + target;
        }

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [GET (" + (new Date()) + ")] -> " + target
                    + " >--------------------------------------------------------------------------------------");
        }
        try {
            ProviderContext ctx = cloud.getContext();

            if (ctx == null) {
                throw new CloudException("No context was set for this request");
            }
            HttpClient client = getClient(ctx, target.startsWith("https"));
            HttpGet get = new HttpGet(target);

            get.addHeader("Accept", "application/nimbula-v2+json");
            get.setHeader("Cookie", authCookie);

            if (wire.isDebugEnabled()) {
                wire.debug(get.getRequestLine().toString());
                for (Header header : get.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
            HttpResponse response;

            try {
                response = client.execute(get);
                if (wire.isDebugEnabled()) {
                    wire.debug(response.getStatusLine().toString());
                    for (Header header : response.getAllHeaders()) {
                        wire.debug(header.getName() + ": " + header.getValue());
                    }
                    wire.debug("");
                }
            } catch (IOException e) {
                logger.error("I/O error from server communications: " + e.getMessage());
                e.printStackTrace();
                throw new InternalException(e);
            }
            int code = response.getStatusLine().getStatusCode();

            logger.debug("HTTP STATUS: " + code);

            if (code == 401) {
                return code;
            }
            if (code != HttpServletResponse.SC_NO_CONTENT) {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    try {
                        this.response = EntityUtils.toString(entity);

                        if (wire.isDebugEnabled()) {
                            wire.debug(this.response);
                            wire.debug("");
                        }
                    } catch (IOException e) {
                        throw new CloudException(e);
                    }
                }
            }
            checkResponse(response, code);
            return code;
        } finally {
            if (wire.isDebugEnabled()) {
                wire.debug("<<< [GET (" + (new Date()) + ")] -> " + target
                        + " <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + NimbulaMethod.class.getName() + ".get()");
        }
    }
}