Example usage for javax.servlet.http HttpServletResponse SC_FORBIDDEN

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

Introduction

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

Prototype

int SC_FORBIDDEN

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

Click Source Link

Document

Status code (403) indicating the server understood the request but refused to fulfill it.

Usage

From source file:com.recomdata.datasetexplorer.proxy.XmlHttpProxyServlet.java

public void doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) {
    StringBuffer bodyContent = null;
    OutputStream out = null;/* w w  w. jav a2s. c om*/
    PrintWriter writer = null;
    String serviceKey = null;

    try {
        BufferedReader in = req.getReader();
        String line = null;
        while ((line = in.readLine()) != null) {
            if (bodyContent == null)
                bodyContent = new StringBuffer();
            bodyContent.append(line);
        }
    } catch (Exception e) {
    }
    try {
        if (requireSession) {
            // check to see if there was a session created for this request
            // if not assume it was from another domain and blow up
            // Wrap this to prevent Portlet exeptions
            HttpSession session = req.getSession(false);
            if (session == null) {
                res.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        }
        serviceKey = req.getParameter("id");
        // only to preven regressions - Remove before 1.0
        if (serviceKey == null)
            serviceKey = req.getParameter("key");
        // check if the services have been loaded or if they need to be reloaded
        if (services == null || configUpdated()) {
            getServices(res);
        }
        String urlString = null;
        String xslURLString = null;
        String userName = null;
        String password = null;
        String format = "json";
        String callback = req.getParameter("callback");
        String urlParams = req.getParameter("urlparams");
        String countString = req.getParameter("count");
        // encode the url to prevent spaces from being passed along
        if (urlParams != null) {
            urlParams = urlParams.replace(' ', '+');
        }

        try {
            if (services.has(serviceKey)) {
                JSONObject service = services.getJSONObject(serviceKey);
                // default to the service default if no url parameters are specified
                if (urlParams == null && service.has("defaultURLParams")) {
                    urlParams = service.getString("defaultURLParams");
                }
                String serviceURL = service.getString("url");
                // build the URL
                if (urlParams != null && serviceURL.indexOf("?") == -1) {
                    serviceURL += "?";
                } else if (urlParams != null) {
                    serviceURL += "&";
                }
                String apikey = "";
                if (service.has("username"))
                    userName = service.getString("username");
                if (service.has("password"))
                    password = service.getString("password");
                if (service.has("apikey"))
                    apikey = service.getString("apikey");
                urlString = serviceURL + apikey;
                if (urlParams != null)
                    urlString += "&" + urlParams;
                if (service.has("xslStyleSheet")) {
                    xslURLString = service.getString("xslStyleSheet");
                }
            }
            //code for passing the url directly through instead of using configuration file
            else if (req.getParameter("url") != null) {
                String serviceURL = req.getParameter("url");
                // build the URL
                if (urlParams != null && serviceURL.indexOf("?") == -1) {
                    serviceURL += "?";
                } else if (urlParams != null) {
                    serviceURL += "&";
                }
                urlString = serviceURL;
                if (urlParams != null)
                    urlString += urlParams;
            } else {
                writer = res.getWriter();
                if (serviceKey == null)
                    writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required.");
                else
                    writer.write("XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not  found.");
                writer.flush();
                return;
            }
        } catch (Exception ex) {
            getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex);
        }

        Map paramsMap = new HashMap();
        paramsMap.put("format", format);
        // do not allow for xdomain unless the context level setting is enabled.
        if (callback != null && allowXDomain) {
            paramsMap.put("callback", callback);
        }
        if (countString != null) {
            paramsMap.put("count", countString);
        }

        InputStream xslInputStream = null;

        if (urlString == null) {
            writer = res.getWriter();
            writer.write(
                    "XmlHttpProxyServlet parameters:  id[Required] urlparams[Optional] format[Optional] callback[Optional]");
            writer.flush();
            return;
        }
        // default to JSON
        res.setContentType(responseContentType);
        out = res.getOutputStream();
        // get the stream for the xsl stylesheet
        if (xslURLString != null) {
            // check the web root for the resource
            URL xslURL = null;
            xslURL = ctx.getResource(resourcesDir + "xsl/" + xslURLString);
            // if not in the web root check the classpath
            if (xslURL == null) {
                xslURL = XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString);
            }
            if (xslURL != null) {
                xslInputStream = xslURL.openStream();
            } else {
                String message = "Could not locate the XSL stylesheet provided for service id " + serviceKey
                        + ". Please check the XMLHttpProxy configuration.";
                getLogger().severe(message);
                try {
                    out.write(message.getBytes());
                    out.flush();
                    return;
                } catch (java.io.IOException iox) {
                }
            }
        }
        if (!isPost) {
            xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password);
        } else {
            if (bodyContent == null)
                getLogger().info(
                        "XmlHttpProxyServlet attempting to post to url " + urlString + " with no body content");
            xhp.doPost(urlString, out, xslInputStream, paramsMap, bodyContent.toString(), req.getContentType(),
                    userName, password);
        }
    } catch (Exception iox) {
        iox.printStackTrace();
        getLogger().severe("XmlHttpProxyServlet: caught " + iox);
        try {
            writer = res.getWriter();
            writer.write(iox.toString());
            writer.flush();
        } catch (java.io.IOException ix) {
            ix.printStackTrace();
        }
        return;
    } finally {
        try {
            if (out != null)
                out.close();
            if (writer != null)
                writer.close();
        } catch (java.io.IOException iox) {
        }
    }
}

