Example usage for javax.servlet.http HttpServletRequest getRequestURL

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

Introduction

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

Prototype

public StringBuffer getRequestURL();

Source Link

Document

Reconstructs the URL the client used to make the request.

Usage

From source file:org.keycloak.example.ProductServiceAccountServlet.java

private void loadProducts(HttpServletRequest req) {
    HttpClient client = getHttpClient();
    String token = (String) req.getSession().getAttribute(TOKEN);

    String requestOrigin = UriUtils.getOrigin(req.getRequestURL().toString());
    HttpGet get = new HttpGet(requestOrigin + "/database/products");
    if (token != null) {
        get.addHeader("Authorization", "Bearer " + token);
    }/*from  w ww .j a va2 s.co  m*/
    try {
        HttpResponse response = client.execute(get);
        HttpEntity entity = response.getEntity();
        int status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            String json = getContent(entity);
            String error = "Failed retrieve products. Status: " + status;
            req.setAttribute(ERROR, error);
        } else if (entity == null) {
            req.setAttribute(ERROR, "No entity");
        } else {
            String products = getContent(entity);
            req.setAttribute(PRODUCTS, products);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
        req.setAttribute(ERROR,
                "Failed retrieve products. IOException occured. See server.log for details. Message is: "
                        + ioe.getMessage());
    }
}

From source file:de.sub.goobi.export.download.ExportPdf.java

@Override
public boolean startExport(Process myProcess, URI inZielVerzeichnis) throws ReadException, IOException,
        PreferencesException, TypeNotAllowedForParentException, WriteException {

    /*//from   w  w  w.  j av a 2  s  .  c  o m
     * Read Document
     */
    Fileformat gdzfile = serviceManager.getProcessService().readMetadataFile(myProcess);
    URI zielVerzeichnis = prepareUserDirectory(inZielVerzeichnis);
    this.myPrefs = serviceManager.getRulesetService().getPreferences(myProcess.getRuleset());

    /*
     * first of all write mets-file in images-Folder of process
     */
    URI metsTempFile = fileService.createResource(myProcess.getTitle() + ".xml");
    writeMetsFile(myProcess, metsTempFile, gdzfile, true);
    Helper.setMeldung(null, myProcess.getTitle() + ": ", "mets file created");
    Helper.setMeldung(null, myProcess.getTitle() + ": ", "start pdf generation now");

    if (logger.isDebugEnabled()) {
        logger.debug("METS file created: " + metsTempFile);
    }

    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
    String fullpath = req.getRequestURL().toString();
    String servletpath = context.getExternalContext().getRequestServletPath();
    String myBasisUrl = fullpath.substring(0, fullpath.indexOf(servletpath));

    if (!ConfigCore.getBooleanParameter("pdfAsDownload")) {
        /*
         * use contentserver api for creation of pdf-file
         */
        CreatePdfFromServletThread pdf = new CreatePdfFromServletThread();
        pdf.setMetsURL(metsTempFile.toURL());
        pdf.setTargetFolder(zielVerzeichnis);
        pdf.setInternalServletPath(myBasisUrl);
        if (logger.isDebugEnabled()) {
            logger.debug("Taget directory: " + zielVerzeichnis);
            logger.debug("Using ContentServer2 base URL: " + myBasisUrl);
        }
        pdf.initialize(myProcess);
        pdf.start();
    } else {

        GetMethod method = null;
        try {
            /*
             * define path for mets and pdfs
             */
            URL kitodoContentServerUrl = null;
            String contentServerUrl = ConfigCore.getParameter("kitodoContentServerUrl");
            Integer contentServerTimeOut = ConfigCore.getIntParameter("kitodoContentServerTimeOut", 60000);

            /*
             * using mets file
             */

            if (new MetadatenVerifizierung().validate(myProcess) && metsTempFile.toURL() != null) {
                /*
                 * if no contentserverurl defined use internal
                 * goobiContentServerServlet
                 */
                if (contentServerUrl == null || contentServerUrl.length() == 0) {
                    contentServerUrl = myBasisUrl + "/gcs/gcs?action=pdf&metsFile=";
                }
                kitodoContentServerUrl = new URL(contentServerUrl + metsTempFile.toURL()
                        + AND_TARGET_FILE_NAME_IS + myProcess.getTitle() + PDF_EXTENSION);
                /*
                 * mets data does not exist or is invalid
                 */

            } else {
                if (contentServerUrl == null || contentServerUrl.length() == 0) {
                    contentServerUrl = myBasisUrl + "/cs/cs?action=pdf&images=";
                }
                FilenameFilter filter = new FileNameMatchesFilter("\\d*\\.tif");
                URI imagesDir = serviceManager.getProcessService().getImagesTifDirectory(true, myProcess);
                ArrayList<URI> meta = fileService.getSubUris(filter, imagesDir);
                int capacity = contentServerUrl.length() + (meta.size() - 1) + AND_TARGET_FILE_NAME_IS.length()
                        + myProcess.getTitle().length() + PDF_EXTENSION.length();
                TreeSet<String> filenames = new TreeSet<>(new MetadatenHelper(null, null));
                for (URI data : meta) {
                    String file = data.toURL().toString();
                    filenames.add(file);
                    capacity += file.length();
                }
                StringBuilder url = new StringBuilder(capacity);
                url.append(contentServerUrl);
                boolean subsequent = false;
                for (String f : filenames) {
                    if (subsequent) {
                        url.append('$');
                    } else {
                        subsequent = true;
                    }
                    url.append(f);
                }
                url.append(AND_TARGET_FILE_NAME_IS);
                url.append(myProcess.getTitle());
                url.append(PDF_EXTENSION);
                kitodoContentServerUrl = new URL(url.toString());
            }

            /*
             * get pdf from servlet and forward response to file
             */
            method = new GetMethod(kitodoContentServerUrl.toString());
            method.getParams().setParameter("http.socket.timeout", contentServerTimeOut);

            if (!context.getResponseComplete()) {
                HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
                String fileName = myProcess.getTitle() + PDF_EXTENSION;
                ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
                String contentType = servletContext.getMimeType(fileName);
                response.setContentType(contentType);
                response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
                response.sendRedirect(kitodoContentServerUrl.toString());
                context.responseComplete();
            }
            if (metsTempFile.toURL() != null) {
                File tempMets = new File(metsTempFile.toURL().toString());
                tempMets.delete();
            }
        } catch (Exception e) {

            /*
             * report Error to User as Error-Log
             */
            String text = "error while pdf creation: " + e.getMessage();
            URI uri = zielVerzeichnis.resolve(myProcess.getTitle() + ".PDF-ERROR.log");
            try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(fileService.write(uri)))) {
                output.write(text);
            } catch (IOException e1) {
                logger.error(e1);
            }
            return false;
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
    }
    return true;
}

