Java Code Examples for javax.servlet.http.HttpServletRequest#getPathInfo()

The following examples show how to use javax.servlet.http.HttpServletRequest#getPathInfo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FaultToEndpointServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handle(String target, Request baseRequest, HttpServletRequest request,
                   HttpServletResponse response) throws IOException, ServletException {
    response.setContentType("text/html;charset=utf-8");

    //System.out.println("In handler: " + request.getContentLength());

    byte[] bytes = new byte[1024];
    InputStream in = request.getInputStream();
    while (in.read(bytes) > -1) {
        //nothing
    }

    faultRequestPath = request.getPathInfo();
    if ("/faultTo".equals(faultRequestPath)) {
        response.setStatus(HttpServletResponse.SC_ACCEPTED);
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
    PrintWriter writer = response.getWriter();
    writer.println("Received");
    writer.close();
    baseRequest.setHandled(true);
}
 
Example 2
Source File: WorkbenchGateway.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void service(final HttpServletRequest req, final HttpServletResponse resp)
		throws ServletException, IOException {
	final String change = getChangeServerPath();
	if (change != null && change.equals(req.getPathInfo())) {
		try {
			changeServer(req, resp);
		} catch (QueryResultHandlerException e) {
			throw new IOException(e);
		}
	} else {
		final WorkbenchServlet servlet = findWorkbenchServlet(req, resp);
		if (servlet == null) {
			// Redirect to change-server-path
			final StringBuilder uri = new StringBuilder(req.getRequestURI());
			if (req.getPathInfo() != null) {
				uri.setLength(uri.length() - req.getPathInfo().length());
			}
			resp.sendRedirect(uri.append(getChangeServerPath()).toString());
		} else {
			servlet.service(req, resp);
		}
	}
}
 
Example 3
Source File: AccessServlet.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * respond to an HTTP GET request
 * 
 * @param req
 *        HttpServletRequest object with the client request
 * @param res
 *        HttpServletResponse object back to the client
 * @exception ServletException
 *            in case of difficulties
 * @exception IOException
 *            in case of difficulties
 */
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
	// process any login that might be present
	basicAuth.doLogin(req);
	// catch the login helper requests
	String option = req.getPathInfo();
	String[] parts = option.split("/");
	if ((parts.length == 2) && ((parts[1].equals("login"))))
	{
		doLogin(req, res, null);
	}	
	else
	{
		dispatch(req, res);
	}
}
 
Example 4
Source File: ImagesService.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@GET
@Path("/getImage")
@Produces(MediaType.APPLICATION_JSON)
@UserConstraint(functionalities = { SpagoBIConstants.IMAGES_MANAGEMENT })
public void getImage(@Context HttpServletRequest req, @Context HttpServletResponse resp) {
	try {
		IImagesDAO dao = DAOFactory.getImagesDAO();
		IEngUserProfile profile = (IEngUserProfile) req.getSession().getAttribute(IEngUserProfile.ENG_USER_PROFILE);
		dao.setUserProfile(profile);
		Integer id = Util.getNumberOrNull(req.getParameter("IMAGES_ID"));
		String preview = req.getParameter("preview");
		SbiImages imageDB = dao.loadImage(id);
		String contentType = "";
		byte[] content;
		if (preview != null) {
			content = imageDB.getContentIco();
		} else {
			content = imageDB.getContent();
		}
		flushFileToResponse(resp, contentType, content);
	} catch (Throwable t) {
		logger.error("An unexpected error occured while executing service \"getImage\"", t);
		throw new SpagoBIServiceException(req.getPathInfo(), "An unexpected error occured while executing service \"getImage\"", t);
	}
}
 
Example 5
Source File: FlagIconServlet.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
/**
 *
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
	String lgId = request.getPathInfo();
	OutputStream os = null;

	try {
		if (lgId.length() > 1) {
			Language language = LanguageDAO.findByPk(lgId.substring(1)); // The first character / must be removed

			if (language != null) {
				byte[] img = SecureStore.b64Decode(new String(language.getImageContent()));
				response.setContentType(language.getImageMime());
				response.setContentLength(img.length);
				os = response.getOutputStream();
				os.write(img);
				os.flush();
			}
		}
	} catch (DatabaseException e) {
		log.error(e.getMessage(), e);
	} finally {
		IOUtils.closeQuietly(os);
	}
}
 
Example 6
Source File: JettyHandler.java    From cougar with Apache License 2.0 5 votes vote down vote up
/**
 * getContextPath and getContextPath are defined in terms of servlets which we bypass completely.
 * we may need to amend this implementation
       *
 * @param request
 * @return
 */
      private final void buildPathInfo(final HttpServletRequest request) {
          fullPath = request.getContextPath() + (request.getPathInfo() ==  null ? "" : request.getPathInfo());

          // Strip the binding protocolBindingRoot off the front.
          if (protocolBindingRoot != null && protocolBindingRoot.length() > 0) {
              operationPath =  fullPath.substring(protocolBindingRoot.length());
          } else {
              operationPath =  fullPath;
          }
}
 
