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.dasein.cloud.nimbula.NimbulaMethod.java

public @Nonnegative int discover(@Nullable String userId) throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + NimbulaMethod.class.getName() + ".discover(" + userId + ")");
    }/*  www  .  ja  v  a  2 s .c om*/
    try {
        authenticate();

        ProviderContext ctx = cloud.getContext();

        if (ctx == null) {
            throw new CloudException("No context was set for this request");
        }

        String target = "/" + ctx.getAccountNumber() + "/";

        if (userId != null) {
            target = target + userId + "/";
        }
        target = url + target;

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [GET (" + (new Date()) + ")] -> " + target
                    + " >--------------------------------------------------------------------------------------");
        }
        try {
            HttpClient client = getClient(ctx, target.startsWith("https"));
            HttpGet get = new HttpGet(target);

            get.addHeader("Accept", "application/nimbula-v2+directory+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 != 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() + ".discover()");
        }
    }
}

From source file:com.ibm.sbt.service.basic.ProxyService.java

public void prepareResponse(HttpRequestBase method, HttpServletRequest request, HttpServletResponse response,
        HttpResponse clientResponse, boolean isCopy) throws ServletException {
    Object timedObject = ProxyProfiler.getTimedObject();
    try {/*from  ww w.jav  a2s  . c  om*/
        int statusCode = clientResponse.getStatusLine().getStatusCode();
        if (statusCode == 401 || statusCode == 403) {
            clientResponse.setHeader("WWW-Authenticate", "");
        }
        response.setStatus(statusCode);
        if (getDebugHook() != null) {
            getDebugHook().getDumpResponse().setStatus(statusCode);
        }

        // Passed back all heads, but process cookies differently.
        Header[] headers = clientResponse.getAllHeaders();
        for (Header header : headers) {
            String headername = header.getName();

            if (headername.equalsIgnoreCase("Set-Cookie")) { // $NON-NLS-1$
                if (forwardCookies(method, request)) {
                    // If cookie, have to rewrite domain/path for browser.
                    String setcookieval = header.getValue();

                    if (setcookieval != null) {
                        String thisserver = request.getServerName();

                        String thisdomain;
                        if (thisserver.indexOf('.') == -1) {
                            thisdomain = "";
                        } else {
                            thisdomain = thisserver.substring(thisserver.indexOf('.'));
                        }
                        String domain = null;

                        // path info = /protocol/server/path-on-server
                        //Matcher m = cookiePathPattern.matcher(request.getPathInfo());
                        String thispath = request.getContextPath() + request.getServletPath();
                        String path = null;

                        String[][] cookparams = getCookieStrings(setcookieval);

                        for (int j = 1; j < cookparams.length; j++) {
                            if ("domain".equalsIgnoreCase(cookparams[j][0])) { // $NON-NLS-1$
                                domain = cookparams[j][1];
                                cookparams[j][1] = null;
                            } else if ("path".equalsIgnoreCase(cookparams[j][0])) { // $NON-NLS-1$
                                path = cookparams[j][1];
                                cookparams[j][1] = null;
                            }
                        }

                        if (domain == null) {
                            domain = method.getURI().getHost();
                        }

                        // Set cookie name
                        String encoded = encodeCookieNameAndPath(cookparams[0][0], path, domain);
                        if (encoded != null) {
                            String newcookiename = PASSTHRUID + encoded;

                            StringBuilder newset = new StringBuilder(newcookiename);
                            newset.append('=');
                            newset.append(cookparams[0][1]);

                            for (int j = 1; j < cookparams.length; j++) {
                                String settingname = cookparams[j][0];
                                String settingvalue = cookparams[j][1];
                                if (settingvalue != null) {
                                    newset.append("; ").append(settingname); // $NON-NLS-1$
                                    newset.append('=').append(settingvalue); // $NON-NLS-1$
                                }
                            }

                            newset.append("; domain=").append(thisdomain); // $NON-NLS-1$
                            newset.append("; path=").append(thispath); // $NON-NLS-1$

                            String newsetcookieval = newset.toString();
                            // this implementation of HttpServletRequest seems to have issues... setHeader works as I would
                            // expect addHeader to.
                            response.setHeader(headername, newsetcookieval);
                            if (getDebugHook() != null) {
                                getDebugHook().getDumpResponse().addCookie(headername, newsetcookieval);
                            }
                        }
                    }
                }
            } else if (!headername.equalsIgnoreCase("Transfer-Encoding")) { // $NON-NLS-1$
                String headerval = header.getValue();

                if (headername.equalsIgnoreCase("content-type")) {
                    int loc = headerval.indexOf(';');
                    String type;
                    if (loc > 0) {
                        type = headerval.substring(0, loc).trim();
                    } else {
                        type = headerval;
                    }
                    if (!isMimeTypeAllowed(type)) {
                        isCopy = false;
                        break;
                    } else {
                        response.setHeader(headername, headerval);
                        if (getDebugHook() != null) {
                            getDebugHook().getDumpResponse().addHeader(headername, headerval);
                        }
                    }
                } else if ((statusCode == 401 || statusCode == 403)
                        && headername.equalsIgnoreCase("WWW-Authenticate")) { // $NON-NLS-1$
                    if (headerval.indexOf("Basic") != -1) { // $NON-NLS-1$
                        String pathInfo = request.getPathInfo();
                        String[] pathParts = (pathInfo.startsWith("/") ? pathInfo.substring(1) : pathInfo)
                                .split("/");
                        if (pathParts.length > 1) {
                            StringBuilder strb = new StringBuilder("Basic realm=\""); // $NON-NLS-1$
                            strb.append(request.getContextPath());
                            strb.append(request.getServletPath());
                            strb.append('/');
                            strb.append(pathParts[0]);
                            strb.append('/');
                            strb.append(pathParts[1]);
                            strb.append('"');
                            headerval = strb.toString();
                            response.setHeader(headername, headerval);
                            if (getDebugHook() != null) {
                                getDebugHook().getDumpResponse().addHeader(headername, headerval);
                            }
                        }
                    }
                } else {
                    response.setHeader(headername, headerval);
                    if (getDebugHook() != null) {
                        getDebugHook().getDumpResponse().addHeader(headername, headerval);
                    }
                }
            }
        }

        // Need to move response body over too
        if (statusCode == HttpServletResponse.SC_NO_CONTENT
                || statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
            response.setHeader("Content-Length", "0");
            if (getDebugHook() != null) {
                getDebugHook().getDumpResponse().addHeader("Content-Length", "0");
            }
        } else if (isCopy) {
            HttpEntity entity = clientResponse.getEntity();
            InputStream inStream = entity.getContent();
            if (inStream != null) {
                OutputStream os = response.getOutputStream();
                if (TRACE) {
                    OutputStream tos = new TraceOutputStream(os, System.out, false);
                    os = tos;
                }
                StreamUtil.copyStream(inStream, os);
                os.flush();
            } else {
                response.setHeader("Content-Length", "0");
                if (getDebugHook() != null) {
                    getDebugHook().getDumpResponse().addHeader("Content-Length", "0");
                }
            }
        }
    } catch (IOException ex) {
        throw new ServletException(ex);
    }
    ProxyProfiler.profileTimedRequest(timedObject, "prepareResponse");
}

