Example usage for javax.servlet.http HttpServletRequest getReader

List of usage examples for javax.servlet.http HttpServletRequest getReader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getReader.

Prototype

public BufferedReader getReader() throws IOException;

Source Link

Document

Retrieves the body of the request as character data using a BufferedReader.

Usage

From source file:org.eclipse.orion.server.servlets.PreferencesServlet.java

@SuppressWarnings("unchecked")
@Override//from w w  w  .  jav a 2  s  .  c om
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    traceRequest(req);
    MetadataInfo info = getNode(req, resp);
    if (info == null)
        return;
    String key = req.getParameter("key"); //$NON-NLS-1$
    String prefix = getPrefix(req);
    try {
        boolean changed = false;
        if (key != null) {
            prefix = prefix + '/' + key;
            String newValue = req.getParameter("value"); //$NON-NLS-1$
            String oldValue = info.setProperty(prefix.toString(), newValue);
            changed = !newValue.equals(oldValue);
        } else {
            JSONObject newNode = new JSONObject(new JSONTokener(req.getReader()));
            //can't overwrite base user settings via preference servlet
            if (prefix.startsWith("user/")) {
                resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            //operations should not be removed by PUT
            if (!prefix.equals("operations")) {

                //clear existing values matching prefix
                changed |= removeMatchingProperties(info, prefix.toString());
            }
            for (Iterator<String> it = newNode.keys(); it.hasNext();) {
                key = it.next();
                String newValue = newNode.getString(key);
                String qualifiedKey = prefix + '/' + key;
                String oldValue = info.setProperty(qualifiedKey, newValue);
                changed |= !newValue.equals(oldValue);
            }
        }
        if (changed)
            save(info);
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } catch (Exception e) {
        handleException(resp, NLS.bind("Failed to store preferences for {0}", req.getRequestURL()), e);
        return;
    }
}

From source file:org.jbpm.formbuilder.server.EmbedingServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String profile = request.getParameter("profile");
    String usr = request.getParameter("usr");
    String pwd = request.getParameter("pwd");
    TaskDefinitionService taskService = createTaskService(request, usr, pwd);
    FormDefinitionService formService = createFormService(request, usr, pwd);
    FormRepresentationEncoder encoder = FormEncodingFactory.getEncoder();
    JsonObject json = new JsonObject();
    json.addProperty("embedded", profile);
    try {/*from   w w  w.  j a va2s .c o m*/
        if (profile != null && "designer".equals(profile)) {
            String userTask = request.getParameter("userTask");
            String processName = request.getParameter("processName");
            String bpmn2Process = IOUtils.toString(request.getReader());
            TaskRef task = taskService.getBPMN2Task(bpmn2Process, processName, userTask);
            if (task != null) {
                //get associated form if it exists
                FormRepresentation form = formService.getAssociatedForm(task.getPackageName(), task);
                if (form != null) {
                    json.addProperty("formjson", encoder.encode(form));
                }
                json.add("task", toJsonObject(task));
                json.addProperty("packageName", task.getPackageName());
            }
        } else {
            throw new Exception("Unknown profile for POST: " + profile);
        }
        request.setAttribute("jsonData", new Gson().toJson(json));
        request.getRequestDispatcher("/FormBuilder.jsp").forward(request, response);
    } catch (TaskServiceException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem getting task from guvnor");
    } catch (FormServiceException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem reading form from guvnor");
    } catch (FormEncodingException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem encoding form");
    } catch (Exception e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:fll.web.api.JudgesServlet.java

@SuppressFBWarnings(value = {
        "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING" }, justification = "Dynamic table based upon categories")
@Override//  w w  w.j av a  2s .c om
protected final void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {
    final ObjectMapper jsonMapper = new ObjectMapper();
    response.reset();
    response.setContentType("application/json");
    final PrintWriter writer = response.getWriter();

    final ServletContext application = getServletContext();

    int numNewJudges = 0;
    final DataSource datasource = ApplicationAttributes.getDataSource(application);
    Connection connection = null;
    PreparedStatement insertJudge = null;
    try {
        connection = datasource.getConnection();

        final int currentTournament = Queries.getCurrentTournament(connection);

        final StringWriter debugWriter = new StringWriter();
        IOUtils.copy(request.getReader(), debugWriter);

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Read data: " + debugWriter.toString());
        }

        final Reader reader = new StringReader(debugWriter.toString());

        final Collection<JudgeInformation> judges = jsonMapper.readValue(reader,
                JudgesTypeInformation.INSTANCE);

        final Collection<JudgeInformation> currentJudges = JudgeInformation.getJudges(connection,
                currentTournament);

        insertJudge = connection
                .prepareStatement("INSERT INTO Judges (id, category, Tournament, station) VALUES (?, ?, ?, ?)");
        insertJudge.setInt(3, currentTournament);

        for (final JudgeInformation judge : judges) {

            if (null != judge) {
                JudgeInformation found = null;
                for (final JudgeInformation cjudge : currentJudges) {
                    if (ComparisonUtils.safeEquals(cjudge, judge)) {
                        found = cjudge;
                    }
                }

                if (null == found) {
                    insertJudge.setString(1, judge.getId());
                    insertJudge.setString(2, judge.getCategory());
                    insertJudge.setString(4, judge.getGroup());
                    insertJudge.executeUpdate();
                    ++numNewJudges;
                }
            } // non-null judge
        } // foreach judge sent

        final UploadResult result = new UploadResult(true, "Successfully uploaded judges", numNewJudges);
        response.reset();
        jsonMapper.writeValue(writer, result);

    } catch (final SQLException e) {
        LOGGER.error("Error uploading judges", e);

        final UploadResult result = new UploadResult(false, e.getMessage(), numNewJudges);
        jsonMapper.writeValue(writer, result);
    } finally {
        SQLFunctions.close(insertJudge);
        SQLFunctions.close(connection);
    }

}