Example 7
Source File: EngineResource.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8")
public String getEngine(@Context HttpServletRequest req) {

	logger.debug("IN");
	try {
		return serializeEngine();
	} catch (Exception e) {
		throw new SpagoBIServiceException(req.getPathInfo(), "An unexpected error occured while executing service", e);
	} finally {
		logger.debug("OUT");
	}
}
 
Example 8
Source File: ResourceCacheControl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
boolean isCacheableResourceRequest(HttpServletRequest request) {
    String requestPath = request.getPathInfo();
    if (requestPath == null) {
        return false;
    }
    for (String resourcePrefix : resourcePrefixes) {
        if (requestPath.startsWith(resourcePrefix)) {
            return true;
        }
    }
    return false;
}
 
Example 9
Source File: FakeZendeskAPIServlet.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    if (request.getPathInfo().equals("/tickets.json")) {
        String resource = TestUtils.getResourceValue(FakeZendeskAPIServlet.class, "/tickets.json");
        response.getOutputStream().print(resource);
    } else {
        throw new IllegalStateException("Unknown path: " + request.getPathInfo());
    }
}
 
Example 10
Source File: TestCoyoteAdapter.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    // Not thread safe
    pathInfo = req.getPathInfo();
}
 
Example 11
Source File: MCRActionMappingServlet.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void doGet(MCRServletJob job) throws Exception {
    HttpServletRequest request = job.getRequest();
    String pathInfo = request.getPathInfo();
    HttpServletResponse response = job.getResponse();
    if (pathInfo != null) {
        List<String> splitted = PATH_SPLITTER.splitToList(pathInfo);
        if (splitted.size() == 2) {
            String collection = splitted.get(0);
            String action = splitted.get(1);
            String url = MCRURLRetriever.getURLforCollection(action, collection, true);
            if (url != null) {
                //MCR-1172 check if we redirect to a valid URI
                URI uri = URI.create(url);
                response.sendRedirect(response.encodeRedirectURL(uri.toString()));
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
            return;
        }
        //misses action
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    //should never happen:
    response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
}
 
Example 12
Source File: XtextResourcesServlet.java    From xtext-web with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
	try {
		String resourceURI = "META-INF/resources" + request.getServletPath() + request.getPathInfo();
		InputStream inputStream = getResourceAsStream(resourceURI);
		if (inputStream != null) {
			String[] tokens = resourceURI.split("/");
			String fileName = tokens[tokens.length - 1];
			if (!disableCache && tokens.length > 4) {
				String version = tokens[3];
				response.setHeader("ETag", fileName + "_" + version);
				response.setDateHeader("Expires",
						System.currentTimeMillis() + XtextResourcesServlet.DEFAULT_EXPIRE_TIME_MS);
				response.addHeader("Cache-Control",
						("private, max-age=" + XtextResourcesServlet.DEFAULT_EXPIRE_TIME_S));
			}
			String mimeType = getServletContext().getMimeType(fileName);
			String contentType = null;
			if (mimeType != null) {
				contentType = mimeType;
			} else {
				contentType = "application/octet-stream";
			}
			response.setContentType(contentType);
			ByteStreams.copy(inputStream, response.getOutputStream());
		} else {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
		}
	} catch (IOException e) {
		throw Exceptions.sneakyThrow(e);
	}
}
 
Example 13
Source File: RobotRegistrationServlet.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  String pathInfo = req.getPathInfo();
  if (CREATE_PATH.equals(pathInfo)) {
    doRegisterGet(req, resp, "");
  } else {
    resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
  }
}
 
