Example usage for javax.servlet.http HttpServletResponse SC_OK

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

Introduction

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

Prototype

int SC_OK

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

Click Source Link

Document

Status code (200) indicating the request succeeded normally.

Usage

From source file:com.controller.schedule.GetScheduledEntitiesServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww w  . j av a 2 s . com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    try {
        HttpSession session = request.getSession();
        if (session.getAttribute("UID") == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "User is not logged in");
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().flush();
            return;
        }
        Integer userId = Integer.parseInt(session.getAttribute("UID").toString());
        List<String> errorMsgs = new ArrayList<>();

        if (StringUtils.isEmpty(request.getParameter("from"))) {
            errorMsgs.add("from date parameter is missing");
        }
        if (StringUtils.isEmpty(request.getParameter("to"))) {
            errorMsgs.add("to date parameter is missing");
        }

        if (!errorMsgs.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("error", errorMsgs);
            response.getWriter().write(AppConstants.GSON.toJson(responseMap));
            response.getWriter().flush();
            return;
        }

        LocalDate fromDate = null;
        LocalDate toDate = null;
        //Dates have to follow the format: 2011-12-03
        try {
            fromDate = LocalDate.parse(request.getParameter("from"));
        } catch (DateTimeParseException ex) {
            errorMsgs.add("from parameter is not in the required yyyy-mm-dd format");
            logger.log(Level.SEVERE, "", ex);
        }

        try {
            toDate = LocalDate.parse(request.getParameter("to"));
        } catch (DateTimeParseException ex) {
            errorMsgs.add("to parameter is not in the required yyyy-mm-dd format");
            logger.log(Level.SEVERE, "", ex);
        }
        if (!errorMsgs.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("error", errorMsgs);
            response.getWriter().write(AppConstants.GSON.toJson(responseMap));
            response.getWriter().flush();
            return;
        }

        JSONObject scheduledEntities = ScheduleDAO.getScheduledEntities(userId, fromDate, toDate);
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(AppConstants.GSON.toJson(scheduledEntities));
        response.getWriter().flush();
    } catch (SQLException ex) {
        Logger.getLogger(GetScheduledEntitiesServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

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  w ww.  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:org.jboss.as.test.clustering.cluster.web.authentication.FormAuthenticationWebFailoverTestCase.java

@Test
public void test(@ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws IOException, URISyntaxException {

    URI uri1 = SecureServlet.createURI(baseURL1);
    URI uri2 = SecureServlet.createURI(baseURL2);

    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
        HttpResponse response = client.execute(new HttpGet(uri1));
        try {/*from  w  ww.  ja v  a2 s. c om*/
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertNull(response.getFirstHeader(SecureServlet.SESSION_ID_HEADER));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        HttpPost login = new HttpPost(baseURL1.toURI().resolve("j_security_check"));

        List<NameValuePair> pairs = new ArrayList<>(2);
        pairs.add(new BasicNameValuePair("j_username", "allowed"));
        pairs.add(new BasicNameValuePair("j_password", "password"));

        login.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
        response = client.execute(login);
        try {
            Assert.assertEquals(HttpServletResponse.SC_FOUND, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        String sessionId = null;
        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertNotNull(response.getFirstHeader(SecureServlet.SESSION_ID_HEADER));
            sessionId = response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue();
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        undeploy(DEPLOYMENT_1);

        response = client.execute(new HttpGet(uri2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        deploy(DEPLOYMENT_1);

        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }
}

From source file:com.wso2telco.workflow.api.WorkflowHistoryAPI.java

@GET
@Path("/apis/{subscriberName}")
@Produces(MediaType.APPLICATION_JSON)// www  .  j  ava2  s .com
public Response getAPIsBySubscriber(@PathParam("subscriberName") String subscriberName) {

    String jsonPayload;
    try {
        List<String> apis = SbHostObjectUtils.getAPIsBySubscriber(subscriberName);
        jsonPayload = new Gson().toJson(apis);
    } catch (Exception e) {
        log.error(e);
        return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).build();
    }
    return Response.status(HttpServletResponse.SC_OK).entity(jsonPayload).build();
}

From source file:com.erudika.para.security.TwitterAuthFilter.java

/**
 * Handles an authentication request./*w  ww  .  j a  v a  2s.c  o  m*/
 * @param request HTTP request
 * @param response HTTP response
 * @return an authentication object that contains the principal object if successful.
 * @throws IOException ex
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    final String requestURI = request.getRequestURI();
    UserAuthentication userAuth = null;

    if (requestURI.endsWith(TWITTER_ACTION)) {
        String verifier = request.getParameter("oauth_verifier");

        if (verifier == null) {
            String callback = Utils.urlEncode(request.getRequestURL().toString());
            Map<String, String[]> params = new HashMap<String, String[]>();
            params.put("oauth_callback", new String[] { callback });

            HttpPost tokenPost = new HttpPost(FLOW_URL1);
            tokenPost.setHeader(HttpHeaders.AUTHORIZATION, OAuth1HmacSigner.sign("POST", FLOW_URL1, params,
                    Config.TWITTER_APP_ID, Config.TWITTER_SECRET, null, null));
            tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
            CloseableHttpResponse resp1 = httpclient.execute(tokenPost);

            if (resp1.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
                String decoded = EntityUtils.toString(resp1.getEntity());
                for (String pair : decoded.split("&")) {
                    if (pair.startsWith("oauth_token")) {
                        response.sendRedirect(FLOW_URL2 + pair);
                        return null;
                    }
                }
            }
        } else {
            String token = request.getParameter("oauth_token");
            Map<String, String[]> params = new HashMap<String, String[]>();
            params.put("oauth_verifier", new String[] { verifier });

            HttpPost tokenPost = new HttpPost(FLOW_URL3);
            tokenPost.setEntity(new StringEntity("oauth_verifier=" + verifier));
            tokenPost.setHeader(HttpHeaders.AUTHORIZATION, OAuth1HmacSigner.sign("POST", FLOW_URL3, params,
                    Config.TWITTER_APP_ID, Config.TWITTER_SECRET, token, null));
            tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
            CloseableHttpResponse resp2 = httpclient.execute(tokenPost);

            if (resp2.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
                String decoded = EntityUtils.toString(resp2.getEntity());
                String oauthToken = null;
                String oauthSecret = null;
                for (String pair : decoded.split("&")) {
                    if (pair.startsWith("oauth_token_secret")) {
                        oauthSecret = pair.substring(19);
                    } else if (pair.startsWith("oauth_token")) {
                        oauthToken = pair.substring(12);
                    }
                }
                userAuth = getOrCreateUser(null, oauthToken, oauthSecret);
            }
        }
    }

    User user = SecurityUtils.getAuthenticatedUser(userAuth);

    if (userAuth == null || user == null || user.getIdentifier() == null) {
        throw new BadCredentialsException("Bad credentials.");
    } else if (!user.getActive()) {
        throw new LockedException("Account is locked.");
    }
    return userAuth;
}

From source file:com.adobe.acs.commons.oak.impl.EnsureOakIndexServlet.java

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

    String forceParam = StringUtils.defaultIfEmpty(request.getParameter(PARAM_FORCE), "false");
    boolean force = Boolean.parseBoolean(forceParam);

    String path = StringUtils.stripToNull(request.getParameter(PARAM_PATH));
    try {//from   ww w.  j av  a 2  s .  c  om

        int count = 0;
        if (StringUtils.isBlank(path)) {
            count = ensureOakIndexManager.ensureAll(force);
        } else {
            count = ensureOakIndexManager.ensure(force, path);
        }

        response.setContentType("text/plain; charset=utf-8");
        response.getWriter().println("Initiated the ensuring of " + count + " oak indexes");
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (IOException e) {
        log.warn("Caught IOException while handling doPost() in the Ensure Oak Index Servlet", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.osmsurround.ae.amenity.AmenityService.java

public void updateAmenity(Node.OsmType osmType, long nodeId, Map<String, String> data,
        NewPosition newPosition) {/*from w  ww.j  a  v a 2  s . co m*/
    OsmBasicType amenity = null;
    switch (osmType) {
    case NODE:
        OsmNode amenityNode = getNode(nodeId);
        amenity = amenityNode;
        // save the original amenity position
        newPosition.setLat(Double.valueOf(amenityNode.getLat()));
        newPosition.setLon(Double.valueOf(amenityNode.getLon()));
        updateAmenityValues(amenityNode, data, newPosition);
        break;
    case WAY:
        amenity = getWay(nodeId);
        updateAmenityValues(amenity, data);
        break;
    case RELATION:
        amenity = getRelation(nodeId);
        updateAmenityValues(amenity, data);
        break;
    }

    HttpResponse httpResponse = osmUpdateRequest.execute(amenity);
    if (httpResponse.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
        Amenity amenityFromOsm = getAmenity(osmType, nodeId);
        internalDataService.updateInternalData(osmType, nodeId, amenityFromOsm);
    } else {
        throw RequestUtils.createExceptionFromHttpResponse(httpResponse);
    }
}

From source file:org.magnum.mobilecloud.video.VideoSvc.java

@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/like", method = RequestMethod.POST)
public @ResponseBody void likeVideo(@PathVariable("id") long id, HttpServletRequest request,
        HttpServletResponse response) {//from  w  w  w  .j a v a 2  s.  c  om
    Video video = videos.findOne(id);
    if (video != null) {
        Set<String> users = video.getLikesUserNames();
        String user = request.getRemoteUser();
        System.out.println("User: " + user);
        if (users.contains(user)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } else {
            users.add(user);
            video.setLikesUserNames(users);
            video.setLikes(users.size());
            videos.save(video);
            response.setStatus(HttpServletResponse.SC_OK);
        }
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:edu.uci.ics.hyracks.control.cc.web.ApplicationInstallationHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {// w ww  .  j a v  a  2 s.com
        while (target.startsWith("/")) {
            target = target.substring(1);
        }
        while (target.endsWith("/")) {
            target = target.substring(0, target.length() - 1);
        }
        String[] parts = target.split("/");
        if (parts.length != 1) {
            return;
        }
        final String[] params = parts[0].split("&");
        String deployIdString = params[0];
        String rootDir = ccs.getServerContext().getBaseDir().toString();
        final String deploymentDir = rootDir.endsWith(File.separator)
                ? rootDir + "applications/" + deployIdString
                : rootDir + File.separator + "/applications/" + File.separator + deployIdString;
        if (HttpMethods.PUT.equals(request.getMethod())) {
            class OutputStreamGetter extends SynchronizableWork {
                private OutputStream os;

                @Override
                protected void doRun() throws Exception {
                    FileUtils.forceMkdir(new File(deploymentDir));
                    String fileName = params[1];
                    File jarFile = new File(deploymentDir, fileName);
                    os = new FileOutputStream(jarFile);
                }
            }
            OutputStreamGetter r = new OutputStreamGetter();
            try {
                ccs.getWorkQueue().scheduleAndSync(r);
            } catch (Exception e) {
                throw new IOException(e);
            }
            try {
                IOUtils.copyLarge(request.getInputStream(), r.os);
            } finally {
                r.os.close();
            }
        } else if (HttpMethods.GET.equals(request.getMethod())) {
            class InputStreamGetter extends SynchronizableWork {
                private InputStream is;

                @Override
                protected void doRun() throws Exception {
                    String fileName = params[1];
                    File jarFile = new File(deploymentDir, fileName);
                    is = new FileInputStream(jarFile);
                }
            }
            InputStreamGetter r = new InputStreamGetter();
            try {
                ccs.getWorkQueue().scheduleAndSync(r);
            } catch (Exception e) {
                throw new IOException(e);
            }
            if (r.is == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            } else {
                response.setContentType("application/octet-stream");
                response.setStatus(HttpServletResponse.SC_OK);
                try {
                    IOUtils.copyLarge(r.is, response.getOutputStream());
                } finally {
                    r.is.close();
                }
            }
        }
        baseRequest.setHandled(true);
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}