Example usage for javax.servlet.http HttpServletResponse SC_BAD_REQUEST

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

Introduction

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

Prototype

int SC_BAD_REQUEST

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

Click Source Link

Document

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

Usage

From source file:com.vmware.identity.proxyservice.LogoutProcessorImpl.java

/**
 * Error callback in processing logout response or request from external IDP.
 * @see com.vmware.identity.websso.client.LogoutProcessor#logoutError(com.vmware.identity.websso.client.Message, javax.servlet.http.HttpServletResponse)
 *//*from  w w w .j  av a  2 s  .  co  m*/
@Override
public void logoutError(Message arg0, HttpServletRequest request, HttpServletResponse response) {
    Validate.notNull(arg0, "Message");

    com.vmware.identity.websso.client.ValidationResult clientVr = arg0.getValidationResult();
    ValidationResult vr = null;

    String message;

    //The error could be from external idp or from validation of response from external idp
    if (arg0.getStatus() != null && !arg0.getStatus().equals(OasisNames.SUCCESS)) {
        //If it is external IDP authentication error.
        vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, arg0.getStatus(), arg0.getSubstatus());
        message = vr.getMessage(messageSource, getLogoutState().getLocale());
        logger.error("Error logout message from Externel IDP: {} message: {}", vr.getResponseCode(), message);

    } else {
        //Else send the validation error to RP
        vr = new ValidationResult(clientVr.getResponseCode(), clientVr.getStatus(), clientVr.getSubstatus());
        message = vr.getMessage(messageSource, getLogoutState().getLocale());
        logger.error("Failed in validating logout response from Externel IDP: {} message: {}",
                vr.getResponseCode(), message);
    }

    try {
        response.sendError(vr.getResponseCode(), message);
    } catch (IOException e) {
        logger.error("Caught IOException in sending error to logout request/response issurer");
    }
}

From source file:dtu.ds.warnme.ws.rest.json.AbstractRestWS.java

@ExceptionHandler({ BadRequestException.class, MissingServletRequestParameterException.class })
@ResponseBody/* w w  w  .  j av a  2s. c o m*/
String handleBadRequestExceptions(Exception ex, HttpServletRequest request, HttpServletResponse response) {
    log.info(ex.getMessage(), ex);
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    String responseBody = getMessage(ex, request.getLocale());
    RestUtils.decorateResponseHeaderWithMD5(response, responseBody);
    RestUtils.decorateResponseHeaderForJsonContentType(response);
    return responseBody;
}

From source file:cz.incad.kramerius.client.CacheServlet.java

private void loadFromFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    try {/*from  w  w  w  .jav a2  s  . com*/
        String filename = getPath() + req.getParameter("f");
        File f = new File(filename);
        resp.getWriter().write(FileUtils.readFileToString(f, "UTF-8"));
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Could not load file: " + e.toString());
    }
}

From source file:com.cognifide.cq.cqsm.core.servlets.ScriptRunServlet.java

@Override
protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {
    ResourceResolver resolver = request.getResourceResolver();
    final String searchPath = request.getParameter("file");
    final String modeName = request.getParameter("mode");

    if (StringUtils.isEmpty(searchPath)) {
        ServletUtils.writeMessage(response, "error", "Please set the script file name: -d \"file=[name]\"");
        return;//from  w  ww .  j  ava  2 s  .  c o  m
    }

    if (StringUtils.isEmpty(modeName)) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        ServletUtils.writeMessage(response, "error", "Running mode not specified.");
        return;
    }

    final Script script = scriptFinder.find(searchPath, resolver);
    if (script == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        ServletUtils.writeMessage(response, "error", String.format("Script not found: %s", searchPath));
        return;
    }

    try {
        final Mode mode = Mode.fromString(modeName, Mode.DRY_RUN);
        final Progress progressLogger = scriptManager.process(script, mode, resolver);

        if (progressLogger.isSuccess()) {
            ServletUtils.writeJson(response, ProgressHelper.toJson(progressLogger.getEntries()));
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            ServletUtils.writeJson(response, ProgressHelper.toJson(progressLogger.getLastError()));
        }

    } catch (RepositoryException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ServletUtils.writeMessage(response, "error", String
                .format("Script cannot be executed because of" + " repository error: %s", e.getMessage()));
    }
}

