Example usage for javax.servlet.http HttpServletRequest getContentType

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

Introduction

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

Prototype

public String getContentType();

Source Link

Document

Returns the MIME type of the body of the request, or null if the type is not known.

Usage

From source file:com.krawler.esp.servlets.ExportImportContactsServlet.java

private String doImport(HttpServletRequest request, Connection conn)
        throws SessionExpiredException, ServiceException, IOException, JSONException, ConfigurationException {
    String contentType = request.getContentType();
    CsvReader csvReader = null;/*ww  w.j a v a 2s  .  c  o  m*/
    FileInputStream fstream = null;
    JSONObject mapping = new JSONObject();
    if (request.getParameter("headerMap") != null) {
        mapping = new JSONObject(request.getParameter("headerMap"));
    }
    String importType = request.getParameter("importType");
    String csvFile = request.getParameter("filename");
    String fileID = request.getParameter("fileid");
    String realFileName = request.getParameter("realFileName");
    JSONObject jsnobj = new JSONObject();
    String userid = AuthHandler.getUserid(request);
    String nameIndex = mapping.getString("name");
    String emailIndex = mapping.getString("emailid");
    String phoneIndex = mapping.getString("contactno");
    String addressIndex = mapping.getString("address");
    String companyID = AuthHandler.getCompanyid(request);
    String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
            + "importcontacts" + StorageHandler.GetFileSeparator() + userid;
    File csv = new File(destinationDirectory + StorageHandler.GetFileSeparator() + csvFile);

    fstream = new FileInputStream(csv);
    csvReader = new CsvReader(new InputStreamReader(fstream));
    int noOfRecords = 0;
    csvReader.readRecord();
    int threadStartLimit = Integer.parseInt(ConfigReader.getinstance().get("contact_thread_start_limit"));
    while (csvReader.readRecord()) {
        noOfRecords++;
        if (noOfRecords > threadStartLimit) {
            break;
        }
    }
    fstream.close();
    csvReader.close();
    fstream = new FileInputStream(csv);
    csvReader = new CsvReader(new InputStreamReader(fstream));
    String msg = "";
    ThreadImpl r = new ThreadImpl(csvReader, userid, importType, realFileName, fileID, destinationDirectory,
            nameIndex, phoneIndex, addressIndex, emailIndex, companyID);
    if (noOfRecords > threadStartLimit) {
        Thread t = new Thread(r);
        t.start();
    } else {
        msg = r.importContacts(csvReader, userid, importType, realFileName, fileID, destinationDirectory,
                nameIndex, phoneIndex, addressIndex, emailIndex, companyID);
    }
    jsnobj.put("success", "true");
    jsnobj.put("msg", msg);
    String str = jsnobj.toString();
    return str;
}

From source file:org.wings.session.MultipartRequest.java

/**
 * Parses passed request and stores contained parameters.
 *
 * @throws IOException On unrecoverable parsing bugs due to old Tomcat version.
 *///from   w  w w.  j  a  va2 s. c o  m