From source file:com.portfolio.data.attachment.FileServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // =====================================================================================
    initialize(request);//w ww  . ja v  a  2  s.c  om

    int userId = 0;
    int groupId = 0;
    String user = "";

    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    Credential credential = null;
    Connection c = null;
    try {
        //On initialise le dataProvider
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    /// uuid: celui de la ressource

    /// /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]

    String origin = request.getRequestURL().toString();

    /// Rcupration des paramtres
    String url = request.getPathInfo();
    String[] token = url.split("/");
    String uuid = token[1];

    String size = request.getParameter("size");
    if (size == null)
        size = "S";

    String lang = request.getParameter("lang");
    if (lang == null) {
        lang = "fr";
    }

    /// Vrification des droits d'accs
    if (!credential.hasNodeRight(userId, groupId, uuid, Credential.WRITE)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        //throw new Exception("L'utilisateur userId="+userId+" n'a pas le droit WRITE sur le noeud "+nodeUuid);
    }

    String data;
    String fileid = "";
    try {
        data = dataProvider.getResNode(uuid, userId, groupId);

        /// Parse les donnes
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader("<node>" + data + "</node>"));
        Document doc = documentBuilder.parse(is);
        DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0");
        LSSerializer serial = impl.createLSSerializer();
        serial.getDomConfig().setParameter("xml-declaration", false);

        /// Cherche si on a dj envoy quelque chose
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//filename[@lang=\"" + lang + "\"]";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        String filename = "";
        if (nodelist.getLength() > 0)
            filename = nodelist.item(0).getTextContent();

        if (!"".equals(filename)) {
            /// Already have one, per language
            String filterId = "//fileid[@lang='" + lang + "']";
            NodeList idlist = (NodeList) xPath.compile(filterId).evaluate(doc, XPathConstants.NODESET);
            if (idlist.getLength() != 0) {
                Element fileNode = (Element) idlist.item(0);
                fileid = fileNode.getTextContent();
            }
        }
    } catch (Exception e2) {
        e2.printStackTrace();
    }

    int last = fileid.lastIndexOf("/") + 1; // FIXME temp patch
    if (last < 0)
        last = 0;
    fileid = fileid.substring(last);
    /// request.getHeader("REFERRER");

    /// criture des donnes
    String urlTarget = "http://" + server + "/" + fileid;
    //      String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";

    // Unpack form, fetch binary data and send
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Configure a repository (to ensure a secure temp location is used)
    /*
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);
    //*/

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    String json = "";
    HttpURLConnection connection = null;
    // Parse the request
    try {
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if ("uploadfile".equals(item.getFieldName())) {
                // Send raw data
                InputStream inputData = item.getInputStream();

                /*
                URL urlConn = new URL(urlTarget);
                connection = (HttpURLConnection) urlConn.openConnection();
                connection.setDoOutput(true);
                connection.setUseCaches(false);                 /// We don't want to cache data
                connection.setInstanceFollowRedirects(false);   /// Let client follow any redirection
                String method = request.getMethod();
                connection.setRequestMethod(method);
                        
                String context = request.getContextPath();
                connection.setRequestProperty("app", context);
                //*/

                String fileName = item.getName();
                long filesize = item.getSize();
                String contentType = item.getContentType();

                //               /*
                connection = CreateConnection(urlTarget, request);
                connection.setRequestProperty("filename", uuid);
                connection.setRequestProperty("content-type", "application/octet-stream");
                connection.setRequestProperty("content-length", Long.toString(filesize));
                //*/
                connection.connect();

                OutputStream outputData = connection.getOutputStream();
                IOUtils.copy(inputData, outputData);

                /// Those 2 lines are needed, otherwise, no request sent
                int code = connection.getResponseCode();
                String msg = connection.getResponseMessage();

                InputStream objReturn = connection.getInputStream();
                StringWriter idResponse = new StringWriter();
                IOUtils.copy(objReturn, idResponse);
                fileid = idResponse.toString();

                connection.disconnect();

                /// Construct Json
                StringWriter StringOutput = new StringWriter();
                JsonWriter writer = new JsonWriter(StringOutput);
                writer.beginObject();
                writer.name("files");
                writer.beginArray();
                writer.beginObject();

                writer.name("name").value(fileName);
                writer.name("size").value(filesize);
                writer.name("type").value(contentType);
                writer.name("url").value(origin);
                writer.name("fileid").value(fileid);
                //                               writer.name("deleteUrl").value(ref);
                //                                       writer.name("deleteType").value("DELETE");
                writer.endObject();

                writer.endArray();
                writer.endObject();

                writer.close();

                json = StringOutput.toString();

                /*
                DataOutputStream datawriter = new DataOutputStream(connection.getOutputStream());
                byte[] buffer = new byte[1024];
                int dataSize;
                while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
                {
                   datawriter.write(buffer, 0, dataSize);
                }
                datawriter.flush();
                datawriter.close();
                //*/
                //               outputData.close();
                //               inputData.close();

                break;
            }
        }
    } catch (FileUploadException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    /*
    HttpURLConnection connection = CreateConnection( urlTarget, request );
            
    connection.setRequestProperty("referer", origin);
            
    /// Send post data
    ServletInputStream inputData = request.getInputStream();
    DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
            
    byte[] buffer = new byte[1024];
    int dataSize;
    while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
    {
       writer.write(buffer, 0, dataSize);
    }
    inputData.close();
    writer.close();
            
    /// So we can forward some Set-Cookie
    String ref = request.getHeader("referer");
            
    /// Prend le JSON du fileserver
    InputStream in = connection.getInputStream();
            
    InitAnswer(connection, response, ref);
            
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    StringBuilder builder = new StringBuilder();
    for( String line = null; (line = reader.readLine()) != null; )
       builder.append(line).append("\n");
    //*/

    /// Envoie la mise  jour au backend
    /*
    try
    {
       PostForm.updateResource(session.getId(), backend, uuid, lang, json);
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
    //*/

    connection.disconnect();
    /// Renvoie le JSON au client
    response.setContentType("application/json");
    PrintWriter respWriter = response.getWriter();
    respWriter.write(json);

    //      RetrieveAnswer(connection, response, ref);
    dataProvider.disconnect();
}