From source file:com.basetechnology.s0.agentserver.appserver.HandleGet.java

public boolean handleGet() throws IOException, ServletException, AgentAppServerException, AgentServerException,
        InterruptedException, SymbolException, JSONException {
    // Extract out commonly used info
    String path = httpInfo.path;//from  www .ja v a  2  s . c om
    String[] pathParts = httpInfo.pathParts;
    Request request = httpInfo.request;
    HttpServletResponse response = httpInfo.response;
    AgentServer agentServer = httpInfo.agentServer;
    String lcPath = path.toLowerCase();

    if (path.equalsIgnoreCase("/about")) {
        log.info("Getting about info");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        JSONObject aboutJson = new JsonListMap();
        aboutJson.put("name", agentServer.config.get("name"));
        aboutJson.put("software", agentServer.config.get("software"));
        aboutJson.put("version", agentServer.config.get("version"));
        aboutJson.put("description", agentServer.config.get("description"));
        aboutJson.put("website", agentServer.config.get("website"));
        aboutJson.put("contact", agentServer.config.get("contact"));
        setOutput(aboutJson);
    } else if (path.equalsIgnoreCase("/evaluate")) {
        try {
            BufferedReader reader = request.getReader();
            String expressionString = null;
            try {
                StringBuilder builder = new StringBuilder();
                char[] buffer = new char[8192];
                int read;
                while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
                    builder.append(buffer, 0, read);
                }
                expressionString = builder.toString();
            } catch (Exception e) {
                log.info("Exception reading expression text : " + e);
            }

            log.info("Evaluating expression: " + expressionString);
            AgentDefinition dummyAgentDefinition = new AgentDefinition(agentServer);
            AgentInstance dummyAgentInstance = new AgentInstance(dummyAgentDefinition);
            ScriptParser parser = new ScriptParser(dummyAgentInstance);
            ScriptRuntime scriptRuntime = new ScriptRuntime(dummyAgentInstance);
            ExpressionNode expressionNode = parser.parseExpressionString(expressionString);
            Value valueNode = scriptRuntime.evaluateExpression(expressionString, expressionNode);
            String resultString = valueNode.getStringValue();

            response.setContentType("text/plain; charset=utf-8");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().println(resultString);
        } catch (Exception e) {
            log.info("Evaluate Exception: " + e);
        }
        ((Request) request).setHandled(true);
    } else if (path.equalsIgnoreCase("/run")) {
        try {
            BufferedReader reader = request.getReader();
            String scriptString = null;
            try {
                StringBuilder builder = new StringBuilder();
                char[] buffer = new char[8192];
                int read;
                while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
                    builder.append(buffer, 0, read);
                }
                scriptString = builder.toString();
            } catch (Exception e) {
                log.info("Exception reading script text : " + e);
            }

            log.info("Running script: " + scriptString);
            AgentDefinition dummyAgentDefinition = new AgentDefinition(agentServer);
            AgentInstance dummyAgentInstance = new AgentInstance(dummyAgentDefinition);
            ScriptParser parser = new ScriptParser(dummyAgentInstance);
            ScriptRuntime scriptRuntime = new ScriptRuntime(dummyAgentInstance);
            ScriptNode scriptNode = parser.parseScriptString(scriptString);
            Value valueNode = scriptRuntime.runScript(scriptString, scriptNode);
            String resultString = valueNode.getStringValue();
            log.info("Script result: " + resultString);

            response.setContentType("text/plain; charset=utf-8");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().println(resultString);
        } catch (Exception e) {
            log.info("Run Exception: " + e);
        }
        ((Request) request).setHandled(true);
    } else if (path.equalsIgnoreCase("/status")) {
        log.info("Getting status info");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);

        // Sleep a little to assure status reflects any recent operation
        Thread.sleep(100);

        // Get the status info
        JSONObject aboutJson = new JsonListMap();
        AgentScheduler agentScheduler = AgentScheduler.singleton;
        aboutJson.put("status", agentScheduler == null ? "shutdown" : agentScheduler.getStatus());
        aboutJson.put("since", DateUtils.toRfcString(agentServer.startTime));
        aboutJson.put("num_registered_users", agentServer.users.size());
        int numActiveUsers = 0;
        for (NameValue<AgentInstanceList> agentInstanceListNameValue : agentServer.agentInstances)
            if (agentInstanceListNameValue.value.size() > 0)
                numActiveUsers++;
        aboutJson.put("num_active_users", numActiveUsers);
        int num_registered_agents = 0;
        for (NameValue<AgentDefinitionList> agentDefinitionListNameValue : agentServer.agentDefinitions)
            num_registered_agents += agentDefinitionListNameValue.value.size();
        aboutJson.put("num_registered_agents", num_registered_agents);
        int num_active_agents = 0;
        for (NameValue<AgentInstanceList> agentInstanceListNameValue : agentServer.agentInstances)
            num_active_agents += agentInstanceListNameValue.value.size();
        aboutJson.put("num_active_agents", num_active_agents);
        response.getWriter().println(aboutJson.toString(4));
    } else if (path.equalsIgnoreCase("/config")) {
        log.info("Getting configuration settings");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);

        // Get the config info
        JSONObject configJson = agentServer.config.toJson();

        response.getWriter().println(configJson.toString(4));
    } else if (path.equalsIgnoreCase("/agent_definitions")) {
        checkAdminAccess();
        log.info("Getting list of agent definitions");
        JSONArray agentDefinitionsArrayJson = new JSONArray();
        // Get all agents for all users
        for (NameValue<AgentDefinitionList> userAgentDefinitions : agentServer.agentDefinitions) {
            // Get all agents for this user
            for (AgentDefinition agentDefinition : agentServer.agentDefinitions
                    .get(userAgentDefinitions.name)) {
                // Generate JSON for short summary of agent definition
                JSONObject agentDefinitionJson = new JsonListMap();
                agentDefinitionJson.put("user", agentDefinition.user.id);
                agentDefinitionJson.put("name", agentDefinition.name);
                agentDefinitionJson.put("description", agentDefinition.description);
                agentDefinitionsArrayJson.put(agentDefinitionJson);
            }
        }
        JSONObject agentDefinitionsJson = new JSONObject();
        agentDefinitionsJson.put("agent_definitions", agentDefinitionsArrayJson);
        setOutput(agentDefinitionsJson);
    } else if (path.equalsIgnoreCase("/agents")) {
        checkAdminAccess();
        log.info("Getting list of agent instances for all users");
        JSONArray agentInstancesArrayJson = new JSONArray();
        // Get all agents for all users
        for (NameValue<AgentInstanceList> userAgentInstances : agentServer.agentInstances) {
            // Get all agents for this user
            for (AgentInstance agentInstance : agentServer.agentInstances.get(userAgentInstances.name)) {
                // Generate JSON for short summary of agent instance
                JSONObject agentInstanceJson = new JsonListMap();
                agentInstanceJson.put("user", agentInstance.user.id);
                agentInstanceJson.put("name", agentInstance.name);
                agentInstanceJson.put("definition", agentInstance.agentDefinition.name);
                agentInstanceJson.put("description", agentInstance.description);
                agentInstancesArrayJson.put(agentInstanceJson);
            }
        }
        JSONObject agentInstancesJson = new JSONObject();
        agentInstancesJson.put("agent_instances", agentInstancesArrayJson);
        setOutput(agentInstancesJson);
    } else if (path.equalsIgnoreCase("/field_types")) {
        try {
            log.info("Getting list of field types");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(HttpServletResponse.SC_OK);
            JSONArray fieldTypesArrayJson = new JSONArray();
            for (String fieldType : Field.types)
                fieldTypesArrayJson.put(fieldType);
            JSONObject fieldTypesJson = new JSONObject();
            fieldTypesJson.put("field_types", fieldTypesArrayJson);
            response.getWriter().println(fieldTypesJson.toString(4));
        } catch (JSONException e) {
            throw new AgentServerException("JSON error generating JSON for agent definition status - " + e);
        }
        return true;
    } else if (path.equalsIgnoreCase("/usage")) {
        log.info("Getting API usage summary text");

        // Get text of API usage summary, api_usage.txt
        // TODO: Where to read the file from... ./doc or???
        String apiUsageText = FileUtils.readFileToString(new File("./doc/api_usage.txt"));

        // Return the text
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().println(apiUsageText);
    } else if (path.equalsIgnoreCase("/users")) {
        checkAdminAccess();
        log.info("Getting list of all user ids");
        JSONArray usersArrayJson = new JSONArray();
        for (NameValue<User> userIdValue : agentServer.users) {
            User user = userIdValue.value;
            JSONObject userJson = new JSONObject();
            userJson.put("id", user.id);
            userJson.put("display_name",
                    user.incognito ? "(Incognito)" : (user.displayName == null ? "" : user.displayName));
            usersArrayJson.put(userJson);
        }
        JSONObject usersJson = new JSONObject();
        usersJson.put("users", usersArrayJson);
        setOutput(usersJson);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*$")) {
        User user = checkUserAccess(false);
        log.info("Getting detailed info for a specified user Id: " + user.id);
        setOutput(user.toJson());
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agent_definitions$")) {
        User user = checkUserAccess(false);
        log.info("Getting list of all agent definitions for user Id: " + user.id);

        // Get all agents for this user
        JSONArray agentDefinitionsArrayJson = new JSONArray();
        for (AgentDefinition agentDefinition : agentServer.agentDefinitions.get(user.id)) {
            // Generate JSON for short summary of agent definition
            JSONObject agentDefinitionJson = new JsonListMap();
            agentDefinitionJson.put("user", agentDefinition.user.id);
            agentDefinitionJson.put("name", agentDefinition.name);
            agentDefinitionJson.put("description", agentDefinition.description);
            agentDefinitionsArrayJson.put(agentDefinitionJson);
        }
        JSONObject agentDefinitionsJson = new JSONObject();
        agentDefinitionsJson.put("agent_definitions", agentDefinitionsArrayJson);
        setOutput(agentDefinitionsJson);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agent_definitions/[a-zA-Z0-9_.@\\-]*$")) {
        User user = checkUserAccess(false);
        String agentName = pathParts[4];
        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent definition name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent definition name path parameter");
        if (!agentServer.agentDefinitions.get(user.id).containsKey(agentName))
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "No agent definition with that name for that user");

        log.info("Getting definition for agent definition " + agentName + " for user: " + user.id);
        AgentDefinitionList agentMap = agentServer.agentDefinitions.get(user.id);
        AgentDefinition agentDefinition = agentMap.get(agentName);
        setOutput(agentDefinition.toJson());
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agent_definitions/[a-zA-Z0-9_.@\\-]*/status$")) {
        User user = checkUserAccess(false);
        String agentName = pathParts[4];

        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent definition name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent definition name path parameter");
        if (!agentServer.agentDefinitions.get(user.id).containsKey(agentName))
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "No agent definition with that name for that user");

        log.info("Getting status for agent definition " + agentName + " for user: " + user.id);
        AgentDefinitionList agentMap = agentServer.agentDefinitions.get(user.id);
        AgentDefinition agent = agentMap.get(agentName);
        JSONObject statusJson = new JSONObject();
        statusJson.put("user_id", user.id);
        statusJson.put("name", agent.name);
        statusJson.put("created", DateUtils.toRfcString(agent.timeCreated));
        statusJson.put("modified", DateUtils.toRfcString(agent.timeModified));
        int numActiveInstances = 0;
        for (NameValue<AgentInstanceList> agentInstanceListNameValue : agentServer.agentInstances)
            for (AgentInstance agentInstance : agentInstanceListNameValue.value)
                if (agentInstance.agentDefinition == agent)
                    numActiveInstances++;
        statusJson.put("num_active_instances", numActiveInstances);
        setOutput(statusJson);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agents$")) {
        User user = checkUserAccess(false);
        log.info("Getting list of all agent instances for a user");

        // Get all agents for this user
        JSONArray agentInstancesArrayJson = new JSONArray();
        for (AgentInstance agentInstance : agentServer.agentInstances.get(user.id)) {
            // Generate JSON for short summary of agent instance
            JSONObject agentInstanceJson = new JsonListMap();
            agentInstanceJson.put("user", agentInstance.user.id);
            agentInstanceJson.put("name", agentInstance.name);
            agentInstanceJson.put("definition", agentInstance.agentDefinition.name);
            // TODO: Add the SHA for this instance
            agentInstanceJson.put("description", agentInstance.description);
            agentInstancesArrayJson.put(agentInstanceJson);
        }
        JSONObject agentInstancesJson = new JSONObject();
        agentInstancesJson.put("agent_instances", agentInstancesArrayJson);
        setOutput(agentInstancesJson);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agents/[a-zA-Z0-9_.@\\-]*$")) {
        User user = checkUserAccess(false);
        String agentName = pathParts[4];
        String stateString = request.getParameter("state");
        boolean includeState = stateString != null && (stateString.equalsIgnoreCase("true")
                || stateString.equalsIgnoreCase("yes") || stateString.equalsIgnoreCase("on"));
        String countString = request.getParameter("count");
        int count = -1;
        if (countString != null && countString.trim().length() > 0)
            count = Integer.parseInt(countString);

        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent instance name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent instance name path parameter");
        if (!agentServer.agentInstances.get(user.id).containsKey(agentName))
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "No agent instance with that name for that user");

        log.info("Getting detail info for agent instance " + agentName + " for user: " + user.id);
        AgentInstance agentInstance = agentServer.agentInstances.get(user.id).get(agentName);

        setOutput(agentInstance.toJson(includeState, count));
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agents/[a-zA-Z0-9_.@\\-]*/notifications$")) {
        User user = checkUserAccess(false);
        String agentName = pathParts[4];

        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent instance name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent instance name path parameter");
        if (!agentServer.agentInstances.get(user.id).containsKey(agentName))
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "No agent instance with that name for that user");

        log.info("Getting current pending notification for agent instance " + agentName + " for user: "
                + user.id);
        AgentInstanceList agentMap = agentServer.agentInstances.get(user.id);
        AgentInstance agent = agentMap.get(agentName);

        // Build a JSON array of all pending notifications for agent
        JSONArray pendingNotificationsJson = new JSONArray();
        for (String notificationName : agent.notifications) {
            NotificationInstance notificationInstance = agent.notifications.get(notificationName);
            if (notificationInstance.pending) {
                // Generate and return a summary of the notification
                JSONObject notificationSummaryJson = new JsonListMap();
                notificationSummaryJson.put("agent", agent.name);
                notificationSummaryJson.put("name", notificationInstance.definition.name);
                notificationSummaryJson.put("description", notificationInstance.definition.description);
                notificationSummaryJson.put("details", notificationInstance.details.toJsonObject());
                notificationSummaryJson.put("type", notificationInstance.definition.type);
                notificationSummaryJson.put("time", DateUtils.toRfcString(notificationInstance.timeNotified));
                notificationSummaryJson.put("timeout", notificationInstance.timeout);
                pendingNotificationsJson.put(notificationSummaryJson);
            }
        }

        // Build a wrapper object for the array
        JSONObject wrapperJson = new JSONObject();
        wrapperJson.put("pending_notifications", pendingNotificationsJson);

        // Return the wrapped list
        setOutput(wrapperJson);
    } else if (lcPath.matches(
            "^/users/[a-zA-Z0-9_.@\\-]*/agents/[a-zA-Z0-9_.@\\-]*/notifications/[a-zA-Z0-9_.@\\-]*$")) {
        User user = checkUserAccess(false);
        String agentName = pathParts[4];
        // TODO: Maybe if path ends with "/", should be treated as GET of list of pending notifications
        String notificationName = pathParts.length >= 7 ? pathParts[6] : null;
        String responseParam = request.getParameter("response");
        String responseChoice = request.getParameter("response_choice");
        String comment = request.getParameter("comment");

        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent instance name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent instance name path parameter");
        if (!agentServer.agentInstances.get(user.id).containsKey(agentName))
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "No agent instance with that name for that user");
        if (notificationName == null)
            throw new AgentAppServerBadRequestException("Missing notification name path parameter");
        if (notificationName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty notification name path parameter");

        // Access the named notification
        AgentInstanceList agentMap = agentServer.agentInstances.get(user.id);
        AgentInstance agent = agentMap.get(agentName);
        NotificationInstance notificationInstance = agent.notifications.get(notificationName);
        if (notificationInstance == null)
            throw new AgentAppServerBadRequestException(
                    "Undefined notification name for agent instance '" + agentName + "': " + notificationName);

        // If no response, simply return info about the notification
        if (responseParam == null) {
            // Generate and return a summary of the notification
            JSONObject notificationSummaryJson = new JsonListMap();
            notificationSummaryJson.put("agent", agent.name);
            notificationSummaryJson.put("name", notificationInstance.definition.name);
            notificationSummaryJson.put("description", notificationInstance.definition.description);
            notificationSummaryJson.put("details", notificationInstance.details.toJsonObject());
            notificationSummaryJson.put("type", notificationInstance.definition.type);
            notificationSummaryJson.put("time", DateUtils.toRfcString(notificationInstance.timeNotified));
            notificationSummaryJson.put("timeout", notificationInstance.timeout);
            setOutput(notificationSummaryJson);
        } else {
            if (responseParam.trim().length() == 0)
                throw new AgentAppServerBadRequestException("Empty response query parameter");
            if (!NotificationInstance.responses.contains(responseParam))
                throw new AgentAppServerBadRequestException("Unknown response keyword query parameter");
            if (!notificationInstance.pending)
                throw new AgentAppServerBadRequestException(
                        "Cannot respond to notification '" + notificationName + "' for agent instance '"
                                + agentName + "' since it is not pending");

            log.info("Respond to a pending notification '" + notificationName + "' for agent instance "
                    + agentName + " for user: " + user.id);

            agent.respondToNotification(notificationInstance, responseParam, responseChoice, comment);

            // Done
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agents/[a-zA-Z0-9_.@\\-]*/output$")) {
        String userId = pathParts[2];
        String agentName = pathParts[4];

        if (userId == null)
            throw new AgentAppServerBadRequestException("Missing user Id path parameter");
        if (userId.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty user Id path parameter");
        if (!agentServer.users.containsKey(userId))
            throw new AgentAppServerBadRequestException("Unknown user name or invalid password");
        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent instance name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent instance name path parameter");
        if (!agentServer.agentInstances.get(userId).containsKey(agentName))
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "No agent instance with that name for that user");

        // Password not required for "public output" instances
        AgentInstance agent = agentServer.agentInstances.get(userId).get(agentName);
        User user = null;
        if (!agent.publicOutput)
            user = checkUserAccess(false);

        log.info("Getting output for agent instance " + agentName + " for user: " + userId);

        // Build a JSON object equivalent to map of output fields
        JSONObject outputJson = new JsonListMap();
        SymbolValues outputValues = agent.categorySymbolValues.get("outputs");
        for (Symbol outputSymbol : outputValues) {
            String fieldName = outputSymbol.name;
            outputJson.put(fieldName, agent.getOutput(fieldName).toJsonObject());
        }

        setOutput(outputJson);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agents/[a-zA-Z0-9_.@\\-]*/output_history$")) {
        User user = checkUserAccess(false);
        String agentName = pathParts[4];
        String countString = request.getParameter("count");
        int count = countString == null ? -1 : Integer.parseInt(countString);

        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent instance name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent instance name path parameter");
        if (!agentServer.agentInstances.get(user.id).containsKey(agentName))
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "No agent instance with that name for that user");

        log.info("Getting output history for agent instance " + agentName + " for user: " + user.id);
        AgentInstanceList agentMap = agentServer.agentInstances.get(user.id);
        AgentInstance agent = agentMap.get(agentName);

        // Limit or default the user's specified count
        if (count <= 0)
            count = agent.defaultOutputCount;
        if (count > agent.outputLimit)
            count = agent.outputLimit;
        int outputSize = agent.outputHistory.size();
        if (count > outputSize)
            count = outputSize;

        // Compute starting history index
        int start = outputSize - count;

        int n = agent.outputHistory.size();
        if (n > 4) {
            SymbolValues s1 = agent.outputHistory.get(n - 2).output;
            SymbolValues s2 = agent.outputHistory.get(n - 1).output;
            boolean eq = s1.equals(s2);
        }

        // Build a JSON array of output rows
        JSONArray outputJson = new JSONArray();
        for (int i = start; i < outputSize; i++) {
            OutputRecord outputs = agent.outputHistory.get(i);
            outputJson.put(outputs.output.toJson());
        }

        // Wrap the array in an object since that is what output code expects
        JSONObject outputHistory = new JsonListMap();
        outputHistory.put("output_history", outputJson);
        setOutput(outputHistory);
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agents/[a-zA-Z0-9_.@\\-]*/state$")) {
        User user = checkUserAccess(false);
        String agentName = pathParts[4];
        String countString = request.getParameter("count");

        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent instance name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent instance name path parameter");
        if (!agentServer.agentInstances.get(user.id).containsKey(agentName))
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "No agent instance with that name for that user");

        int count = -1;
        if (countString != null && countString.trim().length() > 0)
            count = Integer.parseInt(countString);

        log.info(
                "Getting full state and detail info for agent instance " + agentName + " for user: " + user.id);
        AgentInstanceList agentMap = agentServer.agentInstances.get(user.id);
        AgentInstance agentInstance = agentMap.get(agentName);
        setOutput(agentInstance.toJson(true, count));
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-]*/agents/[a-zA-Z0-9_.@\\-]*/status$")) {
        User user = checkUserAccess(false);
        String agentName = pathParts[4];
        String stateString = request.getParameter("state");
        boolean includeState = stateString != null && (stateString.equalsIgnoreCase("true")
                || stateString.equalsIgnoreCase("yes") || stateString.equalsIgnoreCase("on"));
        String countString = request.getParameter("count");
        int count = -1;
        if (countString != null && countString.trim().length() > 0)
            count = Integer.parseInt(countString);

        if (agentName == null)
            throw new AgentAppServerBadRequestException("Missing agent instance name path parameter");
        if (agentName.trim().length() == 0)
            throw new AgentAppServerBadRequestException("Empty agent instance name path parameter");
        if (!agentServer.agentInstances.get(user.id).containsKey(agentName))
            throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                    "No agent instance with that name for that user");

        log.info("Getting status for agent instance " + agentName + " for user: " + user.id);
        /*      AgentInstanceList agentMap = agentServer.agentInstances.get(user.id);
              AgentInstance agent = agentMap.get(agentName);
              JSONObject statusJson = new JsonListMap();
              statusJson.put("user", user.id);
              statusJson.put("name", agent.name);
              statusJson.put("definition", agent.agentDefinition.name);
              statusJson.put("description", agent.description);
              statusJson.put("status", agent.getStatus());
              statusJson.put("instantiated", DateUtils.toRfcString(agent.timeInstantiated));
              long lastUpdated = agent.timeUpdated;
              statusJson.put("updated", lastUpdated > 0 ? DateUtils.toRfcString(lastUpdated) : "");
              long lastInputsChanged = agent.lastInputsChanged;
              statusJson.put("inputs_changed", lastInputsChanged > 0 ? DateUtils.toRfcString(lastInputsChanged) : "");
              long lastTriggered = agent.lastTriggered;
              statusJson.put("triggered", lastTriggered > 0 ? DateUtils.toRfcString(lastTriggered) : "");
              int outputsSize = agent.outputHistory.size();
              long lastOutput = outputsSize > 0 ? agent.outputHistory.get(outputsSize - 1).time : 0;
              statusJson.put("outputs_changed", lastOutput > 0 ? DateUtils.toRfcString(lastOutput) : "");
                      
              // Done
              setOutput(statusJson);
              */
        AgentInstanceList agentMap = agentServer.agentInstances.get(user.id);
        AgentInstance agentInstance = agentMap.get(agentName);
        setOutput(agentInstance.toJson(includeState, count));
    } else if (lcPath.matches("^/users/[a-zA-Z0-9_.@\\-*]*/website_access$")) {
        User user = checkAdminUserAccess();

        log.info("Getting web site access controls for user: " + user.id);

        // Get the access control list for the user
        ListMap<String, String> accessList = agentServer.getWebSiteAccessControls(user);

        // Put the list in JSON format
        JSONObject accessListJson = new JSONObject();
        for (String url : accessList)
            accessListJson.put(url, accessList.get(url));

        // Done
        setOutput(accessListJson);
    } else {
        throw new AgentAppServerException(HttpServletResponse.SC_NOT_FOUND,
                "Path does not address any existing object");
    }
    return true;
}