protected void processRequest(HttpServletRequest req) throws IOException {
    String type = req.getContentType();
    if (type == null || !type.toLowerCase().startsWith("multipart/form-data")) {
        urlencodedRequest = true;
        return;
    }

    urlencodedRequest = false;
    parameters = new HashMap<String, List>();
    files = new HashMap<String, UploadedFile>();

    for (Iterator iterator = req.getParameterMap().entrySet().iterator(); iterator.hasNext(); /**/) {
        Map.Entry entry = (Map.Entry) iterator.next();
        parameters.put((String) entry.getKey(), new ArrayList(Arrays.asList((String[]) entry.getValue())));
    }

    String boundaryToken = extractBoundaryToken(type);
    if (boundaryToken == null) {
        /*
         * this could happen due to a bug in Tomcat 3.2.2 in combination
         * with Opera.
         * Opera sends the boundary on a separate line, which is perfectly
         * correct regarding the way header may be constructed 
         * (multiline headers). Alas, Tomcat fails to read the header in 
         * the content type line and thus we cannot read it.. haven't 
         * checked later versions of Tomcat, but upgrading is
         * definitly needed, since we cannot do anything about it here.
         * (JServ works fine, BTW.) (Henner)
         */
        throw new IOException("Separation boundary was not specified (BUG in Tomcat 3.* with Opera?)");
    }

    MultipartInputStream mimeStream = null;

    ByteArrayOutputStream headerByteArray;
    StringBuilder content = new StringBuilder();
    HashMap headers = null;
    int currentByte = 0;
    int currentPos = 0;
    int currentTransformByte = 0;
    String currentParam = null;
    File uploadFile = null;
    OutputStream fileStream = null;
    boolean done;
    int last = -1;

    try {
        mimeStream = new MultipartInputStream(req.getInputStream(), req.getContentLength(), maxSize);
        while (currentByte != -1) {
            // Read MIME part header line
            done = false;
            headerByteArray = new ByteArrayOutputStream();
            while ((currentByte = mimeStream.read()) != -1 && !done) {
                headerByteArray.write(currentByte);
                done = (last == '\n' && currentByte == '\r');
                last = currentByte;
            }
            if (currentByte == -1)
                break;

            headers = parseHeader(headerByteArray.toString(req.getCharacterEncoding()));
            headerByteArray.reset();
            currentParam = (String) headers.get("name");

            if (headers.size() == 1) { // .. it's not a file
                byte[] bytes = new byte[req.getContentLength()];
                currentPos = 0;
                while ((currentByte = mimeStream.read()) != -1) {
                    bytes[currentPos] = (byte) currentByte;
                    currentPos++;
                    if (currentPos >= boundaryToken.length()) {
                        int i;
                        for (i = 0; i < boundaryToken.length(); i++) {
                            if (boundaryToken
                                    .charAt(boundaryToken.length() - i - 1) != bytes[currentPos - i - 1]) {
                                i = 0;
                                break;
                            }
                        }
                        if (i == boundaryToken.length()) { // end of part ..
                            ByteArrayInputStream bais = new ByteArrayInputStream(bytes, 0,
                                    currentPos - boundaryToken.length() - 4);
                            InputStreamReader ir;
                            if (req.getCharacterEncoding() != null)
                                // It's common behaviour of browsers to encode their form input in the character
                                // encoding of the page, though they don't declare the used characterset explicetly
                                // for backward compatibility.
                                ir = new InputStreamReader(bais, req.getCharacterEncoding());
                            else
                                ir = new InputStreamReader(bais);
                            content.setLength(0);
                            while ((currentTransformByte = ir.read()) != -1) {
                                content.append((char) currentTransformByte);
                            }

                            putParameter(currentParam, content.toString());
                            break;
                        }
                    }
                }
            } else { // .. it's a file
                String filename = (String) headers.get("filename");
                if (filename != null && filename.length() != 0) {
                    // The filename may contain a full path.  Cut to just the filename.
                    int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
                    if (slash > -1) {
                        filename = filename.substring(slash + 1);
                    }
                    String name = (String) headers.get("name");

                    String contentType = (String) headers.get("content-type");
                    try {
                        uploadFile = File.createTempFile("wings_uploaded", "tmp");
                    } catch (IOException e) {
                        log.error("couldn't create temp file in '" + System.getProperty("java.io.tmpdir")
                                + "' (CATALINA_TMPDIR set correctly?)", e);
                        throw e;
                    }

                    UploadedFile upload = new UploadedFile(filename, contentType, uploadFile);
                    fileStream = new FileOutputStream(uploadFile);

                    fileStream = UploadFilterManager.createFilterInstance(name, fileStream);

                    AccessibleByteArrayOutputStream byteArray = new AccessibleByteArrayOutputStream();
                    byte[] bytes = null;

                    int blength = boundaryToken.length();
                    int i;
                    while ((currentByte = mimeStream.read()) != -1) {
                        byteArray.write(currentByte);
                        for (i = 0; i < blength; i++) {
                            if (boundaryToken.charAt(blength - i - 1) != byteArray.charAt(-i - 1)) {
                                i = 0;
                                if (byteArray.size() > 512 + blength + 2)
                                    byteArray.writeTo(fileStream, 512);
                                break;
                            }
                        }
                        if (i == blength) // end of part ..
                            break;
                    }
                    bytes = byteArray.toByteArray();
                    fileStream.write(bytes, 0, bytes.length - blength - 4);
                    fileStream.close();

                    files.put(name, upload);
                    putParameter(name, upload.toString());
                } else { // workaround for some netscape bug
                    int i;
                    int blength = boundaryToken.length();
                    while ((currentByte = mimeStream.read()) != -1) {
                        content.append((char) currentByte);
                        if (content.length() >= blength) {
                            for (i = 0; i < blength; i++) {
                                if (boundaryToken.charAt(blength - i - 1) != content
                                        .charAt(content.length() - i - 1)) {
                                    i = 0;
                                    break;
                                }
                            }
                            if (i == blength)
                                break;
                        }
                    }
                }
            }

            currentByte = mimeStream.read();
            if (currentByte == '\r' && mimeStream.read() != '\n')
                log.error("No line return char? " + currentByte);
            if (currentByte == '-' && mimeStream.read() != '-')
                log.error("?? No clue " + currentByte);
        }
    } catch (IOException ex) {
        // cleanup and store the exception for notification of SFileChooser
        log.warn("upload", ex);
        if (uploadFile != null)
            uploadFile.delete();
        setException(currentParam, ex);
    } finally {
        try {
            fileStream.close();
        } catch (Exception ign) {
        }
        try {
            mimeStream.close();
        } catch (Exception ign) {
        }
    }
}