From source file:org.dataconservancy.ui.api.CollectionController.java

@RequestMapping(value = "/{idpart}", method = RequestMethod.GET)
public void handleCollectionGetRequest(@RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestHeader(value = "If-Match", required = false) String ifMatch,
        @RequestHeader(value = "If-None-Match", required = false) String ifNoneMatch,
        @RequestHeader(value = "If-Modified-Since", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date modifiedSince,
        HttpServletRequest request, HttpServletResponse response)
        throws IOException, ArchiveServiceException, BizPolicyException, BizInternalException {

    // Check to see if the user is authenticated (TODO: Spring Security should be responsible for this)
    // Note that the fact that the user has to be authenticated, and further authorized, is a policy decision,
    // but the pattern for the Project and Person controllers is that the Controller has handled this.
    final Person authenticatedUser = getAuthenticatedUser();

    // Rudimentary Accept Header handling; accepted values are */*, application/*, application/xml,
    // application/octet-stream
    if (mimeType != null && !(mimeType.contains(APPLICATION_XML) || mimeType.contains(ACCEPT_WILDCARD)
            || mimeType.contains(ACCEPT_APPLICATION_WILDCARD) || mimeType.contains(ACCEPT_OCTET_STREAM))) {
        response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                "Unacceptable value for 'Accept' header: '" + mimeType + "'");
        return;/*from  ww w  . j  a v a 2 s.  c  o  m*/
    }

    // Resolve the Request URL to the ID of the Collection (in this case URL == ID)
    String collectionId = requestUtil.buildRequestUrl(request);

    if (collectionId == null || collectionId.trim().isEmpty()) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // Get the Collection
    final Collection collection = getCollection(collectionId);

    // Calculate the ETag for the Collection, may be null.
    final String etag;
    if (collection != null) {
        etag = calculateEtag(collection);
    } else {
        etag = null;
    }

    // Handle the 'If-Match' header first; RFC 2616 14.24
    if (this.responseHeaderUtil.handleIfMatch(request, response, this.requestUtil, ifMatch, collection, etag,
            collectionId, "Collection")) {
        return;
    }

    final DateTime lastModified;
    if (collection != null) {
        lastModified = getLastModified(collection.getId());
    } else {
        lastModified = null;
    }

    // Handle the 'If-None-Match' header; RFC 2616 14.26
    if (this.responseHeaderUtil.handleIfNoneMatch(request, response, ifNoneMatch, collection, etag,
            collectionId, lastModified, modifiedSince)) {
        return;
    }

    if (collection == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Handle the 'If-Modified-Since' header; RFC 2616 14.26
    if (this.responseHeaderUtil.handleIfModifiedSince(request, response, modifiedSince, lastModified)) {
        return;
    }

    // Check to see if the user is authorized
    if (!authzService.canRetrieveCollection(authenticatedUser, collection)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Compose the Business Object Package
    Bop businessPackage = new Bop();
    businessPackage.addCollection(collection);

    // Serialize the package to an output stream
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bob.buildBusinessObjectPackage(businessPackage, out);
    out.close();

    this.responseHeaderUtil.setResponseHeaderFields(response, etag, out, lastModified);

    // Send the Response
    final ServletOutputStream servletOutputStream = response.getOutputStream();
    IOUtils.copy(new ByteArrayInputStream(out.toByteArray()), servletOutputStream);
    servletOutputStream.flush();
    servletOutputStream.close();
}

From source file:com.google.appengine.tools.mapreduce.MapReduceServlet.java

/**
 * Checks to ensure that the current request was sent via an AJAX request.
 *
 * If the request was not sent by an AJAX request, returns false, and sets
 * the response status code to 403. This protects against CSRF attacks against
 * AJAX only handlers./*from   w  ww  .java  2s.  co  m*/
 *
 * @return true if the request is a task queue request
 */
private boolean checkForAjax(HttpServletRequest request, HttpServletResponse response) {
    if (!"XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
        log.log(Level.SEVERE, "Received unexpected non-XMLHttpRequest command. Possible CSRF attack.");
        try {
            response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "Received unexpected non-XMLHttpRequest command.");
        } catch (IOException ioe) {
            throw new RuntimeException("Encountered error writing error", ioe);
        }
        return false;
    }
    return true;
}

From source file:net.bhira.sample.api.controller.CompanyController.java

/**
 * Delete the instance of {@link net.bhira.sample.model.Company} represented by given companyId.
 * In case of an error return the error message.
 * /*from  w ww  .  j  a  v  a 2s  .  c o m*/
 * @param companyId
 *            the ID for {@link net.bhira.sample.model.Company}.
 * @param response
 *            the http response to which the results will be written.
 * @return the error message, if save was not successful.
 */
@RequestMapping(value = "/company/{companyId}", method = RequestMethod.DELETE)
@ResponseBody
public Callable<String> deleteCompany(@PathVariable long companyId, HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            LOG.debug("servicing DELETE company/{}", companyId);
            String body = "";
            try {
                boolean success = companyService.delete(companyId);
                LOG.debug("DELETE company/{} status = {}", companyId, success);
                if (!success) {
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                }
            } catch (Exception ex) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                body = ex.getLocalizedMessage();
                LOG.warn("Error deleting company/{}. {}", companyId, body);
                LOG.debug("Delete error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:eu.dasish.annotation.backend.rest.TargetResource.java

/**
 * /*from   w  ww  .  jav  a 2 s.c  o m*/
 * @param targetIdentifier the external UUID of a target. 
 * @param fragmentDescriptor a string representing the location of the target within the cached-representation's content.
 * @param multiPart a {@link MultiPart} object representing two-part request body, containing the cached representation metadata 
 * {@link CachedRepresentationInfo} element} and a blob for a cached representation content.
 * @return a {@link CachedRepresentationInfo} element containing the metadata of the just added cached representation;
 * the difference with the input metadata is that a persistent external UUID is assigned, and the last-updated
 * attribute is changed.
 * @throws IOException  if sending an error fails.
 */
@POST
@Consumes("multipart/mixed")
@Produces(MediaType.APPLICATION_XML)
@Path("{targetid: " + BackendConstants.regExpIdentifier + "}/fragment/{fragmentDescriptor}/cached")
public JAXBElement<CachedRepresentationInfo> postCached(@PathParam("targetid") String targetIdentifier,
        @PathParam("fragmentDescriptor") String fragmentDescriptor, MultiPart multiPart) throws IOException {

    Map params = new HashMap();
    params.put("cachedInfo", multiPart.getBodyParts().get(0).getEntityAs(CachedRepresentationInfo.class));
    BodyPartEntity bpe = (BodyPartEntity) multiPart.getBodyParts().get(1).getEntity();
    params.put("cachedBlob", bpe.getInputStream());
    params.put("fragmentDescriptor", fragmentDescriptor);
    try {
        CachedRepresentationInfo result = (CachedRepresentationInfo) (new RequestWrappers(this))
                .wrapRequestResource(params, new PostCached(), Resource.TARGET, Access.ALL, targetIdentifier);
        if (result != null) {
            return new ObjectFactory().createCachedRepresentationInfo(result);
        } else {
            return new ObjectFactory().createCachedRepresentationInfo(new CachedRepresentationInfo());
        }
    } catch (NotInDataBaseException e1) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage());
        return new ObjectFactory().createCachedRepresentationInfo(new CachedRepresentationInfo());
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return new ObjectFactory().createCachedRepresentationInfo(new CachedRepresentationInfo());
    }
}

