Example usage for javax.servlet.http HttpServletRequest getPathInfo

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

Introduction

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

Prototype

public String getPathInfo();

Source Link

Document

Returns any extra path information associated with the URL the client sent when it made this request.

Usage

From source file:com.thinkberg.webdav.MkColHandler.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    BufferedReader bufferedReader = request.getReader();
    String line = bufferedReader.readLine();
    if (line != null) {
        response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        return;/*from  w w  w  .  j av a2 s.  com*/
    }

    FileObject object = VFSBackend.resolveFile(request.getPathInfo());

    try {
        if (!LockManager.getInstance().evaluateCondition(object, getIf(request)).result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
    } catch (LockException e) {
        response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    if (object.exists()) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    if (!object.getParent().exists() || !FileType.FOLDER.equals(object.getParent().getType())) {
        response.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    }

    try {
        object.createFolder();
        response.setStatus(HttpServletResponse.SC_CREATED);
    } catch (FileSystemException e) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}

From source file:com.ebay.pulsar.collector.servlet.IngestServlet.java

private String readRequestHead(HttpServletRequest request) {
    try {//  w w w. java2s . c  o  m
        StringBuffer sb = new StringBuffer();
        sb.append(request.getMethod()).append(" ");
        sb.append(request.getProtocol()).append(" ");
        sb.append(request.getPathInfo()).append("\n");
        // Jetstream getHeaderNames has issues.
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            sb.append(name).append(": ");
            sb.append(request.getHeader(name)).append("\n");
        }
        return sb.toString();
    } catch (Throwable ex) {
        return null;
    }
}

From source file:com.jjtree.servelet.Accounts.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*w  w  w  .  j av a  2s .c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    String pathInfo = request.getPathInfo();
    String[] path = pathInfo.split("/");
    int userID = Integer.parseInt(path[1]);

    try {
        // Register JDBC driver
        Class.forName(JConstant.JDBC_DRIVER);

        // Open a connection
        conn = DriverManager.getConnection(JConstant.DB_URL, JConstant.USER, JConstant.PASSWORD);

        // Execute SQL query
        stmt = conn.createStatement();
        String sql;
        sql = "SELECT * FROM JUser WHERE userID = " + userID;
        ResultSet rs = stmt.executeQuery(sql);

        // Extract data from result set
        while (rs.next()) {
            //Retrieve by column name
            int accountID = rs.getInt("userID");

            String email = rs.getString("email");
            String mobile = rs.getString("mobile");
            String password = rs.getString("password");
            String name = rs.getString("name");
            String avatarURL = rs.getString("avatarURL");

            JSONObject account = new JSONObject();

            account.put("accountID", accountID);
            account.put("email", email);
            account.put("mobile", mobile);
            account.put("password", password);
            account.put("name", name);
            account.put("avatarURL", avatarURL);

            PrintWriter writer = response.getWriter();
            writer.print(account);
            writer.flush();
        }

        // Clean-up environment
        rs.close();
        stmt.close();
        conn.close();
    } catch (SQLException se) {
        //Handle errors for JDBC
        se.printStackTrace();
    } catch (Exception e) {
        //Handle errors for Class.forName
        e.printStackTrace();
    } finally {
        //finally block used to close resources
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException se2) {
        } // nothing we can do
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException se) {
            se.printStackTrace();
        } //end finally try
    } //end try
}

From source file:it.geosolutions.opensdi2.configurations.controller.OSDIModuleController.java

/**
 * /* w w  w.  j av a2 s .  c o m*/
 * Load the Configuration following these steps:
 * <ul>
 * <li>Load the <b>scopeID</b> taking it from the first placeholder path</li>
 * <li>Load the <b>instanceID</b> calling the abstract method</li>
 * <li><strong>If the instanceID is null (or blank)</strong> it will initialized as the scopeID... this case means that the module has only one configuration, called as the module name</li>
 * <li>Use that params to load the configuration using the method loadExistingConfiguration</li>
 * </ul>
 * 
 * @param req
 * @return
 * @throws OSDIConfigurationException
 */