From source file:com.zimbra.cs.service.FileUploadServlet.java

@SuppressWarnings("unchecked")
List<Upload> handleMultipartUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct,
        boolean limitByFileUploadMaxSize, AuthToken at, boolean csrfCheckComplete)
        throws IOException, ServiceException {
    List<FileItem> items = null;
    String reqId = null;//w  w w.j  a  v  a  2  s.  c o  m

    ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize);
    try {
        items = upload.parseRequest(req);

        if (!csrfCheckComplete && !CsrfUtil.checkCsrfInMultipartFileUpload(items, at)) {
            drainRequestStream(req);
            mLog.info("CSRF token validation failed for account: %s, Auth token is CSRF enabled",
                    acct.getName());
            sendResponse(resp, HttpServletResponse.SC_UNAUTHORIZED, fmt, null, null, items);
            return Collections.emptyList();
        }
    } catch (FileUploadBase.SizeLimitExceededException e) {
        // at least one file was over max allowed size
        mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, reqId, null, items);
        return Collections.emptyList();
    } catch (FileUploadBase.InvalidContentTypeException e) {
        // at least one file was of a type not allowed
        mLog.info("File upload failed", e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, fmt, reqId, null, items);
        return Collections.emptyList();
    } catch (FileUploadException e) {
        // parse of request failed for some other reason
        mLog.info("File upload failed", e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, reqId, null, items);
        return Collections.emptyList();
    }

    String charset = "utf-8";
    LinkedList<String> names = new LinkedList<String>();
    HashMap<FileItem, String> filenames = new HashMap<FileItem, String>();
    if (items != null) {
        for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
            FileItem fi = it.next();
            if (fi == null)
                continue;

            if (fi.isFormField()) {
                if (fi.getFieldName().equals("requestId")) {
                    // correlate this file upload session's request and response
                    reqId = fi.getString();
                } else if (fi.getFieldName().equals("_charset_") && !fi.getString().equals("")) {
                    // get the form value charset, if specified
                    charset = fi.getString();
                } else if (fi.getFieldName().startsWith("filename")) {
                    // allow a client to explicitly provide filenames for the uploads
                    names.clear();
                    String value = fi.getString(charset);
                    if (!Strings.isNullOrEmpty(value)) {
                        for (String name : value.split("\n")) {
                            names.add(name.trim());
                        }
                    }
                }
                // strip form fields out of the list of uploads
                it.remove();
            } else {
                if (fi.getName() == null || fi.getName().trim().equals("")) {
                    it.remove();
                } else {
                    filenames.put(fi, names.isEmpty() ? null : names.remove());
                }
            }
        }
    }

    // restrict requestId value for safety due to later use in javascript
    if (reqId != null && reqId.length() != 0) {
        if (!ALLOWED_REQUESTID_CHARS.matcher(reqId).matches()) {
            mLog.info("Rejecting upload with invalid chars in reqId: %s", reqId);
            sendResponse(resp, HttpServletResponse.SC_BAD_REQUEST, fmt, null, null, items);
            return Collections.emptyList();
        }
    }

    // empty upload is not a "success"
    if (items == null || items.isEmpty()) {
        mLog.info("No data in upload for reqId: %s", reqId);
        sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, reqId, null, items);
        return Collections.emptyList();
    }

    // cache the uploaded files in the hash and construct the list of upload IDs
    List<Upload> uploads = new ArrayList<Upload>(items.size());
    for (FileItem fi : items) {
        String name = filenames.get(fi);
        if (name == null || name.trim().equals(""))
            name = fi.getName();
        Upload up = new Upload(acct.getId(), fi, name);

        mLog.info("Received multipart: %s", up);
        synchronized (mPending) {
            mPending.put(up.uuid, up);
        }
        uploads.add(up);
    }

    sendResponse(resp, HttpServletResponse.SC_OK, fmt, reqId, uploads, items);
    return uploads;
}