From source file:de.betterform.agent.web.servlet.XFormsRepeater.java

protected void doSubmissionReplaceAll(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    final Log LOG = LogFactory.getLog(XFormsRepeater.class);
    HttpSession session = request.getSession(false);
    WebProcessor webProcessor = WebUtil.getWebProcessor(request, response, session);
    if (session != null && webProcessor != null) {
        if (LOG.isDebugEnabled()) {
            Enumeration keys = session.getAttributeNames();
            if (keys.hasMoreElements()) {
                LOG.debug("--- existing keys in session --- ");
            }//w  w w.j av a  2  s  .c  om
            while (keys.hasMoreElements()) {
                String s = (String) keys.nextElement();
                LOG.debug("existing sessionkey: " + s + ":" + session.getAttribute(s));
            }
        }

        Map submissionResponse = webProcessor.checkForExitEvent().getContextInfo();
        if (submissionResponse != null) {

            if (LOG.isDebugEnabled()) {
                LOG.debug("handling submission/@replace='all'");
                Enumeration keys = session.getAttributeNames();
                if (keys.hasMoreElements()) {
                    LOG.debug("--- existing keys in http session  --- ");
                    while (keys.hasMoreElements()) {
                        String s = (String) keys.nextElement();
                        LOG.debug("existing sessionkey: " + s + ":" + session.getAttribute(s));
                    }
                } else {
                    LOG.debug("--- no keys left in http session  --- ");
                }
            }

            // copy header fields
            Map headerMap = (Map) submissionResponse.get("header");
            String name;
            String value;
            Iterator iterator = headerMap.keySet().iterator();
            while (iterator.hasNext()) {
                name = (String) iterator.next();
                if (name.equalsIgnoreCase("Transfer-Encoding")) {
                    // Some servers (e.g. WebSphere) may set a "Transfer-Encoding"
                    // with the value "chunked". This may confuse the client since
                    // XFormsServlet output is not encoded as "chunked", so this
                    // header is ignored.
                    continue;
                }

                value = (String) headerMap.get(name);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("added header: " + name + "=" + value);
                }

                response.setHeader(name, value);
            }

            // copy body stream
            InputStream bodyStream = (InputStream) submissionResponse.get("body");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            for (int b = bodyStream.read(); b > -1; b = bodyStream.read()) {
                outputStream.write(b);
            }

            // close streams
            bodyStream.close();
            outputStream.close();

            //kill XFormsSession
            WebUtil.removeSession(webProcessor.getKey());
            return;
        }
    }
    response.sendError(HttpServletResponse.SC_FORBIDDEN, "no submission response available");
}

