Search in sources :

Example 96 with ServletInputStream

use of javax.servlet.ServletInputStream in project OpenAM by OpenRock.

the class FSSSOAndFedService method doPost.

/**
     * Processes single sign on POST request.
     * @param request <code>HttpServletRequest</code> object
     * @param response <code>HttpServletResponse</code> object
     * @exception ServletException, IOException if an error occurred
     */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    FSUtils.debug.message("FSSSOAndFedService.doPost: Called");
    if ((request == null) || (response == null)) {
        response.sendError(response.SC_INTERNAL_SERVER_ERROR, FSUtils.bundle.getString("nullInputParameter"));
        return;
    }
    if (FSUtils.needSetLBCookieAndRedirect(request, response, true)) {
        return;
    }
    // Check if it's an LECP request
    if (isLECPRequest(request)) {
        // TODO: assume auth framework will understand this param
        String useForward = (String) request.getAttribute(Constants.FORWARD_PARAM);
        if (useForward != null && useForward.equals(Constants.FORWARD_YES_VALUE)) {
            // this is a forward POST after authentication, need to
            // use GET instead of POST here
            FSUtils.debug.message("FSSSOAndFedService.doPost: LECP forward");
            this.doGet(request, response);
        } else {
            try {
                MimeHeaders mimeHeaders = SAMLUtils.getMimeHeaders(request);
                ServletInputStream sInputStream = request.getInputStream();
                SOAPMessage soapMessage = msgFactory.createMessage(mimeHeaders, sInputStream);
                this.onMessage(request, response, soapMessage);
            } catch (SOAPException se) {
                throw new ServletException(se);
            }
        }
        return;
    }
    // obtain AuthnRequest message
    String enocodedAuthnRequest = request.getParameter(IFSConstants.POST_AUTHN_REQUEST_PARAM);
    if (enocodedAuthnRequest == null) {
        doGet(request, response);
        return;
    }
    enocodedAuthnRequest = enocodedAuthnRequest.replace(' ', '\n');
    if (FSUtils.debug.messageEnabled()) {
        FSUtils.debug.message("FSSSOAndFedService.doPost: " + "BASE64 encoded AuthnRequest at the RECEIVER: " + enocodedAuthnRequest);
    }
    //decode and create FSAuthnRequest object
    FSAuthnRequest authnRequest = null;
    try {
        authnRequest = FSAuthnRequest.parseBASE64EncodedString(enocodedAuthnRequest);
        if (authnRequest == null) {
            FSUtils.debug.error("FSSSOAndFedService: " + FSUtils.bundle.getString("invalidAuthnRequest"));
            String[] data = { FSUtils.bundle.getString("invalidAuthnRequest") };
            LogUtil.error(Level.INFO, LogUtil.INVALID_AUTHN_REQUEST, data);
            response.sendError(response.SC_BAD_REQUEST, FSUtils.bundle.getString("invalidAuthnRequest"));
            return;
        } else {
            if (FSUtils.debug.messageEnabled()) {
                FSUtils.debug.message("FSSSOAndFedService: " + "AuthnRequest received:" + authnRequest.toXMLString());
            }
        }
    } catch (FSException e) {
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("FSSSOAndFedService: " + FSUtils.bundle.getString("invalidAuthnRequest"), e);
        }
        response.sendError(response.SC_BAD_REQUEST, FSUtils.bundle.getString("invalidAuthnRequest"));
        return;
    }
    String metaAlias = null;
    String realm = null;
    String hostEntityId = null;
    IDPDescriptorType hostedDesc = null;
    BaseConfigType hostedConfig = null;
    try {
        metaAlias = FSServiceUtils.getMetaAlias(request);
        realm = IDFFMetaUtils.getRealmByMetaAlias(metaAlias);
        hostEntityId = metaManager.getEntityIDByMetaAlias(metaAlias);
        hostedDesc = metaManager.getIDPDescriptor(realm, hostEntityId);
        hostedConfig = metaManager.getIDPDescriptorConfig(realm, hostEntityId);
    } catch (Exception e) {
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("FSSSOAndFedService: couldn't obtain hosted entity id:", e);
        }
    }
    handleAuthnRequest(request, response, authnRequest, false, false, realm, hostEntityId, metaAlias, hostedDesc, hostedConfig);
    return;
}
Also used : ServletException(javax.servlet.ServletException) IDPDescriptorType(com.sun.identity.liberty.ws.meta.jaxb.IDPDescriptorType) BaseConfigType(com.sun.identity.federation.jaxb.entityconfig.BaseConfigType) MimeHeaders(javax.xml.soap.MimeHeaders) ServletInputStream(javax.servlet.ServletInputStream) SOAPException(javax.xml.soap.SOAPException) FSAuthnRequest(com.sun.identity.federation.message.FSAuthnRequest) FSException(com.sun.identity.federation.common.FSException) SOAPMessage(javax.xml.soap.SOAPMessage) ServletException(javax.servlet.ServletException) SOAPException(javax.xml.soap.SOAPException) SessionException(com.sun.identity.plugin.session.SessionException) FSException(com.sun.identity.federation.common.FSException) IOException(java.io.IOException) FSAccountMgmtException(com.sun.identity.federation.accountmgmt.FSAccountMgmtException)