From source file:nl.nn.adapterframework.http.RestListener.java

public String processRequest(String correlationId, String message, Map requestContext)
        throws ListenerException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) requestContext
            .get("restListenerServletRequest");
    String response;/*from   www.j  a  v a2s.c om*/
    String contentType = (String) requestContext.get("contentType");

    //Check if valid path
    String requestRestPath = (String) requestContext.get("restPath");
    if (!getRestPath().equals(requestRestPath)) {
        throw new ListenerException(
                "illegal restPath value [" + requestRestPath + "], must be '" + getRestPath() + "'");
    }

    //Check if consumes has been set or contentType is set to JSON
    if (getConsumes().equalsIgnoreCase("JSON")
            || "application/json".equalsIgnoreCase(httpServletRequest.getContentType())) {
        try {
            message = transformToXml(message);
        } catch (PipeRunException e) {
            throw new ListenerException("Failed to transform JSON to XML");
        }
    }

    //Check if contentType is not overwritten which disabled auto-converting and mediatype headers
    if (contentType == null || StringUtils.isEmpty(contentType) || contentType.equalsIgnoreCase("*/*")) {
        if (getProduces().equalsIgnoreCase("XML"))
            requestContext.put("contentType", "application/xml");
        if (getProduces().equalsIgnoreCase("JSON"))
            requestContext.put("contentType", "application/json");
        if (getProduces().equalsIgnoreCase("TEXT"))
            requestContext.put("contentType", "text/plain");

        response = super.processRequest(correlationId, message, requestContext);

        if (getProduces().equalsIgnoreCase("JSON")) {
            try {
                response = transformToJson(response);
            } catch (PipeRunException e) {
                throw new ListenerException("Failed to transform XML to JSON");
            }
        }
    } else {
        response = super.processRequest(correlationId, message, requestContext);
    }

    return response;
}