From source file:eu.dasish.annotation.backend.rest.PrincipalResource.java

/**
 * /*from w  w  w  . j  a v  a  2  s .  co  m*/
 * @param externalIdentifier the external UUID of a principal.
 * @return a {@link CurrentPrincipalInfo} element containing "true" if the principal 
 * with externalIdentifier is logged-in in this session; 
 * with the current implementation does not make that much sense for me,
 * because the logged-in user knows his/her externalIDdentifier and knows that the other UUIDs
 * will be "not logged in", and therefore "false" is expected.
 * @throws IOException if sending an error fails.
 */
@GET
@Produces(MediaType.TEXT_XML)
@Path("{principalid}/current")
@Transactional(readOnly = true)
public JAXBElement<CurrentPrincipalInfo> getCurrentPrincipalInfo(
        @PathParam("principalid") String externalIdentifier) throws IOException {
    Map params = new HashMap<String, String>();
    params.put("externalId", externalIdentifier);
    try {
        CurrentPrincipalInfo result = (CurrentPrincipalInfo) (new RequestWrappers(this))
                .wrapRequestResource(params, new GetCurrentPrincipalInfo());
        return (result != null) ? (new ObjectFactory().createCurrentPrincipalInfo(result))
                : (new ObjectFactory().createCurrentPrincipalInfo(new CurrentPrincipalInfo()));
    } catch (NotInDataBaseException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return new ObjectFactory().createCurrentPrincipalInfo(new CurrentPrincipalInfo());
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return new ObjectFactory().createCurrentPrincipalInfo(new CurrentPrincipalInfo());
    }
}