public OSDIConfiguration loadConfiguration(HttpServletRequest req) throws OSDIConfigurationException {

    String instanceID = getInstanceID(req);
    String scopeID = getScopeID(req);

    if (StringUtils.isBlank(scopeID)) {
        LOGGER.info("Executing module: '" + req.getPathInfo()
                + "' ...ScopeID is null or blank... This should never happen... Have you overrode the getScopeID method?...");
        throw new OSDIConfigurationException(
                "ScopeID is null or blank... This should never happen... Have you overrode the getScopeID method?");
    }
    if (StringUtils.isBlank(instanceID)) {
        instanceID = scopeID;
        LOGGER.warn(
                "The instanceID is null or blank and it will be set as the scopeID... A configuration file called as the scopeID is expected...");
    }
    LOGGER.info("Executing module: '" + req.getPathInfo() + "' configuration with ScopeID: '" + scopeID
            + "' and instanceID: '" + instanceID + "'");
    OSDIConfiguration tmpConf = new OSDIConfigurationKVP(scopeID, instanceID);
    if (!tmpConf.validateIDs()) {
        LOGGER.error(
                "A scope and instance IDs are not valid... Please check your module configurations and installation");
        throw new OSDIConfigurationException(
                "A scope and instance IDs are not valid... Please check your module configurations and installation");
    }
    OSDIConfiguration conf = null;
    try {
        conf = depot.loadExistingConfiguration(scopeID, instanceID);
    } catch (OSDIConfigurationException e) {
        LOGGER.error(
                "A configuration exception occurred while loading the configuration, the exception message is: '"
                        + e.getMessage() + "'");
        throw new OSDIConfigurationException(
                "A configuration exception occurred while loading the configuration, the exception message is: '"
                        + e.getMessage() + "'");
    } catch (Exception e) {
        LOGGER.error("An unexpected error occurred while loading the configuration, the exception message is: '"
                + e.getMessage() + "'");
        throw new OSDIConfigurationException(
                "An unexpected error occurred while loading the configuration, the exception message is: '"
                        + e.getMessage() + "'");
    }
    if (conf == null || !(conf instanceof OSDIConfiguration)) {
        LOGGER.error(
                "No exceptions are occurred but the configurations is null or is not an instance of OSDIConfiguration... this should never happens...");
        throw new OSDIConfigurationException(
                "No exceptions are occurred but the configurations is null or is not an instance of OSDIConfiguration... this should never happens...");
    }
    LOGGER.info("Loading the configuration with ScopeID: '" + scopeID + "' and instanceID: '" + instanceID
            + "' DONE!");

    return conf;
}

From source file:org.codemucker.testserver.capturing.CapturedRequest.java

public CapturedRequest(final HttpServletRequest req) {
    scheme = req.getScheme();//from  w  w w.j av a 2s  .c o m
    host = req.getServerName();
    port = req.getServerPort();
    contextPath = req.getContextPath();
    servletPath = req.getServletPath();
    pathInfo = req.getPathInfo();
    characterEncoding = req.getCharacterEncoding();
    method = req.getMethod();
    final Cookie[] cookies = req.getCookies();

    // cookies
    if (cookies != null) {
        for (final Cookie cookie : cookies) {
            this.cookies.add(new CapturedCookie(cookie));
        }
    }
    // headers
    for (@SuppressWarnings("unchecked")
    final Enumeration<String> names = req.getHeaderNames(); names.hasMoreElements();) {
        final String name = names.nextElement();
        @SuppressWarnings("unchecked")
        final Enumeration<String> values = req.getHeaders(name);
        if (values != null) {
            for (; values.hasMoreElements();) {
                this.addHeader(new CapturedHeader(name, values.nextElement()));
            }
        }
    }
    // if we use the normal 'toString' on maps, and arrays, we get pretty
    // poor results
    // Use ArrayLists instead to get a nice output
    @SuppressWarnings("unchecked")
    final Map<String, String[]> paramMap = req.getParameterMap();
    if (paramMap != null) {
        for (final String key : paramMap.keySet()) {
            final String[] vals = paramMap.get(key);
            this.parameters.put(key, new ArrayList<String>(Arrays.asList(vals)));
        }
    }
    // handle multipart posts
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        final FileItemFactory factory = new DiskFileItemFactory();

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

        try {
            @SuppressWarnings("unchecked")
            final List<FileItem> items = upload.parseRequest(req);
            for (final FileItem item : items) {
                fileItems.add(new CapturedFileItem(item));
            }
        } catch (final FileUploadException e) {
            throw new RuntimeException("Error handling multipart content", e);
        }
    }

}