From source file:com.impala.servlet.Remit.java

/**
 * //from  w ww. j a  v  a 2  s . c o m
 * @param request
 * @return
 * @throws IOException
 */
private String moneytransfer(HttpServletRequest request) throws IOException, JSONException {

    // joined json string
    String join = "";
    JsonElement root = null;
    JsonElement root2 = null;
    JsonElement root3 = null;

    String responseobject = "";
    String nickname = "KENDYIPL";

    // These represent parameters received over the network
    String referenceid = "", customermsisdn = "", amount = "", batchref = "", username = "", password = "",
            narrative = "";
    //referenceid, customermsisdn, nickname,amount, batchref, username, password, narrative

    // Get all parameters, the keys of the parameters are specified
    List<String> lines = IOUtils.readLines(request.getReader());

    // used to format/join incoming JSon string
    join = StringUtils.join(lines.toArray(), "");

    //###############################################################################
    // instantiate the JSon
    //Note
    //The = sign is encoded to \u003d. Hence you need to use disableHtmlEscaping().
    //###############################################################################

    Gson g = new GsonBuilder().disableHtmlEscaping().create();
    //Gson g = new Gson();
    Map<String, String> expected = new HashMap<>();

    try {
        // parse the JSon string
        //referenceid, customermsisdn, nickname,amount, batchref, username, password, narrative

        root = new JsonParser().parse(join);

        referenceid = root.getAsJsonObject().get("transaction_id").getAsString();

        customermsisdn = root.getAsJsonObject().get("beneficiary_msisdn").getAsString();

        amount = root.getAsJsonObject().get("amount").getAsString();

        password = root.getAsJsonObject().get("password").getAsString();
        batchref = root.getAsJsonObject().get("source_msisdn").getAsString();
        username = root.getAsJsonObject().get("username").getAsString();
        narrative = root.getAsJsonObject().get("sendingIMT").getAsString();

    } catch (Exception e) {

        expected.put("command_status", "COMMANDSTATUS_INVALID_PARAMETERS");
        String jsonResult = g.toJson(expected);
        System.out.println(e);

        return jsonResult;
    }

    // check for the presence of all required parameters
    if (StringUtils.isBlank(referenceid) || StringUtils.isBlank(customermsisdn) || StringUtils.isBlank(nickname)
            || StringUtils.isBlank(amount) || StringUtils.isBlank(password) || StringUtils.isBlank(batchref)
            || StringUtils.isBlank(username) || StringUtils.isBlank(narrative)) {

        expected.put("am_referenceid", username);
        expected.put("am_timestamp", "tombwa");
        expected.put("status_code", statuscode);
        expected.put("status_description", Statusdescription);
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

    //assign the remit url from properties.config

    String processtransaction = remittoairtel.Airtelpayout(referenceid, customermsisdn, nickname, amount,
            batchref, username, password, narrative);
    //capture the switch respoinse.

    System.out.println(processtransaction);

    //pass the returned json string
    JsonElement roots = new JsonParser().parse(processtransaction);

    //exctract a specific json element from the object(status_code)
    String switchresponse = roots.getAsJsonObject().get("Status").getAsString();

    if (switchresponse.equalsIgnoreCase("success")) {
        switchresponse = "S000";
    }

    //map error
    if (switchresponse.equalsIgnoreCase("failed")) {
        switchresponse = "00029";
    }

    if (switchresponse.equalsIgnoreCase("Insufficient Funds In Source Wallet")) {
        switchresponse = "00029";
    }

    //add 

    String success = "S000";

    if (switchresponse.equalsIgnoreCase(success)) {

        //exctract a specific json element from the object(transactionID)
        String transactionID = roots.getAsJsonObject().get("Reference").getAsString();

        expected.put("am_referenceid", transactionID);
        expected.put("am_timestamp", username);
        expected.put("status_code", "S000");
        expected.put("status_description", "SUCCESSFUL");
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

    expected.put("am_referenceid", username);
    expected.put("am_timestamp", username);
    expected.put("status_code", switchresponse);
    expected.put("status_description", "FAILED");

    String jsonResult = g.toJson(expected);

    return jsonResult;

}

From source file:org.deegree.enterprise.servlet.OGCServletController.java

/**
 * Sends the passed <code>OGCWebServiceException</code> to the calling client.
 *
 * @param response//from w w w .jav  a  2s.  c om
 * @param e
 * @param request
 * @param service
 *            the service name, if known
 */
private static void sendException(HttpServletResponse response, OGCWebServiceException e,
        HttpServletRequest request, String service) {
    LOG.logInfo("Sending OGCWebServiceException to client.");

    Map<?, ?> pmap = request.getParameterMap();
    Map<String, String> map = new HashMap<String, String>(pmap.size());
    for (Object o : pmap.keySet()) {
        String[] tmp = (String[]) pmap.get(o);
        for (int i = 0; i < tmp.length; i++) {
            tmp[i] = tmp[i].trim();
        }
        map.put(((String) o).toLowerCase(), arrayToString(tmp, ','));
    }

    boolean isWMS130 = false, isCSW = false, isWCTS = false, isWFS = false, isWFS100 = false;

    if (service == null) {
        service = map.get("service");
    }

    String version = map.get("version");

    if (service != null) {
        if ("wms".equalsIgnoreCase(service)) {
            isWMS130 = version != null && version.equals("1.3.0");
        }
        if ("wfs".equalsIgnoreCase(service)) {
            isWFS = true;
            isWFS100 = version != null && version.equals("1.0.0");
        }

        isCSW = "csw".equalsIgnoreCase(service);
        isWCTS = "wcts".equalsIgnoreCase(service);
        isWFS = "wfs".equalsIgnoreCase(service);
    } else {
        try {
            XMLFragment doc = new XMLFragment(request.getReader(), XMLFragment.DEFAULT_URL);
            service = OGCRequestFactory.getTargetService("", "", doc.getRootElement().getOwnerDocument());
            isCSW = "csw".equalsIgnoreCase(service);
            isWCTS = "wcts".equalsIgnoreCase(service);
            isWFS = "wfs".equalsIgnoreCase(service);
            isWFS100 = isWFS && doc.getRootElement().getAttribute("version") != null
                    && doc.getRootElement().getAttribute("version").equals("1.0.0");
        } catch (SAXException e1) {
            // ignore
        } catch (IOException e1) {
            // ignore
        } catch (IllegalStateException e1) {
            // ignore, that happens in some tomcats
        }
    }

    try {
        XMLFragment doc;
        String contentType = "text/xml";

        if (!(isWMS130 || isCSW || isWCTS || isWFS)) {
            // apply the simplest of heuristics...
            String req = request.getRequestURI().toLowerCase();
            if (req.indexOf("csw") != -1) {
                isCSW = true;
            } else if (req.indexOf("wcts") != -1) {
                isWCTS = true;
            } else if (req.indexOf("wfs") != -1) {
                isWFS = true;
            }

            if (isWFS) {
                isWFS100 = req.indexOf("1.0.0") != -1;
            }

            if (!(isWMS130 || isCSW || isWCTS || isWFS || isWFS100)) {
                isWMS130 = version != null && version.equals("1.3.0");
            }
        }

        // send exception format INIMAGE etc. for WMS
        if (service != null && service.equalsIgnoreCase("wms")) {
            ServiceDispatcher handler = getInstance().getHandler(service, request.getRemoteAddr());
            if (handler instanceof WMSHandler) {
                WMSHandler h = (WMSHandler) handler;
                String format = map.get("format");
                String eFormat = map.get("exceptions");
                try {
                    h.determineExceptionFormat(eFormat, format, version, response);
                    h.writeServiceExceptionReport(e);
                    return;
                } catch (Exception ex) {
                    LOG.logDebug("Error while sending the exception in special format."
                            + " Continuing in default mode.", ex);
                }
            }
        }

        if (isWMS130 || "wcs".equalsIgnoreCase(e.getLocator())) {
            doc = XMLFactory.exportNS(new ExceptionReport(new OGCWebServiceException[] { e }));
        } else if (isCSW) {
            doc = XMLFactory.exportExceptionReport(new ExceptionReport(new OGCWebServiceException[] { e }));
        } else if (isWCTS) {
            doc = org.deegree.owscommon_1_1_0.XMLFactory.exportException(e);
        } else if (isWFS100) {
            doc = XMLFactory.exportExceptionReportWFS100(e);
        } else if (isWFS) {
            doc = XMLFactory.exportExceptionReportWFS(e);
        } else {
            contentType = "application/vnd.ogc.se_xml";
            doc = XMLFactory.export(new ExceptionReport(new OGCWebServiceException[] { e }));
        }

        response.setContentType(contentType);
        OutputStream os = response.getOutputStream();
        doc.write(os);
        os.close();
    } catch (Exception ex) {
        LOG.logError("ERROR: " + ex.getMessage(), ex);
    }
}

From source file:org.eclipse.rdf4j.http.server.repository.statements.StatementsController.java

private ModelAndView getSparqlUpdateResult(Repository repository, HttpServletRequest request,
        HttpServletResponse response) throws ServerHTTPException, ClientHTTPException, HTTPException {
    ProtocolUtil.logRequestParameters(request);

    String mimeType = HttpServerUtil.getMIMEType(request.getContentType());

    String sparqlUpdateString;// w w w  .j a v  a 2s.  c om
    if (Protocol.SPARQL_UPDATE_MIME_TYPE.equals(mimeType)) {
        // The query should be the entire body
        try {
            sparqlUpdateString = IOUtils.toString(request.getReader());
        } catch (IOException e) {
            throw new ClientHTTPException(SC_BAD_REQUEST, "Error reading request message body", e);
        }
        if (sparqlUpdateString.isEmpty())
            sparqlUpdateString = null;
    } else {
        sparqlUpdateString = request.getParameterValues(Protocol.UPDATE_PARAM_NAME)[0];
    }

    // default query language is SPARQL
    QueryLanguage queryLn = QueryLanguage.SPARQL;

    String queryLnStr = request.getParameter(QUERY_LANGUAGE_PARAM_NAME);
    logger.debug("query language param = {}", queryLnStr);

    if (queryLnStr != null) {
        queryLn = QueryLanguage.valueOf(queryLnStr);

        if (queryLn == null) {
            throw new ClientHTTPException(SC_BAD_REQUEST, "Unknown query language: " + queryLnStr);
        }
    }

    String baseURI = request.getParameter(Protocol.BASEURI_PARAM_NAME);

    // determine if inferred triples should be included in query evaluation
    boolean includeInferred = ProtocolUtil.parseBooleanParam(request, INCLUDE_INFERRED_PARAM_NAME, true);

    // build a dataset, if specified
    String[] defaultRemoveGraphURIs = request.getParameterValues(REMOVE_GRAPH_PARAM_NAME);
    String[] defaultInsertGraphURIs = request.getParameterValues(INSERT_GRAPH_PARAM_NAME);
    String[] defaultGraphURIs = request.getParameterValues(USING_GRAPH_PARAM_NAME);
    String[] namedGraphURIs = request.getParameterValues(USING_NAMED_GRAPH_PARAM_NAME);

    SimpleDataset dataset = null;
    if (defaultRemoveGraphURIs != null || defaultInsertGraphURIs != null || defaultGraphURIs != null
            || namedGraphURIs != null) {
        dataset = new SimpleDataset();
    }

    if (defaultRemoveGraphURIs != null) {
        for (String graphURI : defaultRemoveGraphURIs) {
            try {
                IRI uri = createURIOrNull(repository, graphURI);
                dataset.addDefaultRemoveGraph(uri);
            } catch (IllegalArgumentException e) {
                throw new ClientHTTPException(SC_BAD_REQUEST,
                        "Illegal URI for default remove graph: " + graphURI);
            }
        }
    }

    if (defaultInsertGraphURIs != null && defaultInsertGraphURIs.length > 0) {
        String graphURI = defaultInsertGraphURIs[0];
        try {
            IRI uri = createURIOrNull(repository, graphURI);
            dataset.setDefaultInsertGraph(uri);
        } catch (IllegalArgumentException e) {
            throw new ClientHTTPException(SC_BAD_REQUEST, "Illegal URI for default insert graph: " + graphURI);
        }
    }

    if (defaultGraphURIs != null) {
        for (String defaultGraphURI : defaultGraphURIs) {
            try {
                IRI uri = createURIOrNull(repository, defaultGraphURI);
                dataset.addDefaultGraph(uri);
            } catch (IllegalArgumentException e) {
                throw new ClientHTTPException(SC_BAD_REQUEST,
                        "Illegal URI for default graph: " + defaultGraphURI);
            }
        }
    }

    if (namedGraphURIs != null) {
        for (String namedGraphURI : namedGraphURIs) {
            try {
                IRI uri = createURIOrNull(repository, namedGraphURI);
                dataset.addNamedGraph(uri);
            } catch (IllegalArgumentException e) {
                throw new ClientHTTPException(SC_BAD_REQUEST, "Illegal URI for named graph: " + namedGraphURI);
            }
        }
    }

    final int maxQueryTime = ProtocolUtil.parseTimeoutParam(request);
    try (RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request)) {
        Update update = repositoryCon.prepareUpdate(queryLn, sparqlUpdateString, baseURI);

        update.setIncludeInferred(includeInferred);
        update.setMaxExecutionTime(maxQueryTime);

        if (dataset != null) {
            update.setDataset(dataset);
        }

        // determine if any variable bindings have been set on this
        // update.
        @SuppressWarnings("unchecked")
        Enumeration<String> parameterNames = request.getParameterNames();

        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();

            if (parameterName.startsWith(BINDING_PREFIX) && parameterName.length() > BINDING_PREFIX.length()) {
                String bindingName = parameterName.substring(BINDING_PREFIX.length());
                Value bindingValue = ProtocolUtil.parseValueParam(request, parameterName,
                        repository.getValueFactory());
                update.setBinding(bindingName, bindingValue);
            }
        }

        update.execute();

        return new ModelAndView(EmptySuccessView.getInstance());
    } catch (QueryInterruptedException e) {
        throw new ServerHTTPException(SC_SERVICE_UNAVAILABLE, "update execution took too long");
    } catch (UpdateExecutionException e) {
        if (e.getCause() != null && e.getCause() instanceof HTTPException) {
            // custom signal from the backend, throw as HTTPException
            // directly
            // (see SES-1016).
            throw (HTTPException) e.getCause();
        } else {
            throw new ServerHTTPException("Repository update error: " + e.getMessage(), e);
        }
    } catch (RepositoryException e) {
        if (e.getCause() != null && e.getCause() instanceof HTTPException) {
            // custom signal from the backend, throw as HTTPException
            // directly
            // (see SES-1016).
            throw (HTTPException) e.getCause();
        } else {
            throw new ServerHTTPException("Repository update error: " + e.getMessage(), e);
        }
    } catch (MalformedQueryException e) {
        ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_QUERY, e.getMessage());
        throw new ClientHTTPException(SC_BAD_REQUEST, errInfo.toString());
    }
}