From source file:au.org.paperminer.main.LocationFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest httpReq = (HttpServletRequest) req;
    String remoteReq = httpReq.getRequestURL().toString();
    int idx = remoteReq.lastIndexOf('/');

    m_logger.info("LocationFilter doFilter" + remoteReq.substring(idx));

    if (remoteReq.substring(idx).startsWith("/ref")) {
        m_logger.debug(" location filter references");
        getReferences((HttpServletRequest) req, (HttpServletResponse) resp);
    } else if (remoteReq.substring(idx).startsWith("/gs")) {
        m_logger.debug(" location filter GS info");
        getGSDetails((HttpServletRequest) req, (HttpServletResponse) resp);
    } else if (remoteReq.substring(idx).startsWith("/q")) {
        m_logger.debug(" location filter find location(s)");
        findLocation((HttpServletRequest) req, (HttpServletResponse) resp);
    } else if (remoteReq.substring(idx).startsWith("/ltln")) {
        m_logger.debug(" location filter find location(s)");
        findLatLongLocation((HttpServletRequest) req, (HttpServletResponse) resp);
    } else if (remoteReq.substring(idx).startsWith("/rm")) {
        m_logger.debug(" location filter strikeout");
        strikeout((HttpServletRequest) req, (HttpServletResponse) resp);
    } else if (remoteReq.substring(idx).startsWith("/add")) {
        m_logger.debug(" location filter add GS record");
        add((HttpServletRequest) req, (HttpServletResponse) resp);
    } else if (remoteReq.substring(idx).startsWith("/ins")) {
        m_logger.debug(" location filter insert location and add GS record");
        insert((HttpServletRequest) req, (HttpServletResponse) resp);
    }/*from  www.  ja  va  2 s  .c  om*/

    m_logger.debug("LocationFilter chaining... ?");
    filterChain.doFilter(req, resp);
    m_logger.debug("LocationFilter chaining complete");
    return;
}