From source file:com.qut.middleware.spep.filter.SPEPFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    if (!(servletRequest instanceof HttpServletRequest)) {
        throw new ServletException(Messages.getString("SPEPFilter.0")); //$NON-NLS-1$
    }/* www.  java2s. com*/
    if (!(servletResponse instanceof HttpServletResponse)) {
        throw new ServletException(Messages.getString("SPEPFilter.1")); //$NON-NLS-1$
    }

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String resource, decodedResource, requested, redirectURL;
    URL serviceHost;

    ServletContext spepContext = this.filterConfig.getServletContext().getContext(this.spepContextName);

    // Get servlet context.
    if (spepContext == null) {
        throw new ServletException(Messages.getString("SPEPFilter.2") + " " + this.spepContextName); //$NON-NLS-1$ //$NON-NLS-2$
    }

    // Establish SPEPProxy object.
    SPEPProxy spep;
    try {
        spep = Initializer.init(spepContext);
    } catch (Exception e) {
        this.logger.error(
                "Unable to process request to acces resource, SPEP is not responding, check cross context configuration is enabled \n"
                        + e.getLocalizedMessage());
        throw new ServletException(Messages.getString("SPEPFilter.3"), e); //$NON-NLS-1$
    }

    // Ensure SPEP startup.
    if (!spep.isStarted()) {
        // Don't allow anything to occur if SPEP hasn't started correctly.
        this.logger.error("Unable to process request to acces resource, SPEP is not initialized correcty ");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw new ServletException(Messages.getString("SPEPFilter.4")); //$NON-NLS-1$
    }

    // Get SPEP cookie.
    Cookie spepCookie = null;
    Cookie globalESOECookie = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(spep.getTokenName())) {
                spepCookie = cookie;
                this.logger.debug("Located spep cookie with value of " + spepCookie.getValue());
            }
            if (cookie.getName().equals(spep.getEsoeGlobalTokenName())) {
                globalESOECookie = cookie;
                this.logger
                        .debug("Located globalESOECookie cookie with value of " + globalESOECookie.getValue());
            }
        }
    }

    // value for re-determining session status after Authz request
    boolean validSession = false;

    // Check SPEP session is valid.
    if (spepCookie != null) {
        String sessionID = spepCookie.getValue();

        this.logger.info("Attempting to retrieve data for session with ID of " + sessionID);
        PrincipalSession PrincipalSession = spep.verifySession(sessionID);

        if (PrincipalSession != null) {
            this.logger.info("Located session with ID of " + sessionID);

            if (request.getSession().getAttribute(ATTRIBUTES) == null) {
                // over write with new data if it exists
                WORMHashMap<String, List<Object>> attributeMap = new WORMHashMap<String, List<Object>>();
                attributeMap.putAll(PrincipalSession.getAttributes());
                attributeMap.close();

                request.getSession().setAttribute(ATTRIBUTES, attributeMap);
                request.getSession().setAttribute(SPEP_SESSIONID, sessionID);
            }

            /*
             * This section of code is critical, we must pass the PEP an exact representation of what the user is
             * attempting to access additionally the PEP expects that the string is not in encoded form as it will
             * do exact matching, so we decode before passing our request to it.
             */
            resource = request.getRequestURI();
            if (request.getQueryString() != null)
                resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$

            decodedResource = decode(resource);

            SPEPProxy.decision authzDecision = spep.makeAuthzDecision(sessionID, decodedResource);

            // the authz processor may destroy the session if the PDP determines that the client
            // session is no longer valid, so we have to check it again
            if ((PrincipalSession = spep.verifySession(sessionID)) != null)
                validSession = true;

            if (validSession) {
                if (authzDecision == SPEPProxy.decision.permit) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was permissable");
                    chain.doFilter(request, response);
                    return;
                } else if (authzDecision == SPEPProxy.decision.deny) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was denied, forcing response of"
                            + HttpServletResponse.SC_FORBIDDEN);
                    response.setStatus(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN);
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                } else if (authzDecision == SPEPProxy.decision.error) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was in error, forcing response of"
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    throw new ServletException(Messages.getString("SPEPFilter.6")); //$NON-NLS-1$
                } else {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was undetermined, forcing response of"
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    throw new ServletException(Messages.getString("SPEPFilter.7")); //$NON-NLS-1$
                }
            }
        }

        /* Clear the local session object the supplied request is invalid */
        this.logger.debug("Invalidating session for ID of " + sessionID);
        request.getSession().invalidate();
    }

    /*
     * If we get to this stage, the user has not got a session established with this SPEP. We proceed to clear the
     * cookies configured by the SPEP to be cleared upon logout, since this is potentially the first time they have
     * come back to the SPEP since logging out.
     */
    List<Cookie> clearCookies = new Vector<Cookie>();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (spep.getLogoutClearCookies() != null) {
                for (Cookie clearCookie : spep.getLogoutClearCookies()) {
                    if (cookie.getName().equalsIgnoreCase(clearCookie.getName())) {
                        Cookie clearCookieCloneInsecure = (Cookie) clearCookie.clone();
                        clearCookieCloneInsecure.setMaxAge(0);
                        clearCookieCloneInsecure.setSecure(false);

                        clearCookies.add(clearCookieCloneInsecure);

                        // Don't need to process the inner loop again for this cookie.
                        break;
                    }
                }
            }
        }
    }

    /* Add the cookies to be cleared into the response object. */
    for (Cookie c : clearCookies)
        response.addCookie(c);

    /*
     * Remove any principal object details which may be in the session, this state can occur if the user has removed
     * their spepSession cookie but retained their jsessionid cookie
     */
    request.getSession().removeAttribute(ATTRIBUTES);

    /*
     * At this stage a determination needs to be made about allowing the request to pass SPEP without being hindered
     * due to lazy session initialization being configured if it isn't or we won't allow the request to pass for the
     * logical reasons below they will be forced to authenticate.
     */
    if (spep.isLazyInit()) {
        this.logger.info(
                "Lazy init is enabled on this SPEP instance, determining if request should be interrogated by SPEP");

        /*
         * We are being lazy in starting sessions, determine if user has already authenticated with an IDP (the
         * ESOE), if so we enforce a session (value is not important just that the cookie exists), if not figure out
         * if user is accessing something that has been configured to force a session to be established before it is
         * accessible
         */
        if (globalESOECookie == null) {
            this.logger.debug("globalESOECookie was not set for this request");

            boolean matchedLazyInitResource = false;
            resource = request.getRequestURI();
            if (request.getQueryString() != null)
                resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$

            decodedResource = decode(resource);

            for (String lazyInitResource : spep.getLazyInitResources()) {
                if (decodedResource.matches(lazyInitResource)) {
                    matchedLazyInitResource = true;
                    this.logger.info("Lazy session init attempt matched initialization query of "
                            + lazyInitResource + " from request of " + decodedResource);
                } else
                    this.logger.debug("Lazy session init attempt failed to match initialization query of "
                            + lazyInitResource + " from request of " + decodedResource);
            }

            // If we still have no reason to engage spep functionality for this request let the request pass
            if (matchedLazyInitResource) {
                if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.deny)) {
                    this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource
                            + " could be determined due to lazyInit, forwarding request to application");
                    chain.doFilter(request, response);
                    return;
                }
            } else {
                if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.permit)) {
                    this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource
                            + " could be determined due to lazyInit, forwarding request to application");
                    chain.doFilter(request, response);
                    return;
                }
            }
        }
    }

    /*
     * All attempts to provide resource access have failed, invoke SPEP to provide secure session establishment
     * Current request is B64 encoded and appended to request for SPEP to redirect users back to content dynamically
     */
    this.logger.debug("Failed all avenues to provide access to content");
    if (request.getQueryString() != null)
        requested = request.getRequestURI() + "?" + request.getQueryString();
    else
        requested = request.getRequestURI();

    /*
     * Determine if the request was directed to the service URL, if so redirect to that point. If not redirect to
     * the local node.
     */
    serviceHost = new URL(spep.getServiceHost());

    String ssoRedirect = spep.getSsoRedirect();
    String timestampParameter;
    if (ssoRedirect.indexOf('?') > -1) {
        timestampParameter = "&ts=" + System.currentTimeMillis();
    } else {
        timestampParameter = "?ts=" + System.currentTimeMillis();
    }

    if (request.getServerName().equals(serviceHost.getHost())) {
        /* Ensures that SSL offloading in Layer 7 environments is correctly handled */
        requested = spep.getServiceHost() + requested;
        String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes()));
        redirectURL = MessageFormat.format(spep.getServiceHost() + spep.getSsoRedirect(),
                new Object[] { base64RequestURI + timestampParameter });
    } else {
        String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes()));
        redirectURL = MessageFormat.format(spep.getSsoRedirect(),
                new Object[] { base64RequestURI + timestampParameter });
    }

    this.logger.debug("Redirecting to " + redirectURL + " to establish secure session");
    response.sendRedirect(redirectURL);
}