From source file:org.eclipse.orion.internal.server.servlets.file.FileHandlerV1.java

@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, IFileStore file)
        throws ServletException {
    try {/* ww w  .j a va  2s .c o  m*/
        String receivedETag = request.getHeader(ProtocolConstants.HEADER_IF_MATCH);
        if (receivedETag != null && !receivedETag.equals(generateFileETag(file))) {
            response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
            return true;
        }
        String parts = IOUtilities.getQueryParameter(request, "parts");
        if (parts == null || "body".equals(parts)) { //$NON-NLS-1$
            switch (getMethod(request)) {
            case DELETE:
                file.delete(EFS.NONE, null);
                break;
            case PUT:
                handlePutContents(request, request.getReader(), response, file);
                break;
            case POST:
                if ("PATCH".equals(request.getHeader(ProtocolConstants.HEADER_METHOD_OVERRIDE))) {
                    handlePatchContents(request, request.getReader(), response, file);
                }
                break;
            default:
                return handleFileContents(request, response, file);
            }
            return true;
        }
        if ("meta".equals(parts)) { //$NON-NLS-1$
            switch (getMethod(request)) {
            case GET:
                response.setCharacterEncoding("UTF-8");
                handleGetMetadata(request, response, response.getWriter(), file);
                return true;
            case PUT:
                handlePutMetadata(request.getReader(), null, file);
                response.setStatus(HttpServletResponse.SC_NO_CONTENT);
                return true;
            }
            return false;
        }
        if ("meta,body".equals(parts) || "body,meta".equals(parts)) { //$NON-NLS-1$ //$NON-NLS-2$
            switch (getMethod(request)) {
            case GET:
                handleMultiPartGet(request, response, file);
                return true;
            case PUT:
                handleMultiPartPut(request, response, file);
                return true;
            }
            return false;
        }
    } catch (JSONException e) {
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "Syntax error in request", e));
    } catch (Exception e) {
        if (!handleAuthFailure(request, response, e))
            throw new ServletException(NLS.bind("Error retrieving file: {0}", file), e);
    }
    return false;
}