From source file:org.dasein.cloud.rackspace.AbstractMethod.java

@SuppressWarnings("unused")
protected @Nullable String postHeaders(@Nonnull String authToken, @Nonnull String endpoint,
        @Nonnull String resource, @Nonnull Map<String, String> customHeaders)
        throws CloudException, InternalException {
    Logger std = RackspaceCloud.getLogger(RackspaceCloud.class, "std");
    Logger wire = RackspaceCloud.getLogger(RackspaceCloud.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + AbstractMethod.class.getName() + ".postString(" + authToken + "," + endpoint
                + "," + resource + "," + customHeaders + ")");
    }//from  ww  w . j  a v  a2s . com
    if (wire.isDebugEnabled()) {
        wire.debug("---------------------------------------------------------------------------------"
                + endpoint + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        HttpPost post = new HttpPost(endpoint + resource);

        post.addHeader("Content-Type", "application/json");
        post.addHeader("X-Auth-Token", authToken);
        if (customHeaders != null) {
            for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
                String val = (entry.getValue() == null ? "" : entry.getValue());

                post.addHeader(entry.getKey(), val);
            }
        }

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

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

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

        if (code != HttpServletResponse.SC_ACCEPTED && code != HttpServletResponse.SC_NO_CONTENT) {
            std.error("postString(): Expected ACCEPTED for POST request, got " + code);
            HttpEntity entity = response.getEntity();
            String json = null;

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

                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                        wire.debug("");
                    }
                } catch (IOException e) {
                    throw new CloudException(e);
                }
            }
            RackspaceException.ExceptionItems items = (json == null ? null
                    : RackspaceException.parseException(code, json));

            if (items == null) {
                items = new RackspaceException.ExceptionItems();
                items.code = 404;
                items.type = CloudErrorType.COMMUNICATION;
                items.message = "itemNotFound";
                items.details = "No such object: " + resource;
            }
            std.error("postString(): [" + code + " : " + items.message + "] " + items.details);
            throw new RackspaceException(items);
        } else {
            if (code == HttpServletResponse.SC_ACCEPTED) {
                HttpEntity entity = response.getEntity();
                String json = null;

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

                        if (wire.isDebugEnabled()) {
                            wire.debug(json);
                            wire.debug("");
                        }
                    } catch (IOException e) {
                        throw new CloudException(e);
                    }
                }
                if (json != null && !json.trim().equals("")) {
                    return json;
                }
            }
            return null;
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + AbstractMethod.class.getName() + ".postString()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("---------------------------------------------------------------------------------"
                    + endpoint + resource);
        }
    }
}

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