From source file:com.jaspersoft.jasperserver.rest.services.RESTPermission.java

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    String[] params;//from  w  w  w  .ja  v  a  2 s . com
    String res = restUtils.extractRepositoryUri(req.getPathInfo());
    List<ObjectPermission> permissions;
    try {
        permissions = permissionsService.getPermissions(res);
    } catch (RemoteException e) {
        throw new ServiceException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                e.getClass().getName() + (e.getMessage() != null ? ": " + e.getMessage() : ""));
    }

    List<String> rolesThatCantBeDeleted = new LinkedList();
    List<String> usersThatCantBeDeleted = new LinkedList();

    final String roles = req.getParameter(restUtils.REQUEST_PARAMENTER_ROLES);
    final String users = req.getParameter(restUtils.REQUEST_PARAMENTER_USERS);
    if ((roles != null && !"".equals(roles)) || (users != null && !"".equals(users))) {
        List<String> rolesToDelete = restUtils.stringToList(roles != null ? roles : "",
                restUtils.REQUEST_PARAMENTER_SEPARATOR);

        List<String> usersToDelete = restUtils.stringToList(users != null ? users : "",
                restUtils.REQUEST_PARAMENTER_SEPARATOR);

        if (log.isDebugEnabled()) {
            log.debug("roles to delete: " + rolesToDelete.size() + " users to delete: " + usersToDelete.size());
        }

        String roleName, userName;
        Iterator<String> rolesIter = rolesToDelete.iterator();
        while (rolesIter.hasNext()) {
            roleName = rolesIter.next();
            if (!canUpdateRolePermissions(roleName)) {
                throw new AccessDeniedException("could not set permissions for: " + roleName);
            }
        }

        Iterator<String> usersIter = usersToDelete.iterator();
        while (usersIter.hasNext()) {
            userName = usersIter.next();
            if (!canUpdateUserPermissions(userName)) {
                if (log.isDebugEnabled()) {
                    log.debug("removed user: " + userName + " from the delete permission request");
                }
                throw new AccessDeniedException("could not set permissions for: " + userName);
            }
        }

        Object permissionRecipient;
        for (ObjectPermission op : permissions) {
            permissionRecipient = op.getPermissionRecipient();

            if ((permissionRecipient instanceof Role
                    && rolesToDelete.contains(((Role) permissionRecipient).getRoleName()))
                    || (permissionRecipient instanceof User
                            && usersToDelete.contains(((User) permissionRecipient).getUsername())))
                try {
                    permissionsService.deletePermission(op);
                } catch (RemoteException e) {
                    throw new ServiceException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            e.getClass().getName() + (e.getMessage() != null ? ": " + e.getMessage() : ""));
                }
        }
    } else {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "users or roles must be specified");
    }

    restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, "");
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTReport.java