From source file:com.codenvy.ide.git.VFSPermissionsFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    int tokenPlace;
    String lastTokenBeforePath = "/" + gitServerUriPrefix + "/";
    if ((tokenPlace = req.getRequestURL().indexOf(lastTokenBeforePath)) != -1) {
        //get path to project
        String url = req.getRequestURL().substring(tokenPlace + lastTokenBeforePath.length());
        url = url.replaceFirst("/info/refs", "");
        url = url.replaceFirst("/git-upload-pack", "");
        //adaptation to fs
        url = url.replaceAll("/", Matcher.quoteReplacement(File.separator));
        //search for dotVFS directory
        File projectDirectory = Paths.get(vfsRoot, url).toFile();
        String auth;/* w w w  .  ja  va 2 s. co  m*/
        String userName = "";
        String password = "";
        if ((auth = req.getHeader("authorization")) != null) {
            //get encoded password phrase
            String userAndPasswordEncoded = auth.substring(6);
            // decode Base64 user:password
            String userAndPasswordDecoded = new String(Base64.decodeBase64(userAndPasswordEncoded));
            //get username and password separator ':'
            int betweenUserAndPassword = userAndPasswordDecoded.indexOf(':');
            //get username - it is before first ':'
            userName = userAndPasswordDecoded.substring(0, betweenUserAndPassword);
            //get password - it is after first ':'
            password = userAndPasswordDecoded.substring(betweenUserAndPassword + 1);
        }

        // Check if user authenticated and has permissions to project, or send response code 403
        boolean needLogout = false;
        String token = null;
        User user;
        try {
            if (!userName.isEmpty()) {
                if (password.equals("x-che")) { // internal SSO
                    token = userName;
                } else {
                    token = getToken(userName, password);
                    if (token == null) {
                        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
                        return;
                    }
                    needLogout = true;
                }
                user = getUserBySSO(token);
                EnvironmentContext.getCurrent().setUser(user);
            }

            if (!hasAccessToItem(projectDirectory.getParentFile().getName(), projectDirectory.getName())) {
                if (!userName.isEmpty()) {
                    // Authenticated but no access
                    ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                } else {
                    // Not authenticated, try again with credentials
                    ((HttpServletResponse) response).addHeader("Cache-Control", "private");
                    ((HttpServletResponse) response).addHeader("WWW-Authenticate", "Basic");
                    ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    return;
                }
            }
        } finally {
            if (needLogout) {
                logout();
            }
            EnvironmentContext.reset();
        }
    }
    chain.doFilter(req, response);
}

From source file:com.alibaba.sample.petstore.web.common.PetstoreUserAuth.java

public void onDeny(Status status) throws Exception {
    HttpServletRequest request = status.rundata.getRequest();
    HttpServletResponse response = status.rundata.getResponse();
    URIBroker redirectURI = uriBrokerService.getURIBroker(brokerId);

    assertNotNull(redirectURI, "no URI broker found: %s", brokerId);

    StringBuffer buf = request.getRequestURL();
    String queryString = trimToNull(request.getQueryString());

    if (queryString != null) {
        buf.append('?').append(queryString);
    }/*from  w w w .  j  a  v a 2  s .  co  m*/

    String returnURL = buf.toString();

    response.sendRedirect(redirectURI.addQueryData(returnKey, returnURL).render());
}

From source file:com.qcadoo.view.internal.resource.module.UniversalResourceModule.java

private String getContentTypeFromURI(final HttpServletRequest request) {
    String[] arr = request.getRequestURI().split("\\.");
    String ext = arr[arr.length - 1];
    if ("js".equals(ext)) {
        return "text/javascript";
    } else if ("css".equals(ext)) {
        return "text/css";
    } else {//from www. j a v a 2s  .  c  om
        return URLConnection.guessContentTypeFromName(request.getRequestURL().toString());
    }
}

From source file:org.sakaiproject.imagegallery.web.MultiFileUploaderController.java

public ModelAndView singleFileUpload(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    if (log.isInfoEnabled())
        log.info("req contextPath=" + request.getContextPath() + ", pathInfo=" + request.getPathInfo()
                + ", query=" + request.getQueryString() + ", URI=" + request.getRequestURI() + ", URL="
                + request.getRequestURL() + ", servlet=" + request.getServletPath());
    if (request instanceof MultipartHttpServletRequest) {
        return new ModelAndView(new RedirectView(
                "/site/AddInformationToImages?imageIds=" + storeNewImage((MultipartHttpServletRequest) request),
                true));/*from ww  w  . j a  va 2 s . c o m*/
    }

    return null;
}