private void processServerGc(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    System.gc();//from  w w w  . j  av  a 2s .  co  m
    resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
}

From source file:com.zimbra.cs.service.FileUploadServlet.java

/**
 * This is used when handling a POST request generated by {@link ZMailbox#uploadContentAsStream}
 *
 * @param req//from   w  ww .j  av a2s  .co  m
 * @param resp
 * @param fmt
 * @param acct
 * @param limitByFileUploadMaxSize
 * @return
 * @throws IOException
 * @throws ServiceException
 */
List<Upload> handlePlainUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct,
        boolean limitByFileUploadMaxSize) throws IOException, ServiceException {
    // metadata is encoded in the response's HTTP headers
    ContentType ctype = new ContentType(req.getContentType());
    String contentType = ctype.getContentType(), filename = ctype.getParameter("name");
    if (filename == null) {
        filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename");
    }

    if (filename == null || filename.trim().equals("")) {
        mLog.info("Rejecting upload with no name.");
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, null, null, null);
        return Collections.emptyList();
    }

    // Unescape the filename so it actually displays correctly
    filename = StringEscapeUtils.unescapeHtml(filename);

    // store the fetched file as a normal upload
    ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize);
    FileItem fi = upload.getFileItemFactory().createItem("upload", contentType, false, filename);
    try {
        // write the upload to disk, but make sure not to exceed the permitted max upload size
        long size = ByteUtil.copy(req.getInputStream(), false, fi.getOutputStream(), true,
                upload.getSizeMax() * 3);
        if ((upload.getSizeMax() >= 0 /* -1 would mean "no limit" */) && (size > upload.getSizeMax())) {
            mLog.debug("handlePlainUpload(): deleting %s", fi);
            fi.delete();
            mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + acct.getId());
            drainRequestStream(req);
            sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, null, null, null);
            return Collections.emptyList();
        }
    } catch (IOException ioe) {
        mLog.warn("Unable to store upload.  Deleting %s", fi, ioe);
        fi.delete();
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, null, null, null);
        return Collections.emptyList();
    }
    List<FileItem> items = new ArrayList<FileItem>(1);
    items.add(fi);

    Upload up = new Upload(acct.getId(), fi, filename);
    mLog.info("Received plain: %s", up);
    synchronized (mPending) {
        mPending.put(up.uuid, up);
    }

    List<Upload> uploads = Arrays.asList(up);
    sendResponse(resp, HttpServletResponse.SC_OK, fmt, null, uploads, items);
    return uploads;
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Process a POST request for the specified resource.
 *
 * @throws IOException      if an input/output error occurs
 * @throws ServletException if a servlet-specified error occurs
 *//*from   w  w  w. j ava2s. co m*/