From source file:com.sonicle.webtop.core.app.servlet.ResourceRequest.java

protected LookupResult lookupNoCache(HttpServletRequest req, String reqPath) {
    String subject = null, subjectPath = null, jsPath = null, path = null, targetPath = null;
    boolean isVirtualUrl = false, jsPathFound = false;
    URL targetUrl = null;//from   ww  w  . j a v  a 2  s  . c om

    try {
        WebTopApp wta = WebTopApp.get(req);

        // Builds a convenient URL for the servlet relative URL
        try {
            //String reqPath = req.getPathInfo();
            //logger.trace("Requested path [{}]", reqPath);

            Matcher matcher = PATTERN_VIRTUAL_URL.matcher(reqPath);
            if (matcher.matches()) {
                // Matches URLs like: /{service.id}/{service.version}/{remaining.url.part}
                // Eg. /com.sonicle.webtop.core/5.1.1/laf/default/service.css
                //   {service.id} -> com.sonicle.webtop.core
                //   {service.version} -> 5.1.1
                //   {remaining.url.part} -> laf/default/service.css
                isVirtualUrl = true;
                subject = matcher.group(1);
                path = matcher.group(3);

                if (!wta.getServiceManager().hasService(subject)) {
                    return new Error(HttpServletResponse.SC_BAD_REQUEST, "Bad Request");
                }
                targetUrl = new URL("http://fake/client/" + subject + "/" + path);

            } else {
                isVirtualUrl = false;
                String[] urlParts = splitPath(reqPath);
                subject = urlParts[0];
                jsPath = wta.getServiceManager().getServiceJsPath(subject);
                jsPathFound = (jsPath != null);
                subjectPath = (jsPathFound) ? jsPath : urlParts[0];
                path = urlParts[1];

                targetUrl = new URL("http://fake/" + subjectPath + "/" + path);
            }
            targetPath = targetUrl.getPath();

            //logger.trace("Translated path [{}]", translPath);
            if (isForbidden(targetPath))
                return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");

        } catch (MalformedURLException ex1) {
            return new Error(HttpServletResponse.SC_BAD_REQUEST, "Bad Request");
        }

        if (!isVirtualUrl && path.startsWith("images")) {
            // Addresses domain public images
            // URLs like "/{domainPublicName}/images/{relativePathToFile}"
            // Eg.   "/1bbc048f/images/login.png"
            //      "/1bbc048f/images/sub/login.png"
            WebTopManager wtMgr = wta.getWebTopManager();

            String domainId = wtMgr.publicNameToDomainId(subject);
            if (StringUtils.isBlank(domainId)) {
                // We must support old-style URL using {domainInternetName}
                // instead of {domainPublicName}
                // Eg.   "/sonicle.com/images/login.png"
                domainId = wtMgr.internetNameToDomain(subject);
            }
            if (StringUtils.isBlank(domainId)) {
                return new Error(HttpServletResponse.SC_BAD_REQUEST, "Bad Request");
            }

            return lookupDomainImage(req, targetUrl, domainId);

        } else if (isVirtualUrl && subject.equals(CoreManifest.ID)
                && path.equals("resources/images/login.png")) {
            // Addresses login image
            // URLs like "/{serviceId}/{serviceVersion}/resources/images/login.png"
            // Eg.   "/com.sonicle.webtop.core/5.0.0/images/login.png"
            return lookupLoginImage(req, targetUrl);

        } else if (isVirtualUrl && subject.equals(CoreManifest.ID) && path.equals("resources/license.html")) {
            // Addresses licence page
            // URLs like "/{serviceId}/{serviceVersion}/resources/license.html"
            return lookupLicense(req, targetUrl);

        } else if (!isVirtualUrl && path.startsWith("whatsnew/")) {
            return lookupWhatsnew(req, targetUrl, path, subject);
        } else {
            if (StringUtils.endsWith(targetPath, ".js")) {
                String sessionId = ServletHelper.getSessionID(req);
                if (StringUtils.startsWith(path, "resources/vendor")
                        || StringUtils.startsWith(path, "resources/libs")) {
                    // If targets lib folder, simply return requested file without handling debug versions
                    return lookupJs(req, targetUrl, false);

                } else if (StringUtils.startsWith(path, "boot/")) {
                    return lookupJs(req, targetUrl, isJsDebug());

                } else if (StringUtils.startsWith(FilenameUtils.getBaseName(path), "Locale")) {
                    return lookupLocaleJs(req, targetUrl, subject);

                } else {
                    return lookupJs(req, targetUrl, isJsDebug());
                }

            } else if (StringUtils.startsWith(path, "laf")) {
                return lookupLAF(req, targetUrl, path, subject, subjectPath);

            } else {
                return lookupDefault(req, isVirtualUrl ? ClientCaching.YES : ClientCaching.AUTO, targetUrl);
            }
        }

    } catch (ServletException ex) {
        return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}