From source file:com.cognifide.cq.cqsm.core.servlets.ScriptReplicationServlet.java

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    ResourceResolver resolver = request.getResourceResolver();

    final String searchPath = request.getParameter("fileName");
    final String run = request.getParameter("run");

    if (StringUtils.isEmpty(searchPath)) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        ServletUtils.writeMessage(response, "error", "File name parameter is required");
        return;/*from  www  .  j  ava2 s . c  o m*/
    }

    final Script script = scriptFinder.find(searchPath, resolver);
    if (script == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        ServletUtils.writeMessage(response, "error", String.format("Script cannot be found: %s", searchPath));
        return;
    }

    final String scriptPath = script.getPath();

    try {
        final ModifiableScript modifiableScript = new ModifiableScriptWrapper(resolver, script);
        if (PUBLISH_RUN.equals(run)) {
            modifiableScript.setPublishRun(true);
        }
        scriptReplicator.replicate(script, resolver);

        ServletUtils.writeMessage(response, "success",
                String.format("Script '%s' replicated successfully", scriptPath));
    } catch (PersistenceException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ServletUtils.writeMessage(response, "error",
                String.format("Script '%s' cannot be processed because of" + " repository error: %s",
                        scriptPath, e.getMessage()));
    } catch (ExecutionException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ServletUtils.writeMessage(response, "error",
                String.format("Script '%s' cannot be processed: %s", scriptPath, e.getMessage()));
    } catch (ReplicationException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ServletUtils.writeMessage(response, "error",
                String.format("Script '%s' cannot be replicated: %s", scriptPath, e.getMessage()));
    }
}

From source file:au.org.ala.biocache.web.AdminController.java

/**
 * Ingests the list of supplied data resource uids. When no dr param is provided all data resources with the
 * configured collectory are ingested.//from   w  ww  .ja v  a 2s  .  co m
 *
 * Prevents the exact same ingestion from being started multiple times. Only prevents the exact same list of drs being
 * started.
 *
 * @param request
 * @param response
 * @throws Exception
 */
@RequestMapping(value = "/admin/ingest", method = RequestMethod.GET)
public void ingestResources(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //performs an asynchronous ingest.
    String apiKey = request.getParameter("apiKey");
    final String dataResources = request.getParameter("dr");
    final String ingest = dataResources == null ? "all" : dataResources;
    if (shouldPerformOperation(apiKey, response)) {
        logger.debug("Attempting to ingest " + ingest);
        if (ingestingDrs.contains(ingest)) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Already ingesting " + ingest + ". Unable able to start a new ingestion.");
        } else {
            ingestingDrs.add(ingest);
            Thread t = new Thread() {
                public void run() {
                    String[] drs = dataResources != null ? dataResources.split(",") : null;
                    Store.ingest(drs, ingestProcessingThreads);
                    //remove the url from ingesting
                    ingestingDrs.remove(ingest);
                }
            };
            t.start();
        }
    }
}

From source file:m.c.m.proxyma.ProxymaConsoleServlet.java

/**
 * This command handles the POST requests.
 *
 * @param httpservletrequest  the requrest..
 * @param httpservletresponse the response..
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException/*from  w w  w  . j a v a2 s .c o m*/
 */