From source file:org.openrdf.http.server.repository.statements.StatementsController.java

private ModelAndView getSparqlUpdateResult(Repository repository, HttpServletRequest request,
        HttpServletResponse response) throws ServerHTTPException, ClientHTTPException, HTTPException {
    ProtocolUtil.logRequestParameters(request);

    String mimeType = HttpServerUtil.getMIMEType(request.getContentType());

    String sparqlUpdateString;/*from ww  w .j ava 2  s  .c  om*/
    if (Protocol.SPARQL_UPDATE_MIME_TYPE.equals(mimeType)) {
        // The query should be the entire body
        try {
            sparqlUpdateString = IOUtils.toString(request.getReader());
        } catch (IOException e) {
            throw new ClientHTTPException(SC_BAD_REQUEST, "Error reading request message body", e);
        }
        if (sparqlUpdateString.isEmpty())
            sparqlUpdateString = null;
    } else {
        sparqlUpdateString = request.getParameterValues(Protocol.UPDATE_PARAM_NAME)[0];
    }

    // default query language is SPARQL
    QueryLanguage queryLn = QueryLanguage.SPARQL;

    String queryLnStr = request.getParameter(QUERY_LANGUAGE_PARAM_NAME);
    logger.debug("query language param = {}", queryLnStr);

    if (queryLnStr != null) {
        queryLn = QueryLanguage.valueOf(queryLnStr);

        if (queryLn == null) {
            throw new ClientHTTPException(SC_BAD_REQUEST, "Unknown query language: " + queryLnStr);
        }
    }

    String baseURI = request.getParameter(Protocol.BASEURI_PARAM_NAME);

    // determine if inferred triples should be included in query evaluation
    boolean includeInferred = ProtocolUtil.parseBooleanParam(request, INCLUDE_INFERRED_PARAM_NAME, true);

    // build a dataset, if specified
    String[] defaultRemoveGraphURIs = request.getParameterValues(REMOVE_GRAPH_PARAM_NAME);
    String[] defaultInsertGraphURIs = request.getParameterValues(INSERT_GRAPH_PARAM_NAME);
    String[] defaultGraphURIs = request.getParameterValues(USING_GRAPH_PARAM_NAME);
    String[] namedGraphURIs = request.getParameterValues(USING_NAMED_GRAPH_PARAM_NAME);

    SimpleDataset dataset = new SimpleDataset();

    if (defaultRemoveGraphURIs != null) {
        for (String graphURI : defaultRemoveGraphURIs) {
            try {
                IRI uri = createURIOrNull(repository, graphURI);
                dataset.addDefaultRemoveGraph(uri);
            } catch (IllegalArgumentException e) {
                throw new ClientHTTPException(SC_BAD_REQUEST,
                        "Illegal URI for default remove graph: " + graphURI);
            }
        }
    }

    if (defaultInsertGraphURIs != null && defaultInsertGraphURIs.length > 0) {
        String graphURI = defaultInsertGraphURIs[0];
        try {
            IRI uri = createURIOrNull(repository, graphURI);
            dataset.setDefaultInsertGraph(uri);
        } catch (IllegalArgumentException e) {
            throw new ClientHTTPException(SC_BAD_REQUEST, "Illegal URI for default insert graph: " + graphURI);
        }
    }

    if (defaultGraphURIs != null) {
        for (String defaultGraphURI : defaultGraphURIs) {
            try {
                IRI uri = createURIOrNull(repository, defaultGraphURI);
                dataset.addDefaultGraph(uri);
            } catch (IllegalArgumentException e) {
                throw new ClientHTTPException(SC_BAD_REQUEST,
                        "Illegal URI for default graph: " + defaultGraphURI);
            }
        }
    }

    if (namedGraphURIs != null) {
        for (String namedGraphURI : namedGraphURIs) {
            try {
                IRI uri = createURIOrNull(repository, namedGraphURI);
                dataset.addNamedGraph(uri);
            } catch (IllegalArgumentException e) {
                throw new ClientHTTPException(SC_BAD_REQUEST, "Illegal URI for named graph: " + namedGraphURI);
            }
        }
    }

    try {

        RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request);
        synchronized (repositoryCon) {
            Update update = repositoryCon.prepareUpdate(queryLn, sparqlUpdateString, baseURI);

            update.setIncludeInferred(includeInferred);

            if (dataset != null) {
                update.setDataset(dataset);
            }

            // determine if any variable bindings have been set on this update.
            @SuppressWarnings("unchecked")
            Enumeration<String> parameterNames = request.getParameterNames();

            while (parameterNames.hasMoreElements()) {
                String parameterName = parameterNames.nextElement();

                if (parameterName.startsWith(BINDING_PREFIX)
                        && parameterName.length() > BINDING_PREFIX.length()) {
                    String bindingName = parameterName.substring(BINDING_PREFIX.length());
                    Value bindingValue = ProtocolUtil.parseValueParam(request, parameterName,
                            repository.getValueFactory());
                    update.setBinding(bindingName, bindingValue);
                }
            }

            update.execute();
        }

        return new ModelAndView(EmptySuccessView.getInstance());
    } catch (UpdateExecutionException e) {
        if (e.getCause() != null && e.getCause() instanceof HTTPException) {
            // custom signal from the backend, throw as HTTPException directly
            // (see SES-1016).
            throw (HTTPException) e.getCause();
        } else {
            throw new ServerHTTPException("Repository update error: " + e.getMessage(), e);
        }
    } catch (RepositoryException e) {
        if (e.getCause() != null && e.getCause() instanceof HTTPException) {
            // custom signal from the backend, throw as HTTPException directly
            // (see SES-1016).
            throw (HTTPException) e.getCause();
        } else {
            throw new ServerHTTPException("Repository update error: " + e.getMessage(), e);
        }
    } catch (MalformedQueryException e) {
        ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_QUERY, e.getMessage());
        throw new ClientHTTPException(SC_BAD_REQUEST, errInfo.toString());
    }
}