From source file:org.eclipse.rdf4j.http.server.repository.transaction.TransactionController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    ModelAndView result;//from  www .j  ava2s  .co m

    String reqMethod = request.getMethod();
    UUID transactionId = getTransactionID(request);
    logger.debug("transaction id: {}", transactionId);
    logger.debug("request content type: {}", request.getContentType());

    Transaction transaction = ActiveTransactionRegistry.INSTANCE.getTransaction(transactionId);

    if (transaction == null) {
        logger.warn("could not find transaction for transaction id {}", transactionId);
        throw new ClientHTTPException(SC_BAD_REQUEST,
                "unable to find registerd transaction for transaction id '" + transactionId + "'");
    }

    // if no action is specified in the request, it's a rollback (since it's
    // the only txn operation that does not require the action parameter).
    final String actionParam = request.getParameter(Protocol.ACTION_PARAM_NAME);
    final Action action = actionParam != null ? Action.valueOf(actionParam) : Action.ROLLBACK;
    switch (action) {
    case QUERY:
        // TODO SES-2238 note that we allow POST requests for backward
        // compatibility reasons with earlier
        // 2.8.x releases, even though according to the protocol spec only
        // PUT is allowed.
        if ("PUT".equals(reqMethod) || METHOD_POST.equals(reqMethod)) {
            logger.info("{} txn query request", reqMethod);
            result = processQuery(transaction, request, response);
            logger.info("{} txn query request finished", reqMethod);
        } else {
            throw new ClientHTTPException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                    "Method not allowed: " + reqMethod);
        }
        break;
    case GET:
        if ("PUT".equals(reqMethod) || METHOD_POST.equals(reqMethod)) {
            logger.info("{} txn get/export statements request", reqMethod);
            result = getExportStatementsResult(transaction, request, response);
            logger.info("{} txn get/export statements request finished", reqMethod);
        } else {
            throw new ClientHTTPException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                    "Method not allowed: " + reqMethod);
        }
        break;
    case SIZE:
        if ("PUT".equals(reqMethod) || METHOD_POST.equals(reqMethod)) {
            logger.info("{} txn size request", reqMethod);
            result = getSize(transaction, request, response);
            logger.info("{} txn size request finished", reqMethod);
        } else {
            throw new ClientHTTPException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                    "Method not allowed: " + reqMethod);
        }
        break;
    default:
        // TODO Action.ROLLBACK check is for backward compatibility with
        // older 2.8.x releases only. It's not in the protocol spec.
        if ("DELETE".equals(reqMethod) || (action.equals(Action.ROLLBACK)
                && ("PUT".equals(reqMethod) || METHOD_POST.equals(reqMethod)))) {
            logger.info("transaction rollback");
            try {
                transaction.rollback();
            } finally {
                ActiveTransactionRegistry.INSTANCE.deregister(transaction);
            }
            result = new ModelAndView(EmptySuccessView.getInstance());
            logger.info("transaction rollback request finished.");
        } else if ("PUT".equals(reqMethod) || METHOD_POST.equals(reqMethod)) {
            // TODO filter for appropriate PUT operations
            logger.info("{} txn operation", reqMethod);
            result = processModificationOperation(transaction, action, request, response);
            logger.info("PUT txn operation request finished.");
        } else {
            throw new ClientHTTPException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                    "Method not allowed: " + reqMethod);
        }
        break;
    }
    return result;
}

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