Example 14
Source File: FileSystemResourceServlet.java    From Alpine with Apache License 2.0 5 votes vote down vote up
@Override
protected StaticResource getStaticResource(HttpServletRequest request) throws IllegalArgumentException {
    final String pathInfo = request.getPathInfo();

    if (pathInfo == null || pathInfo.isEmpty() || "/".equals(pathInfo)) {
        throw new IllegalArgumentException();
    }

    String name = "";
    try {
        name = URLDecoder.decode(pathInfo.substring(1), StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        LOGGER.error(e.getMessage());
    }

    final ServletContext context = request.getServletContext();
    final File file = absolute ? new File(directory, name) : new File(context.getRealPath("/"), name).getAbsoluteFile();

    return !file.exists() ? null : new StaticResource() {
        @Override
        public long getLastModified() {
            return file.lastModified();
        }
        @Override
        public InputStream getInputStream() throws IOException {
            return Files.newInputStream(file.toPath());
        }
        @Override
        public String getFileName() {
            return file.getName();
        }
        @Override
        public long getContentLength() {
            return file.length();
        }
    };
}
 
Example 15
Source File: ActionDriver.java    From HongsCORE with MIT License 5 votes vote down vote up
/**
 * 获得当前的ServletPath
 * @param req
 * @return
 */
public static final String getRecentPath(HttpServletRequest req) {
    String uri = (String) req.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
    String suf = (String) req.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
    if (uri == null) {
        uri  = req.getServletPath();
        suf  = req.getPathInfo();
    }
    if (suf != null) {
        uri += suf;
    }
    return uri;
}
 
Example 16
Source File: WorkbenchServlet.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void service(final String repoID, final HttpServletRequest req, final HttpServletResponse resp)
		throws RepositoryConfigException, RepositoryException, ServletException, IOException {
	LOGGER.info("Servicing repository: {}", repoID);
	setCredentials(req, resp);
	final DynamicHttpRequest http = new DynamicHttpRequest(req);
	final String path = req.getPathInfo();
	final int idx = path.indexOf(repoID) + repoID.length();
	http.setServletPath(http.getServletPath() + path.substring(0, idx));
	final String pathInfo = path.substring(idx);
	http.setPathInfo(pathInfo.length() == 0 ? null : pathInfo);
	if (repositories.containsKey(repoID)) {
		repositories.get(repoID).service(http, resp);
	} else {
		final Repository repository = manager.getRepository(repoID);
		if (repository == null) {
			final String noId = config.getInitParameter(NO_REPOSITORY);
			if (noId == null || !noId.equals(repoID)) {
				resp.setHeader("Cache-Control", "no-cache, no-store");
				throw new BadRequestException("No such repository: " + repoID);
			}
		}
		final ProxyRepositoryServlet servlet = new ProxyRepositoryServlet();
		servlet.setRepositoryManager(manager);
		if (repository != null) {
			servlet.setRepositoryInfo(manager.getRepositoryInfo(repoID));
			servlet.setRepository(repository);
		}
		servlet.init(new BasicServletConfig(repoID, config));
		repositories.putIfAbsent(repoID, servlet);
		repositories.get(repoID).service(http, resp);
	}
}
 
Example 17
Source File: PluginServlet.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void service(HttpServletRequest request, HttpServletResponse response) {
    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
    else {
        try {
            final PluginMetadata pluginMetadata = getPluginMetadataFromPath(pathInfo);
            if (pluginMetadata.isCsrfProtectionEnabled()) {
                if (!passesCsrf(request)) {
                    request.getSession().setAttribute(FlashMessageTag.ERROR_MESSAGE_KEY, LocaleUtils.getLocalizedString("global.csrf.failed"));
                    response.sendRedirect(request.getRequestURI());
                    return;
                }
            }
            // Handle JSP requests.
            if (pathInfo.endsWith(".jsp")) {
                setCSRF(request);
                if (handleDevJSP(pathInfo, request, response)) {
                    return;
                }
                handleJSP(pathInfo, request, response);
            }
            // Handle servlet requests.
            else if (getServlet(pathInfo) != null) {
                setCSRF(request);
                handleServlet(pathInfo, request, response);
            }
            // Handle image/other requests.
            else {
                handleOtherRequest(pathInfo, response);
            }
        }
        catch (Exception e) {
            Log.error(e.getMessage(), e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
 
Example 18
Source File: AbstractComponentApiServlet.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
protected void get(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  String path = req.getPathInfo();
  if (path == null) {
    path = "";
  } else if (path.startsWith("/")) {
    path = path.substring(1);
  }

  if (path.isEmpty()) {
    if (!getComponents().isPresent()) {
      respondWithError(resp, 503, "Unable to load annotator class");
      return;
    }
    respond(resp, MediaType.create("text", "x-yaml"), getComponents().orElse(""));
  } else {
    try {
      Class<?> component = getClassFromString(path, componentPackage);
      List<Map<String, Object>> parameters = getParameters(component);

      respondWithJson(resp, parameters);
    } catch (InvalidParameterException ipe) {
      LoggerFactory.getLogger(clazz).warn("Could not find requested resource", ipe);
      respondWithNotFound(resp);
    }
  }
}
 
Example 19
Source File: ServiceListGeneratorServlet.java    From cxf with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void service(HttpServletRequest request,
                    HttpServletResponse response) throws ServletException, IOException {
    Object obj = request.getAttribute(ServletController.AUTH_SERVICE_LIST);
    boolean isAuthServiceList = false;
    if (obj != null) {
        isAuthServiceList = Boolean.valueOf(obj.toString());
    }
    if (isAuthServiceList) {
        String authServiceListRealm = (String)request.getAttribute(ServletController.AUTH_SERVICE_LIST_REALM);
        ServiceListJAASAuthenticator authenticator = new ServiceListJAASAuthenticator();
        authenticator.setRealm(authServiceListRealm);
        if (!authenticator.authenticate(request, response)) {
            return;
        }
        request.removeAttribute(ServletController.AUTH_SERVICE_LIST);
        request.removeAttribute(ServletController.AUTH_SERVICE_LIST_REALM);
    }
    AbstractDestination[] destinations = destinationRegistry.getSortedDestinations();
    if (request.getParameter("stylesheet") != null) {
        renderStyleSheet(request, response);
        return;
    }
    List<String> privateEndpoints;
    if (bus == null) {
        bus = BusFactory.getDefaultBus(false);
    }
    if (bus != null) {
        privateEndpoints = (List<String>)bus.getProperty("org.apache.cxf.private.endpoints");
    } else {
        privateEndpoints = new ArrayList<>();
    }

    AbstractDestination[] soapEndpoints = getSOAPEndpoints(destinations, privateEndpoints);
    AbstractDestination[] restEndpoints = getRestEndpoints(destinations, privateEndpoints);
    ServiceListWriter serviceListWriter;
    if ("false".equals(request.getParameter("formatted"))) {
        boolean renderWsdlList = "true".equals(request.getParameter("wsdlList"));
        serviceListWriter = new UnformattedServiceListWriter(renderWsdlList, bus);
    } else {
        String styleSheetPath;
        if (serviceListStyleSheet != null) {
            styleSheetPath = request.getContextPath() + "/" + serviceListStyleSheet;
        } else {
            styleSheetPath = "";
            String contextPath = request.getContextPath();
            if (contextPath != null) {
                styleSheetPath += contextPath;
            }
            String servletPath = request.getServletPath();
            if (servletPath != null) {
                styleSheetPath += servletPath;
            }
            String pathInfo = request.getPathInfo();
            if (pathInfo != null) {
                styleSheetPath += pathInfo;
            }

            if (!styleSheetPath.endsWith("/")) {
                styleSheetPath += "/";
            }
            styleSheetPath += "?stylesheet=1";
        }
        serviceListWriter =
            new FormattedServiceListWriter(styleSheetPath, title, showForeignContexts, bus);

    }
    response.setContentType(serviceListWriter.getContentType());
    Object basePath = request.getAttribute(Message.BASE_PATH);
    serviceListWriter.writeServiceList(response.getWriter(),
                                       basePath == null ? null : basePath.toString(),
                                       soapEndpoints, restEndpoints);
}
 
Example 20
Source File: MVCHelper.java    From fast-framework with Apache License 2.0 3 votes vote down vote up
/**
 * 获取请求路径
 * /servlet/MyServlet/a/b
 *
 * @param request
 * @return
 */
public static String getRequestPath(HttpServletRequest request) {
    String servletPath = request.getServletPath(); // /servlet/MyServlet
    String pathInfo = request.getPathInfo();    // /a/b

    return (null != servletPath ? servletPath : "") + StringUtils.defaultIfEmpty(pathInfo, StringUtils.EMPTY);
}