From source file:org.openhab.io.hueemulation.internal.HueEmulationServlet.java

/**
 * Hue API call to set the state of a light
 *
 * @param id/*from   w ww.  jav a 2 s  . c o m*/
 * @param req
 * @param resp
 * @throws IOException
 */
private void apiState(String id, HttpServletRequest req, HttpServletResponse resp) throws IOException {
    if (!req.getMethod().equals(METHOD_PUT)) {
        apiServerError(req, resp, HueErrorResponse.METHOD_NOT_AVAILABLE, "Only PUT allowed for this resource");
        return;
    }
    try {
        // will throw exception if not found
        Item item = itemRegistry.getItem(id);
        HueState state = gson.fromJson(req.getReader(), HueState.class);
        HSBType hsb = state.toHSBType();
        logger.debug("HuState {}", state);
        logger.debug("HSBType {}", hsb);
        Command command = null;
        if (hsb.getBrightness().intValue() > 0) {
            // if state is on then send HSB, Brightness or ON
            if (item.getAcceptedCommandTypes().contains(HSBType.class)) {
                command = hsb;
            } else {
                // try and set the brightness level first
                command = TypeParser.parseCommand(item.getAcceptedCommandTypes(),
                        hsb.getBrightness().toString());
                if (command == null) {
                    // if the item does not accept a number or String type, try ON
                    command = TypeParser.parseCommand(item.getAcceptedCommandTypes(), "ON");
                }
            }
        } else {
            // if state is off, then send 0 or 0FF
            command = TypeParser.parseCommand(item.getAcceptedCommandTypes(), "0");
            if (command == null) {
                command = TypeParser.parseCommand(item.getAcceptedCommandTypes(), "OFF");
            }
        }

        if (command != null) {
            logger.debug("sending {} to {}", command, id);
            eventPublisher.post(ItemEventFactory.createCommandEvent(id, command));
            PrintWriter out = resp.getWriter();
            out.write(String.format(STATE_RESP, id, String.valueOf(state.on)));
            out.close();
        } else {
            logger.error("Item {} does not accept Decimal, ON/OFF or String types", id);
            apiServerError(req, resp, HueErrorResponse.INTERNAL_ERROR,
                    "The Hue device does not respond to that command");
        }
    } catch (ItemNotFoundException e) {
        logger.debug("Item not found: {}", id);
        apiServerError(req, resp, HueErrorResponse.NOT_AVAILABLE, "The Hue device could not be found");
    }
}