private CloseableHttpResponse forward(CloseableHttpClient httpclient, String verb, String uri,
        HttpServletRequest request, MultiValueMap<String, String> headers, MultiValueMap<String, String> params,
        InputStream requestEntity) throws Exception {
    Map<String, Object> info = this.helper.debug(verb, uri, headers, params, requestEntity);
    URL host = RequestContext.getCurrentContext().getRouteHost();
    HttpHost httpHost = getHttpHost(host);
    uri = StringUtils.cleanPath((host.getPath() + uri).replaceAll("/{2,}", "/"));
    HttpRequest httpRequest;/*from  w ww .  j ava  2 s . co m*/
    int contentLength = request.getContentLength();
    InputStreamEntity entity = new InputStreamEntity(requestEntity, contentLength,
            request.getContentType() != null ? ContentType.create(request.getContentType()) : null);
    switch (verb.toUpperCase()) {
    case "POST":
        HttpPost httpPost = new HttpPost(uri + this.helper.getQueryString(params));
        httpRequest = httpPost;
        httpPost.setEntity(entity);
        break;
    case "PUT":
        HttpPut httpPut = new HttpPut(uri + this.helper.getQueryString(params));
        httpRequest = httpPut;
        httpPut.setEntity(entity);
        break;
    case "PATCH":
        HttpPatch httpPatch = new HttpPatch(uri + this.helper.getQueryString(params));
        httpRequest = httpPatch;
        httpPatch.setEntity(entity);
        break;
    default:
        httpRequest = new BasicHttpRequest(verb, uri + this.helper.getQueryString(params));
        log.debug(uri + this.helper.getQueryString(params));
    }
    try {
        httpRequest.setHeaders(convertHeaders(headers));
        log.debug(httpHost.getHostName() + " " + httpHost.getPort() + " " + httpHost.getSchemeName());
        CloseableHttpResponse zuulResponse = forwardRequest(httpclient, httpHost, httpRequest);
        RequestContext.getCurrentContext().set("zuulResponse", zuulResponse);
        this.helper.appendDebug(info, zuulResponse.getStatusLine().getStatusCode(),
                revertHeaders(zuulResponse.getAllHeaders()));
        return zuulResponse;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        // httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.geoserver.rest.catalog.StyleController.java

@PutMapping(value = { "/styles/{styleName}", "/workspaces/{workspaceName}/styles/{styleName}" }, consumes = {
        MediaType.ALL_VALUE })/*from   w  ww. j av  a 2s  .  co m*/
public void stylePut(@PathVariable String styleName, @PathVariable(required = false) String workspaceName,
        @RequestParam(name = "raw", required = false, defaultValue = "false") boolean raw,
        HttpServletRequest request) throws IOException {

    if (workspaceName != null && catalog.getWorkspaceByName(workspaceName) == null) {
        throw new ResourceNotFoundException("Workspace " + workspaceName + " not found");
    }
    checkFullAdminRequired(workspaceName);
    StyleInfo s = catalog.getStyleByName(workspaceName, styleName);

    String contentType = request.getContentType();
    // String extentsion = "sld"; // TODO: determine this from path

    ResourcePool resourcePool = catalog.getResourcePool();
    if (raw) {
        writeRaw(s, request.getInputStream());
    } else {
        String content = IOUtils.toString(request.getInputStream());
        EntityResolver entityResolver = catalog.getResourcePool().getEntityResolver();
        for (StyleHandler format : Styles.handlers()) {
            for (Version version : format.getVersions()) {
                String mimeType = format.mimeType(version);
                if (!mimeType.equals(contentType)) {
                    continue; // skip this format
                }
                try {
                    StyledLayerDescriptor sld = format.parse(content, version, null, entityResolver);
                    Style style = Styles.style(sld);
                    if (format instanceof SLDHandler) {
                        s.setFormat(format.getFormat());
                        resourcePool.writeStyle(s, style, true);
                        catalog.save(s);
                    } else {
                        s.setFormat(format.getFormat());
                        writeRaw(s, request.getInputStream());
                    }
                    return;
                } catch (Exception invalid) {
                    throw new RestException("Invalid style:" + invalid.getMessage(), HttpStatus.BAD_REQUEST,
                            invalid);
                }
            }
        }
        throw new RestException("Unknown style fomrat '" + contentType + "'", HttpStatus.BAD_REQUEST);
    }
}

From source file:org.openrdf.http.server.repository.transaction.TransactionController.java

private ModelAndView getSparqlUpdateResult(RepositoryConnection conn, HttpServletRequest request,
        HttpServletResponse response) throws ServerHTTPException, ClientHTTPException, HTTPException {
    String sparqlUpdateString = null;
    final String contentType = request.getContentType();
    if (contentType != null && contentType.contains(Protocol.SPARQL_UPDATE_MIME_TYPE)) {
        try {//from  w  w w  .  ja  v  a2 s .  com
            final String encoding = request.getCharacterEncoding() != null ? request.getCharacterEncoding()
                    : "UTF-8";
            sparqlUpdateString = IOUtils.toString(request.getInputStream(), encoding);
        } catch (IOException e) {
            logger.warn("error reading sparql update string from request body", e);
            throw new ClientHTTPException(SC_BAD_REQUEST,
                    "could not read SPARQL update string from body: " + e.getMessage());
        }
    } else {
        sparqlUpdateString = request.getParameter(Protocol.UPDATE_PARAM_NAME);
    }

    logger.debug("SPARQL update string: {}", sparqlUpdateString);

    // 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 = null;
                if (!"null".equals(graphURI)) {
                    uri = conn.getValueFactory().createIRI(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 = null;
            if (!"null".equals(graphURI)) {
                uri = conn.getValueFactory().createIRI(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 = null;
                if (!"null".equals(defaultGraphURI)) {
                    uri = conn.getValueFactory().createIRI(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 = null;
                if (!"null".equals(namedGraphURI)) {
                    uri = conn.getValueFactory().createIRI(namedGraphURI);
                }
                dataset.addNamedGraph(uri);
            } catch (IllegalArgumentException e) {
                throw new ClientHTTPException(SC_BAD_REQUEST, "Illegal URI for named graph: " + namedGraphURI);
            }
        }
    }

    try {
        Update update = conn.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,
                        conn.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:bbdn.lti2.LTI2Servlet.java

@SuppressWarnings("unused")
public void handleSettingsRequest(HttpServletRequest request, HttpServletResponse response, String[] parts)
        throws java.io.IOException {

    String URL = request.getRequestURL().toString();
    System.out.println("URL=" + URL);
    String scope = parts[4];// ww  w .j  a  v  a2  s.  c o m
    System.out.println("scope=" + scope);

    String acceptHdr = request.getHeader("Accept");
    String contentHdr = request.getContentType();
    boolean acceptComplex = acceptHdr == null || acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) >= 0;

    System.out.println("accept=" + acceptHdr + " ac=" + acceptComplex);

    // Check the JSON on PUT and check the oauth_body_hash
    IMSJSONRequest jsonRequest = null;
    JSONObject requestData = null;
    if ("PUT".equals(request.getMethod())) {
        try {
            jsonRequest = new IMSJSONRequest(request);
            requestData = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, "Could not parse JSON", e);
            return;
        }
    }

    String consumer_key = "42";
    String profile = (String) PERSIST.get("profile");
    JSONObject providerProfile = (JSONObject) JSONValue.parse(profile);
    JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT);
    String oauth_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET);

    // Validate the incoming message
    Object retval = BasicLTIUtil.validateMessage(request, URL, oauth_secret, consumer_key);
    if (retval instanceof String) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, (String) retval, null);
        return;
    }

    // The URLs for the various settings resources
    String settingsUrl = getServiceURL(request) + SVC_Settings;
    String proxy_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxy + "/" + consumer_key;
    String binding_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxyBinding + "/" + "TBD";
    String link_url = settingsUrl + "/" + LTI2Util.SCOPE_LtiLink + "/" + "TBD";

    // Load and parse the old settings...
    JSONObject link_settings = LTI2Util.parseSettings((String) PERSIST.get(LTI2Util.SCOPE_LtiLink));
    JSONObject binding_settings = LTI2Util.parseSettings((String) PERSIST.get(LTI2Util.SCOPE_ToolProxyBinding));
    JSONObject proxy_settings = LTI2Util.parseSettings((String) PERSIST.get(LTI2Util.SCOPE_ToolProxy));

    // For a GET request we depend on LTI2Util to do the GET logic
    if ("GET".equals(request.getMethod())) {
        Object obj = LTI2Util.getSettings(request, scope, link_settings, binding_settings, proxy_settings,
                link_url, binding_url, proxy_url);

        if (obj instanceof String) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, (String) obj, null);
            return;
        }

        if (acceptComplex) {
            response.setContentType(StandardServices.TOOLSETTINGS_FORMAT);
        } else {
            response.setContentType(StandardServices.TOOLSETTINGS_SIMPLE_FORMAT);
        }

        JSONObject jsonResponse = (JSONObject) obj;
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter out = response.getWriter();
        System.out.println("jsonResponse=" + jsonResponse);
        out.println(jsonResponse.toString());
        return;
    } else if ("PUT".equals(request.getMethod())) {
        // This is assuming the rule that a PUT of the complex settings
        // format that there is only one entry in the graph and it is
        // the same as our current URL.  We parse without much checking.
        String settings = null;
        try {
            JSONArray graph = (JSONArray) requestData.get(LTI2Constants.GRAPH);
            if (graph.size() != 1) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                doErrorJSON(request, response, jsonRequest, "Only one graph entry allowed", null);
                return;
            }
            JSONObject firstChild = (JSONObject) graph.get(0);
            JSONObject custom = (JSONObject) firstChild.get(LTI2Constants.CUSTOM);
            settings = custom.toString();
        } catch (Exception e) {
            settings = jsonRequest.getPostBody();
        }
        PERSIST.put(scope, settings);
        System.out.println("Stored settings scope=" + scope);
        System.out.println("settings=" + settings);
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Method not handled=" + request.getMethod(), null);
    }
}