Example 97 with ServletInputStream

use of javax.servlet.ServletInputStream in project OpenAM by OpenRock.

the class SAMLSOAPReceiver method doPost.

/**
     * Processes request coming from SOAP.
     *
     * @param req <code>HttpServletRequest</code> object.
     * @param resp <code>HttpServletResponse</code> object.
     * @throws ServletException if there is an error.
     * @throws IOException if there is an error.
     */
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException {
    if (SAMLUtils.getMaxContentLength() != 0) {
        int length = req.getContentLength();
        if (length == -1) {
            throw new ServletException(SAMLUtils.bundle.getString("unknownLength"));
        }
        if (length > SAMLUtils.getMaxContentLength()) {
            if (SAMLUtils.debug.messageEnabled()) {
                SAMLUtils.debug.message("content length too large" + length);
            }
            throw new ServletException(SAMLUtils.bundle.getString("largeContentLength"));
        }
    }
    String remoteAddr = ClientUtils.getClientIPAddress(req);
    Set partnerSourceID = null;
    if ((partnerSourceID = checkCaller(req, resp)) != null) {
        if (SAMLUtils.debug.messageEnabled()) {
            SAMLUtils.debug.message(" got request from a trusted server, " + "processing it now..");
        }
        try {
            MimeHeaders mimeHeaders = SAMLUtils.getMimeHeaders(req);
            ServletInputStream sInputStream = req.getInputStream();
            //Create the SOAPMessage from the reply
            SOAPMessage soapMessage = msgFactory.createMessage(mimeHeaders, sInputStream);
            SOAPMessage soapMessageReply = null;
            soapMessageReply = this.onMessage(req, resp, soapMessage, partnerSourceID);
            if (soapMessageReply != null) {
                if (soapMessageReply.saveRequired())
                    soapMessageReply.saveChanges();
                //Check to see if presence of SOAPFault
                if (containsFault(soapMessageReply)) {
                    if (SAMLUtils.debug.messageEnabled()) {
                        SAMLUtils.debug.message("Contains a SOAPFault!");
                    }
                    resp.setStatus(resp.SC_INTERNAL_SERVER_ERROR);
                } else {
                    resp.setStatus(resp.SC_OK);
                }
                //Send the response back to the senderby placing
                //the mime headers into the response, and
                //externalizing the soapmessage onto the response object
                SAMLUtils.setMimeHeaders(soapMessageReply.getMimeHeaders(), resp);
                ServletOutputStream sOutputStream = resp.getOutputStream();
                soapMessageReply.writeTo(sOutputStream);
                sOutputStream.flush();
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else {
        // its not trusted site
        SAMLUtils.debug.error("Error message from SOAP Receiver:" + remoteAddr + " is untrusted site");
        String[] data = { SAMLUtils.bundle.getString("untrustedSite"), remoteAddr };
        LogUtils.error(java.util.logging.Level.INFO, LogUtils.UNTRUSTED_SITE, data);
        SOAPMessage faultReply = FormSOAPError(resp, "Server", "untrustedSite", null);
        SAMLUtils.setMimeHeaders(faultReply.getMimeHeaders(), resp);
        ServletOutputStream sOutputStream = resp.getOutputStream();
        try {
            faultReply.writeTo(sOutputStream);
        } catch (SOAPException se) {
            throw new ServletException(se);
        }
        sOutputStream.flush();
    }
}
Also used : ServletException(javax.servlet.ServletException) MimeHeaders(javax.xml.soap.MimeHeaders) Set(java.util.Set) HashSet(java.util.HashSet) ServletInputStream(javax.servlet.ServletInputStream) ServletOutputStream(javax.servlet.ServletOutputStream) SOAPException(javax.xml.soap.SOAPException) SOAPMessage(javax.xml.soap.SOAPMessage) ServletException(javax.servlet.ServletException) SOAPException(javax.xml.soap.SOAPException) SAMLRequestVersionTooHighException(com.sun.identity.saml.common.SAMLRequestVersionTooHighException) SAMLRequesterException(com.sun.identity.saml.common.SAMLRequesterException) SAMLRequestVersionTooLowException(com.sun.identity.saml.common.SAMLRequestVersionTooLowException) SAMLException(com.sun.identity.saml.common.SAMLException)

Example 98 with ServletInputStream

use of javax.servlet.ServletInputStream in project cuba by cuba-platform.

the class FileUploadController method uploadFile.

/**
 * Method for simple file upload. File contents are placed in the request body. Optional file name parameter is
 * passed as a query param.
 */
@PostMapping(consumes = "!multipart/form-data")
public ResponseEntity<FileInfo> uploadFile(HttpServletRequest request, @RequestParam(required = false) String name) {
    try {
        String contentLength = request.getHeader("Content-Length");
        long size = 0;
        try {
            size = Long.parseLong(contentLength);
        } catch (NumberFormatException ignored) {
        }
        FileDescriptor fd = createFileDescriptor(name, size);
        ServletInputStream is = request.getInputStream();
        uploadToMiddleware(is, fd);
        saveFileDescriptor(fd);
        return createFileInfoResponseEntity(request, fd);
    } catch (Exception e) {
        log.error("File upload failed", e);
        throw new RestAPIException("File upload failed", "File upload failed", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Also used : ServletInputStream(javax.servlet.ServletInputStream) RestAPIException(com.haulmont.restapi.exception.RestAPIException) FileDescriptor(com.haulmont.cuba.core.entity.FileDescriptor) RestAPIException(com.haulmont.restapi.exception.RestAPIException) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 99 with ServletInputStream

use of javax.servlet.ServletInputStream in project Lucee by lucee.

the class ReqRspUtil method getRequestBody.

/**
 * returns the body of the request
 *
 * @param pc
 * @param deserialized
 *            if true lucee tries to deserialize the body based on the content-type, for example when the content type is "application/json"
 * @param defaultValue
 *            value returned if there is no body
 * @return
 */
public static Object getRequestBody(PageContext pc, boolean deserialized, Object defaultValue) {
    HttpServletRequest req = pc.getHttpServletRequest();
    MimeType contentType = getContentType(pc);
    String strContentType = contentType == MimeType.ALL ? null : contentType.toString();
    Charset cs = getCharacterEncoding(pc, req);
    boolean isBinary = !(strContentType == null || HTTPUtil.isTextMimeType(contentType) || strContentType.toLowerCase().startsWith("application/x-www-form-urlencoded"));
    if (req.getContentLength() > -1) {
        ServletInputStream is = null;
        try {
            // new byte[req.getContentLength()];
            byte[] data = IOUtil.toBytes(is = req.getInputStream());
            Object obj = NULL;
            if (deserialized) {
                int format = MimeType.toFormat(contentType, -1);
                obj = toObject(pc, data, format, cs, obj);
            }
            if (obj == NULL) {
                if (isBinary)
                    obj = data;
                else
                    obj = toString(data, cs);
            }
            return obj;
        } catch (Exception e) {
            pc.getConfig().getLog("application").error("request", e);
            return defaultValue;
        } finally {
            IOUtil.closeEL(is);
        }
    }
    return defaultValue;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletInputStream(javax.servlet.ServletInputStream) Charset(java.nio.charset.Charset) MimeType(lucee.commons.lang.mimetype.MimeType) PageException(lucee.runtime.exp.PageException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 100 with ServletInputStream

use of javax.servlet.ServletInputStream in project portal by ixinportal.

the class GzipRequestWrapper method getInputStream.

@Override
public ServletInputStream getInputStream() throws IOException {
    ServletInputStream stream = request.getInputStream();
    String contentEncoding = request.getHeader("Content-Encoding");
    // 如果对内容进行了压缩,则解压
    if (null != contentEncoding && contentEncoding.indexOf("gzip") != -1) {
        try {
            final GZIPInputStream gzipInputStream = new GZIPInputStream(stream);
            ServletInputStream newStream = new ServletInputStream() {

                @Override
                public boolean isFinished() {
                    return false;
                }

                @Override
                public boolean isReady() {
                    return false;
                }

                @Override
                public void setReadListener(ReadListener readListener) {
                }

                @Override
                public int read() throws IOException {
                    return gzipInputStream.read();
                }
            };
            return newStream;
        } catch (Exception e) {
            LOGGER.debug("ungzip content fail.", e);
        }
    }
    return stream;
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) ServletInputStream(javax.servlet.ServletInputStream) ReadListener(javax.servlet.ReadListener) IOException(java.io.IOException)

Aggregations

ServletInputStream (javax.servlet.ServletInputStream)148 IOException (java.io.IOException)73 HttpServletRequest (javax.servlet.http.HttpServletRequest)60 Test (org.junit.Test)59 HttpServletResponse (javax.servlet.http.HttpServletResponse)50 ServletException (javax.servlet.ServletException)42 ByteArrayInputStream (java.io.ByteArrayInputStream)32 ReadListener (javax.servlet.ReadListener)28 CountDownLatch (java.util.concurrent.CountDownLatch)26 HttpServlet (javax.servlet.http.HttpServlet)21 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)20 InterruptedIOException (java.io.InterruptedIOException)18 AsyncContext (javax.servlet.AsyncContext)18 ServletOutputStream (javax.servlet.ServletOutputStream)18 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)18 ByteArrayOutputStream (java.io.ByteArrayOutputStream)17 PrintWriter (java.io.PrintWriter)16 Request (org.eclipse.jetty.server.Request)16 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)15 Test (org.junit.jupiter.api.Test)11