@Override
public void doPost(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse)
        throws ServletException, IOException {

    //Getting parameters
    String context = httpservletrequest.getParameter(GlobalConstants.CONTEXT_PARAMETER);
    String target = httpservletrequest.getParameter(GlobalConstants.TARGET_PARAMETER);
    String action = httpservletrequest.getParameter(GlobalConstants.ACTION_PARAMETER);
    String command = httpservletrequest.getParameter(GlobalConstants.COMMAND_PARAMETER);

    if (!(validateParameters(context, command, target, action))) {
        httpservletresponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    //Choose what to do..
    //manages updateRule command
    ProxymaContext currentContext = proxyma.getContextByName(context);
    ProxyFolderBean currentTarget = proxyma.getProxyFolderByURLEncodedName(target, currentContext);
    if (GlobalConstants.MANAGE_FOLDER_COMMAND.equals(command)) {
        //Update or modify an existent rule
        if (GlobalConstants.ENABLE_FOLDER_ACTION.equals(action)) {
            //enble a disabled rule
            proxyma.enableProxyFolder(currentTarget);
            httpservletrequest.setAttribute(GlobalConstants.PROXY_FOLDER_LIST_REQUEST_ATTRIBUTE,
                    proxyma.getContextProxyFolders(currentContext));
            httpservletrequest.setAttribute(GlobalConstants.USER_MESSAGE_REQUEST_ATTRIBUTE,
                    "Proxy-Folder \"" + currentTarget.getFolderName() + "\" successfully Unlocked.");
            forwardToJsp(httpservletrequest, httpservletresponse, GlobalConstants.CONTEXT_OVERVIEW_PAGE,
                    currentContext);
        } else if (GlobalConstants.DISABLE_FOLDER_ACTION.equals(action)) {
            //disable an enabled rule
            proxyma.disableProxyFolder(currentTarget);
            httpservletrequest.setAttribute(GlobalConstants.PROXY_FOLDER_LIST_REQUEST_ATTRIBUTE,
                    proxyma.getContextProxyFolders(currentContext));
            httpservletrequest.setAttribute(GlobalConstants.USER_MESSAGE_REQUEST_ATTRIBUTE,
                    "Proxy-Folder \"" + currentTarget.getFolderName() + "\" successfully Locked.");
            forwardToJsp(httpservletrequest, httpservletresponse, GlobalConstants.CONTEXT_OVERVIEW_PAGE,
                    currentContext);
        } else if (GlobalConstants.GO_TO_EDIT_FOLDER_ACTION.equals(action)) {
            //Edit an existent rule
            if (currentTarget != null) {
                ProxyEngine dummyProxyEngine = null;
                try {
                    //Load a dummy proxy engine to get the list of the available plugins
                    dummyProxyEngine = this.proxyma.createNewProxyEngine(currentContext);
                } catch (IllegalAccessException ex) {
                    throw new ServletException(
                            "Unable to get available plugins for context " + currentContext.getName());
                }

                httpservletrequest.setAttribute(GlobalConstants.PROXY_FOLDER_REQUEST_ATTRIBUTE, currentTarget);
                httpservletrequest.setAttribute(GlobalConstants.AVAILABLE_CACHE_PROVIDERS_ATTRIBUTE,
                        dummyProxyEngine.getRegisteredCachePlugins());
                httpservletrequest.setAttribute(GlobalConstants.AVAILABLE_PREPROCESSORS_ATTRIBUTE,
                        dummyProxyEngine.getRegisteredPluginsByType(ProxymaTags.HandlerType.PREPROCESSOR));
                httpservletrequest.setAttribute(GlobalConstants.AVAILABLE_RETRIVERS_ATTRIBUTE,
                        dummyProxyEngine.getRegisteredPluginsByType(ProxymaTags.HandlerType.RETRIVER));
                httpservletrequest.setAttribute(GlobalConstants.AVAILABLE_TRANSFORMERS_ATTRIBUTE,
                        dummyProxyEngine.getRegisteredPluginsByType(ProxymaTags.HandlerType.TRANSFORMER));
                httpservletrequest.setAttribute(GlobalConstants.AVAILABLE_SERIALIZERS_ATTRIBUTE,
                        dummyProxyEngine.getRegisteredPluginsByType(ProxymaTags.HandlerType.SERIALIZER));
                forwardToJsp(httpservletrequest, httpservletresponse, GlobalConstants.EDIT_PROXY_FOLDER_PAGE,
                        currentContext);
            } else {
                httpservletresponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
        } else if (GlobalConstants.DELETE_FOLDER_ACTION.equals(action)) {
            //delete an existent rule
            try {
                proxyma.removeProxyFolder(currentTarget, currentContext);
                httpservletrequest.setAttribute(GlobalConstants.USER_MESSAGE_REQUEST_ATTRIBUTE,
                        "Proxy-Folder \"" + currentTarget.getFolderName()
                                + "\" successfully deleted from context \"" + currentContext.getName() + "\".");
            } catch (Exception e) {
                httpservletrequest.setAttribute(GlobalConstants.USER_MESSAGE_REQUEST_ATTRIBUTE, e.getMessage());
            }

            httpservletrequest.setAttribute(GlobalConstants.PROXY_FOLDER_LIST_REQUEST_ATTRIBUTE,
                    proxyma.getContextProxyFolders(currentContext));
            forwardToJsp(httpservletrequest, httpservletresponse, GlobalConstants.CONTEXT_OVERVIEW_PAGE,
                    currentContext);
        } else {
            httpservletresponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        //Manages refreshPage command
    } else if (GlobalConstants.RELOAD_PAGE_COMMAND.equals(command)) {
        //Refresh page data
        if (GlobalConstants.RELOAD_OVERVIEW_ACTION.equals(action)) {
            httpservletrequest.setAttribute(GlobalConstants.PROXY_FOLDER_LIST_REQUEST_ATTRIBUTE,
                    proxyma.getContextProxyFolders(currentContext));
            forwardToJsp(httpservletrequest, httpservletresponse, GlobalConstants.CONTEXT_OVERVIEW_PAGE,
                    currentContext);
        } else if (GlobalConstants.GOTO_WELCOME_PAGE_ACTION.equals(action)) {
            forwardToJsp(httpservletrequest, httpservletresponse, GlobalConstants.WELCOME_PAGE, currentContext);
        } else {
            httpservletresponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        //Manages addRule command by forwarding to the edit rule page
    } else if (GlobalConstants.ADD_NEW_FOLDER_COMMAND.equals(command)) {
        //Add a new Rule
        ProxyFolderBean blankFolder = null;
        ProxyEngine dummyProxyEngine = null;
        try {
            //Load a dummy proxy engine to get the list of the available plugins
            dummyProxyEngine = this.proxyma.createNewProxyEngine(currentContext);
            blankFolder = proxyma.createNewProxyFolder(GlobalConstants.BLANK_PROXY_FOLDER_NAME,
                    GlobalConstants.BLANK_PROXY_FOLDER_DESTINATION, currentContext);
        } catch (IllegalAccessException ex) {
            throw new ServletException(
                    "Unable to get available plugins for context " + currentContext.getName());
        } catch (IllegalArgumentException ex) {
            //The default folder already exists open it
            blankFolder = proxyma.getProxyFolderByURLEncodedName(GlobalConstants.BLANK_PROXY_FOLDER_NAME,
                    currentContext);
        }
        httpservletrequest.setAttribute(GlobalConstants.AVAILABLE_CACHE_PROVIDERS_ATTRIBUTE,
                dummyProxyEngine.getRegisteredCachePlugins());
        httpservletrequest.setAttribute(GlobalConstants.AVAILABLE_PREPROCESSORS_ATTRIBUTE,
                dummyProxyEngine.getRegisteredPluginsByType(ProxymaTags.HandlerType.PREPROCESSOR));
        httpservletrequest.setAttribute(GlobalConstants.AVAILABLE_RETRIVERS_ATTRIBUTE,
                dummyProxyEngine.getRegisteredPluginsByType(ProxymaTags.HandlerType.RETRIVER));
        httpservletrequest.setAttribute(GlobalConstants.AVAILABLE_TRANSFORMERS_ATTRIBUTE,
                dummyProxyEngine.getRegisteredPluginsByType(ProxymaTags.HandlerType.TRANSFORMER));
        httpservletrequest.setAttribute(GlobalConstants.AVAILABLE_SERIALIZERS_ATTRIBUTE,
                dummyProxyEngine.getRegisteredPluginsByType(ProxymaTags.HandlerType.SERIALIZER));

        httpservletrequest.setAttribute(GlobalConstants.PROXY_FOLDER_REQUEST_ATTRIBUTE, blankFolder);
        forwardToJsp(httpservletrequest, httpservletresponse, GlobalConstants.EDIT_PROXY_FOLDER_PAGE,
                currentContext);
        //todo: NOT YET IMPLEMENTED, will manage massive rules import from DB, XML, file.. etc...
    } else if (GlobalConstants.IMPORT_CONTEXT_COMMAND.equals(command)) {
        //Import rules from external sources
        httpservletrequest.setAttribute(GlobalConstants.USER_MESSAGE_REQUEST_ATTRIBUTE,
                "Function not yet Implemented :O(");
        httpservletrequest.setAttribute(GlobalConstants.PROXY_FOLDER_LIST_REQUEST_ATTRIBUTE,
                proxyma.getContextProxyFolders(currentContext));
        forwardToJsp(httpservletrequest, httpservletresponse, GlobalConstants.CONTEXT_OVERVIEW_PAGE,
                currentContext);
        return;
        //todo: NOT YET IMPLEMENTED, will manage massive rules export to DB, XML, file.. etc...
    } else if (GlobalConstants.EXPORT_CONTEXT_COMMAND.equals(command)) {
        //Import rules from external sources
        httpservletrequest.setAttribute(GlobalConstants.USER_MESSAGE_REQUEST_ATTRIBUTE,
                "Function not yet Implemented :O(");
        httpservletrequest.setAttribute(GlobalConstants.PROXY_FOLDER_LIST_REQUEST_ATTRIBUTE,
                proxyma.getContextProxyFolders(currentContext));
        forwardToJsp(httpservletrequest, httpservletresponse, GlobalConstants.CONTEXT_OVERVIEW_PAGE,
                currentContext);
        return;
        //Manages edit page requests.
    } else if (GlobalConstants.UPDATE_FOLDER_COMMAND.equals(command)) {
        //Update an existent Rule
        try {
            StringBuffer message = new StringBuffer(256);
            message.append("Proxy-Folder \"");
            message.append(currentTarget.getFolderName());
            message.append("\" successfully updated.");
            if (!currentTarget.isEnabled())
                message.append(
                        "<br/>WARNING: The folder is locked, click on the \"Status\" button to unlock it.");
            updateProxyFolderFromRequestParameters(httpservletrequest, currentTarget);
            httpservletrequest.setAttribute(GlobalConstants.USER_MESSAGE_REQUEST_ATTRIBUTE, message.toString());
            httpservletrequest.setAttribute(GlobalConstants.PROXY_FOLDER_LIST_REQUEST_ATTRIBUTE,
                    proxyma.getContextProxyFolders(currentContext));
            forwardToJsp(httpservletrequest, httpservletresponse, GlobalConstants.CONTEXT_OVERVIEW_PAGE,
                    currentContext);
        } catch (Exception e) {
            httpservletrequest.setAttribute(GlobalConstants.USER_MESSAGE_REQUEST_ATTRIBUTE, e.getMessage());
            httpservletrequest.setAttribute(GlobalConstants.PROXY_FOLDER_REQUEST_ATTRIBUTE, currentTarget);
            forwardToJsp(httpservletrequest, httpservletresponse, GlobalConstants.EDIT_PROXY_FOLDER_PAGE,
                    currentContext);
        }
    } else if (GlobalConstants.CHANGE_LOG_LEVEL_COMMAND.equals(command)) {
        String newLevel = currentContext.setLogLevel(action);
        httpservletrequest.setAttribute(GlobalConstants.USER_MESSAGE_REQUEST_ATTRIBUTE,
                "Changed log level for context \"" + currentContext.getName() + "\" to " + newLevel);
        httpservletrequest.setAttribute(GlobalConstants.PROXY_FOLDER_LIST_REQUEST_ATTRIBUTE,
                proxyma.getContextProxyFolders(currentContext));
        forwardToJsp(httpservletrequest, httpservletresponse, GlobalConstants.CONTEXT_OVERVIEW_PAGE,
                currentContext);
    } else {
        httpservletresponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
}

From source file:com.pymegest.applicationserver.api.PuestoController.java

@RequestMapping(value = { "/Puesto/{idsPuestos}" }, method = RequestMethod.GET)
public void read(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("idsPuestos") String idsPuestosStr) {

    try {/*from  ww  w  .j a v  a  2 s.  c o  m*/

        String[] idsPuestosArr = idsPuestosStr.split(",");
        List<Puesto> listaPuestos = new ArrayList();
        for (int i = 0; i < idsPuestosArr.length; i++) {
            listaPuestos.add(puestoDAO.read(Integer.parseInt(idsPuestosArr[i])));
        }

        if (listaPuestos.isEmpty() == false) {

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json; chaset=UTF-8");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(listaPuestos);
            response.getWriter().println(json);

        } else {

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("La lista de puestos de trabajo esta vacia.");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(mensaje);
            response.getWriter().println(json);

        }

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

From source file:org.clothocad.phagebook.controllers.AutoCompleteController.java

@RequestMapping(value = "/autoComplete", method = RequestMethod.GET)
protected void autoComplete(@RequestParam Map<String, String> params, HttpServletResponse response)
        throws ServletException, IOException {

    //I WILL RETURN THE MAP AS A JSON OBJECT.. it is client side's issue to parse all data for what they need!
    //they could check over there if the schema matches what they are querying for and so i can do this generically!
    //user should be logged in so I will log in as that user.
    String query = params.get("query") != null ? params.get("query") : "";
    boolean isValid = false;
    System.out.println("Query is: " + query);
    if (!query.equals("")) {
        isValid = true;/*w  w w. j  a  v a  2s .  c o m*/
    }

    if (isValid) {
        ClothoConnection conn = new ClothoConnection(Args.clothoLocation);
        Clotho clothoObject = new Clotho(conn);
        //TODO: we need to have an authentication token at some point
        String username = this.backendPhagebookUser;
        String password = this.backendPhagebookPassword;
        Map loginMap = new HashMap();
        loginMap.put("username", username);
        loginMap.put("credentials", password);

        clothoObject.login(loginMap);

        JSONArray replies = (JSONArray) clothoObject.autocomplete(query);
        conn.closeConnection();
        response.setStatus(HttpServletResponse.SC_ACCEPTED);
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.print(replies);
        out.flush();
        out.close();

        clothoObject.logout();

    }
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    response.setContentType("application/json");
    JSONObject reply = new JSONObject();
    reply.put("message", "Auto Complete requires a query parameter");
    PrintWriter out = response.getWriter();
    out.print(reply);
    out.flush();
    out.close();

}

From source file:com.pymegest.applicationserver.api.FamiliaController.java

@RequestMapping(value = { "/Familia/{idsFamilias}" }, method = RequestMethod.GET)
public void read(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("idsFamilias") String idsFamiliasStr) {

    try {/* w  w  w. ja  v  a  2 s . c o  m*/

        String[] idsFamiliasArr = idsFamiliasStr.split(",");
        List<Familia> listaFamilias = new ArrayList();
        for (int i = 0; i < idsFamiliasArr.length; i++) {
            listaFamilias.add(familiaDAO.read(Integer.parseInt(idsFamiliasArr[i])));
        }
        if (listaFamilias.isEmpty() == false) {

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json; chaset=UTF-8");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(listaFamilias);
            response.getWriter().println(json);

        } else {

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("La lista de puestos de trabajo esta vacia.");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(mensaje);
            response.getWriter().println(json);

        }

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}