protected void doPut(ActionContext context) throws ServletException, IOException {

    //showRequestInfo(context.getRequest());

    if (readOnly) {
        context.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    String path = getRelativePath(context.getRequest());

    //Fix for MACOSX finder. Do not allow requests for files starting with a period
    if (path.indexOf("/.") > -1 || path.indexOf(".DS_Store") > -1) {
        return;
    }

    // Retrieve the resources
    Connection db = null;
    ModuleContext resources = null;
    SystemStatus thisSystem = null;
    Object object = null;

    boolean exists = true;
    boolean result = true;

    try {
        db = this.getConnection(context);
        resources = getCFSResources(db, context);

        if (resources == null) {
            context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        thisSystem = this.getSystemStatus(context);

        try {
            object = resources.lookup(thisSystem, db, path);
        } catch (NamingException e) {
            exists = false;
        }

        // Temp. content file used to support partial PUT
        File contentFile = null;

        // Input stream for temp. content file used to support partial PUT
        FileInputStream contentFileInStream = null;

        //ResourceInfo resourceInfo = new ResourceInfo(thisSystem, path, resources);
        Range range = parseContentRange(context.getRequest(), context.getResponse());

        //InputStream resourceInputStream = null;
        ServletInputStream resourceInputStream = null;
        // Append data specified in ranges to existing content for this
        // resource - create a temp. file on the local filesystem to
        // perform this operation
        // Assume just one range is specified for now
        if (range != null) {
            contentFile = executePartialPut(context.getRequest(), range, path);
            //resourceInputStream = new FileInputStream(contentFile);
        } else {
            resourceInputStream = context.getRequest().getInputStream();
            //System.out.println("RESOURCE INPUT STREAM: " + resourceInputStream);
            System.out.println("CONTENT LENGTH: " + context.getRequest().getContentLength());
            //System.out.println("DATA: " + resourceInputStream.available());
        }

        try {
            Object thisObject = null;
            if (exists) {
                //resources.rebind(path, newResource);
                Resource oldResource = (Resource) object;
                oldResource.setContent(resourceInputStream);
                thisObject = resources.copyResource(thisSystem, db, path, oldResource);
            } else {
                Resource newResource = new Resource(resourceInputStream);
                thisObject = resources.copyResource(thisSystem, db, path, newResource);
            }
            if (thisObject != null) {
                processInsertHook(context, thisObject);
            }
        } catch (NamingException e) {
            //e.printStackTrace(System.out);
            result = false;
        }
    } catch (SQLException e) {
        e.printStackTrace(System.out);
    } finally {
        this.freeConnection(db, context);
    }

    if (result) {
        if (exists) {
            context.getResponse().setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            context.getResponse().setStatus(HttpServletResponse.SC_CREATED);
        }
    } else {
        context.getResponse().sendError(HttpServletResponse.SC_CONFLICT);
    }
}

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

private void processActivateUser(HttpServletRequest req, HttpServletResponse resp) {

    String username = req.getPathInfo().substring(URL_ACTIVATE.length());
    try {/*www.j  av  a 2  s  . c  om*/
        User user = userService.getUser(username);
        if (user.isActivated()) {
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        user.activate();
        userService.updateUser(user);

        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } catch (DataRetrievalFailureException e) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
}

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

public @Nonnegative int post(@Nonnull Map<String, Object> state) throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + NimbulaMethod.class.getName() + ".post(" + state + ")");
    }//from  w  ww .ja  va 2  s. c o m
    try {
        authenticate();
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [POST (" + (new Date()) + ")] -> " + url
                    + "/ >--------------------------------------------------------------------------------------");
        }
        try {
            ProviderContext ctx = cloud.getContext();

            if (ctx == null) {
                throw new CloudException("No context was set for this request");
            }
            HttpClient client = getClient(ctx, url.startsWith("https"));
            HttpPost post = new HttpPost(url + "/");

            post.setHeader("Cookie", authCookie);
            post.addHeader("Accept", "application/nimbula-v2+json");
            try {
                //noinspection deprecation
                post.setEntity(new StringEntity((new JSONObject(state)).toString(),
                        "application/nimbula-v2+json", "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new InternalException(e);
            }

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

                try {
                    wire.debug(EntityUtils.toString(post.getEntity()));
                } catch (IOException ignore) {
                }

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

            try {
                response = client.execute(post);
                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 != HttpServletResponse.SC_NO_CONTENT) {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    try {
                        this.response = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new CloudException(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(this.response);
                        wire.debug("");
                    }
                }
                checkResponse(response, code, this.response);
            } else {
                checkResponse(response, code);
            }
            return code;
        } finally {
            if (wire.isDebugEnabled()) {
                wire.debug("<<< [POST (" + (new Date()) + ")] -> " + url
                        + "/ <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + NimbulaMethod.class.getName() + ".post()");
        }
    }
}