From source file:org.apache.struts2.dispatcher.Dispatcher.java

/**
 * Checks if request is a multipart request (a file upload request)
 *
 * @param request current servlet request
 * @return true if it is a multipart request
 *
 * @since 2.5.11/*  w w w  . ja  va 2  s . c  o m*/
 */
protected boolean isMultipartRequest(HttpServletRequest request) {
    String httpMethod = request.getMethod();
    String contentType = request.getContentType();

    return REQUEST_POST_METHOD.equalsIgnoreCase(httpMethod) && contentType != null
            && multipartValidationPattern.matcher(contentType.toLowerCase(Locale.ENGLISH)).matches();
}

From source file:org.opentestsystem.shared.docs.RequestLoggingInterceptor.java

@Override
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler, final Exception ex) throws Exception { // NOPMD
    FileOutputStream fileOut = null;
    try {/*from  ww w . j  a va 2s . c om*/
        LOGGER.debug(" ");
        LOGGER.debug(" ");

        LOGGER.debug("Request ");

        int rank = getRankOfApiDoc();
        // if rank is -1 skip it: that's the way to hide a api doc. Also exclude negative security testing
        if (rank >= ZERO && response.getStatus() != HttpStatus.SC_UNAUTHORIZED) {
            // block pmd concurrent hashmap warning
            ApiExample example = new ApiExample();
            example.setApiDocRank(rank);
            example.setRequestMethod(HttpMethod.valueOf(request.getMethod()));
            example.setRequestContentType(request.getContentType());
            example.setRequestUri(request.getRequestURI());
            String reqQueryString = request.getQueryString();
            //grab the parameters off the request instead
            if (StringUtils.isBlank(reqQueryString)) {
                if (request.getParameterMap() != null) {
                    List<String> params = new ArrayList<String>();
                    for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
                        String temp = entry.getKey() + "=";
                        if (entry.getValue() != null) {
                            temp += Joiner.on(",").join(entry.getValue());
                        }
                        params.add(temp);
                    }
                    reqQueryString = Joiner.on("&").join(params.toArray());
                }
            }
            example.setRequestQueryString(reqQueryString);

            LOGGER.debug(example.toString());

            InputStream instream = request.getInputStream();
            String requestData = "";
            if (instream != null) {
                StringWriter writer = new StringWriter();
                IOUtils.copy(instream, writer, "UTF-8");
                requestData = writer.toString();
            }
            example.setRequestData(requestData);
            LOGGER.debug("request data :" + example.getRequestData());
            LOGGER.debug(" ");

            LOGGER.debug("Response  ");
            MockHttpServletResponse res = (MockHttpServletResponse) response;
            example.setResponseContent(res.getContentAsString());
            example.setResponseCode(res.getStatus());

            LOGGER.debug("Server Response:" + example.getResponseContent());
            LOGGER.debug(" ");
            LOGGER.debug(" ");

            if (API_EXAMPLE_FILE != null) {
                fileOut = new FileOutputStream(API_EXAMPLE_FILE, true);
                ObjectMapper mapper = new ObjectMapper();
                byte[] bytes = mapper.writeValueAsBytes(example);
                fileOut.write(bytes);
                String str = ",";
                fileOut.write(str.getBytes());
                fileOut.close();
            }
        }
    } finally {
        if (fileOut != null) {
            fileOut.close();
        }
    }
}