/**
 * The get method get resources of a produced report
 * Urls in this case look like /report/uniqueidentifier?file=filename
 *//*from   w  w  w  .j ava  2  s  . co  m*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    // Get the uri of the resource
    String uuid = restUtils.extractRepositoryUri(req.getPathInfo());
    if (uuid.startsWith("/"))
        uuid = uuid.substring(1);

    // Find the report in session...
    HttpSession session = req.getSession();
    Report report = (Report) session.getAttribute(uuid);

    if (report == null) {
        restUtils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp,
                "Report not found (uuid not found in session)");
        return;
    }

    String file = req.getParameter("file");
    if (file != null) {
        if (!report.getAttachments().containsKey(file)) {
            restUtils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp,
                    "Report not found (requested file not available for this report)");
            return;
        } else {
            DataSource ds = (DataSource) report.getAttachments().get(file);
            restUtils.sendFile(ds, resp);
            return;
        }
    } else {
        // Send the report description...
        // Please not that here we may decide to send back a final format based on the accepted
        // content type....
        resp.setContentType("text/xml; charset=UTF-8");
        restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, report.toXml());
    }
}

From source file:io.fabric8.maven.impl.MavenProxyServletSupportTest.java

private void testDownload(Handler serverHandler) throws Exception {
    String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(serverHandler);// w  ww  . j  a  v  a2  s. c  o  m
    server.start();

    try {
        int localPort = server.getConnectors()[0].getLocalPort();
        List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central");
        RuntimeProperties props = new MockRuntimeProperties();
        MavenDownloadProxyServlet servlet = new MavenDownloadProxyServlet(props, "target/tmp", remoteRepos,
                false, "always", "warn", "http", "localhost", localPort, "fuse", "fuse", null);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo())
                .andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar");

        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }
        }).anyTimes();
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();

        EasyMock.replay(request, response);

        servlet.start();
        servlet.doGet(request, response);
        Assert.assertArrayEquals(new byte[] { 0x42 }, baos.toByteArray());

        EasyMock.verify(request, response);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTResource.java

/**
 * POST can be used to modify a resource or to copy/move it.
 *
 * @param req/*w w  w.  ja v a 2s  .  c o  m*/
 * @param resp
 * @throws ServiceException
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    String sourceURI = restUtils.extractRepositoryUri(req.getPathInfo());
    String destURI = restUtils.getDetinationUri(req);
    if (destURI != null) {
        if (req.getParameterMap().containsKey(restUtils.REQUEST_PARAMENTER_COPY_TO))
            resourcesManagementRemoteService.copyResource(sourceURI, destURI);
        else
            resourcesManagementRemoteService.moveResource(sourceURI, destURI);
    } else // Modify the resource...
    {
        HttpServletRequest mreq = restUtils.extractAttachments(runReportService, req);
        String resourceDescriptorXml = null;

        // get the resource descriptor...
        if (mreq instanceof MultipartHttpServletRequest)
            resourceDescriptorXml = mreq.getParameter(restUtils.REQUEST_PARAMENTER_RD);
        else {
            try {
                resourceDescriptorXml = IOUtils.toString(req.getInputStream());
            } catch (IOException ex) {
                throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage());
            }
        }
        if (resourceDescriptorXml == null) {
            String msg = "Missing parameter " + restUtils.REQUEST_PARAMENTER_RD + " "
                    + runReportService.getInputAttachments();
            restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, msg);
            throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, msg);
        }

        // Parse the resource descriptor...
        InputSource is = new InputSource(new StringReader(resourceDescriptorXml));
        Document doc = null;
        ResourceDescriptor rd = null;
        try {
            doc = XMLUtil.getNewDocumentBuilder().parse(is);
            rd = Unmarshaller.readResourceDescriptor(doc.getDocumentElement());

            // we force the rd to be new...
            rd.setIsNew(false);

            if (rd.getUriString() == null || !rd.getUriString().equals(sourceURI)) {
                throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                        "Request URI and descriptor URI are not equals");
            }
            resourcesManagementRemoteService.updateResource(sourceURI, rd, true);

            restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, "");

        } catch (SAXException ex) {
            log.error("error parsing...", ex);
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
        } catch (ServiceException ex) {
            log.error("error executing the service...", ex);
            throw ex;
        } catch (ParserConfigurationException e) {
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        } catch (IOException e) {
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }
}

From source file:com.jaspersoft.jasperserver.war.StaticFilesCacheControlFilter.java

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

    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String path = httpServletRequest.getServletPath();
        if (path != null) {
            String resourcePatch = httpServletRequest.getPathInfo() == null ? path
                    : path.concat(httpServletRequest.getPathInfo());

            boolean excludeFromCacheFlag = false;
            for (String exclRegex : exclusionRegexSet) {
                if (path.matches(exclRegex)) {
                    log.debug("Excluding the path from browser cache by not setting the response header: "
                            + path);/*from ww w .ja v  a2s  .co m*/
                    excludeFromCacheFlag = true;
                    break;
                }
            }

            if (!excludeFromCacheFlag) {
                boolean set = false;
                for (String suffix : urlSuffixes) {
                    if (path.toLowerCase().endsWith(suffix)) {
                        log.debug("Setting headers for " + path);
                        setHeaders(httpServletRequest, httpServletResponse);
                        set = true;
                        break;
                    }
                }
                if (!set) {
                    for (String prefix : urlPrefixes) {
                        if (resourcePatch.toLowerCase().startsWith(prefix)) {
                            log.debug("Setting headers for " + resourcePatch);
                            setHeaders(httpServletRequest, httpServletResponse);
                            break;
                        }
                    }
                }
            }
        }
    }

    chain.doFilter(request, response);
}