From source file:org.apache.lucene.gdata.servlet.handler.AbstractFeedHandler.java

protected ServerBaseFeed createFeedFromRequest(HttpServletRequest request)
        throws ParseException, IOException, FeedHandlerException {
    GDataServerRegistry registry = GDataServerRegistry.getRegistry();
    String providedService = request.getParameter(PARAMETER_SERVICE);
    if (!registry.isServiceRegistered(providedService)) {
        setError(GDataResponse.NOT_FOUND, "no such service");
        throw new FeedHandlerException("ProvicdedService is not registered -- Name: " + providedService);
    }/*w w w.j  av a 2s .  co m*/
    ProvidedService provServiceInstance = registry.getProvidedService(providedService);
    if (providedService == null) {
        setError(GDataResponse.BAD_REQUEST, "no such service");
        throw new FeedHandlerException("no such service registered -- " + providedService);
    }
    try {
        ServerBaseFeed retVal = new ServerBaseFeed(
                GDataEntityBuilder.buildFeed(request.getReader(), provServiceInstance));
        retVal.setServiceConfig(provServiceInstance);
        return retVal;
    } catch (IOException e) {
        if (LOG.isInfoEnabled())
            LOG.info("Can not read from input stream - ", e);
        setError(GDataResponse.BAD_REQUEST, "Can not read from input stream");
        throw e;
    } catch (ParseException e) {
        if (LOG.isInfoEnabled())
            LOG.info("feed can not be parsed - ", e);
        setError(GDataResponse.BAD_REQUEST, "incoming feed can not be parsed");
        throw e;
    }

}