From source file:edu.mayo.qdm.webapp.rest.controller.TranslatorController.java

/**
 * Gets the exceuctions.//w  w  w.j a  v a  2  s .  co m
 *
 * @param request the request
 * @return the exceuctions
 * @throws Exception the exception
 */
@RequestMapping(value = "executor/executions", method = RequestMethod.GET)
public Object getExceuctions(HttpServletRequest request) throws Exception {

    String requestUrl = request.getRequestURL().toString();
    requestUrl = StringUtils.replace(requestUrl, "/executions", "/execution/{id}/{resource}");

    UriTemplate template = new UriTemplate(requestUrl);

    Set<ExecutionInfo> dataFiles = this.fileSystemResolver.getExecutionInfo();

    Executions executions = new Executions(dataFiles, template);
    String xml = xmlProcessor.executionsToXml(executions);

    return this.buildResponse(request, executions, xml);
}

From source file:org.broadleafcommerce.vendor.authorizenet.web.controller.BroadleafAuthorizeNetController.java

@RequestMapping(value = "/process", method = RequestMethod.POST, produces = "text/html")
public @ResponseBody String relay(HttpServletRequest request, HttpServletResponse response, Model model)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException,
        BroadleafAuthorizeNetException {
    LOG.debug("Authorize URL request - " + request.getRequestURL().toString());
    LOG.debug("Authorize Request Parameter Map (params: [" + requestParamToString(request) + "])");

    PaymentResponseDTO responseDTO = new PaymentResponseDTO(PaymentType.CREDIT_CARD,
            AuthorizeNetGatewayType.AUTHORIZENET).rawResponse(webResponsePrintService.printRequest(request));

    Result result = Result.createResult(configuration.getLoginId(), configuration.getMd5Key(),
            request.getParameterMap());/*from   ww  w .j  ava 2  s  . c  o m*/

    boolean approved = false;
    if (result.getResponseCode().toString().equals("APPROVED")) {
        approved = true;
    }

    String tps = authorizeNetCheckoutService.createTamperProofSeal(
            result.getResponseMap().get(MessageConstants.BLC_CID),
            result.getResponseMap().get(MessageConstants.BLC_OID));
    responseDTO.valid(tps.equals(result.getResponseMap().get(MessageConstants.BLC_TPS)));

    System.out.println("requestmap: " + webResponsePrintService.printRequest(request));
    if (approved && responseDTO.isValid()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Transaction success for order "
                    + result.getResponseMap().get(AuthNetField.X_TRANS_ID.getFieldName()));
            LOG.debug("Response for Authorize.net to relay to client: ");
            LOG.debug(authorizeNetCheckoutService.buildRelayResponse(configuration.getConfirmUrl(), result));
        }
        return authorizeNetCheckoutService.buildRelayResponse(configuration.getConfirmUrl(), result);
    }

    return authorizeNetCheckoutService.buildRelayResponse(configuration.getErrorUrl(), result);
}

From source file:com.temenos.interaction.core.web.RequestContextFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest servletRequest = (HttpServletRequest) request;

    String requestURI = servletRequest.getRequestURI();
    requestURI = StringUtils.removeStart(requestURI,
            servletRequest.getContextPath() + servletRequest.getServletPath());
    String baseURL = StringUtils.removeEnd(servletRequest.getRequestURL().toString(), requestURI);

    Map<String, List<String>> headersMap = new HashMap<>();
    Enumeration<String> headerNames = servletRequest.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            List<String> valuesList = Collections.list(servletRequest.getHeaders(headerName));
            headersMap.put(headerName, valuesList);
        }/*  w  w  w. j  a  v a  2  s.  c o m*/
    }

    RequestContext ctx;
    Principal userPrincipal = servletRequest.getUserPrincipal();
    if (userPrincipal != null) {
        ctx = new RequestContext(baseURL, servletRequest.getRequestURI(),
                servletRequest.getHeader(RequestContext.HATEOAS_OPTIONS_HEADER), userPrincipal, headersMap);
    } else {
        ctx = new RequestContext(baseURL, servletRequest.getRequestURI(),
                servletRequest.getHeader(RequestContext.HATEOAS_OPTIONS_HEADER), headersMap);
    }

    RequestContext.setRequestContext(ctx);

    try {
        chain.doFilter(request, response);
    } finally {
        RequestContext.clearRequestContext();
    }
}