Example usage for java.net URI getPath

List of usage examples for java.net URI getPath

Introduction

In this page you can find the example usage for java.net URI getPath.

Prototype

public String getPath() 

Source Link

Document

Returns the decoded path component of this URI.

Usage

From source file:com.jeny.atmosphere.integration.websocket.RawWebSocketProtocol.java

/**
 * Since protocol is simple http tunneling over web socket using RAW approach it parses web socket body as string which represents http request by HTTP standard.
 * It takes all parameters from passed http request and takes some parameters (like Cookies, Content Type and etc) from initial http request if
 * they are missing in the passed http request. On the client side is supposed that it will take passed parameters and missing parameters from
 * browser context during form http request (like Accept-Charset, Accept-Encoding, User-Agent and etc).
 * {@inheritDoc}//from ww w.  ja  v  a2 s . c  o  m
 */
@Override
public List<AtmosphereRequest> onMessage(WebSocket webSocket, String d) {

    HttpRequest request = null;
    try {
        HttpParams params = new BasicHttpParams();
        SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 128, params);
        HttpRequestFactory requestFactory = new DefaultHttpRequestFactory();
        NHttpMessageParser<HttpRequest> requestParser = new DefaultHttpRequestParser(inbuf, null,
                requestFactory, params);
        requestParser.fillBuffer(newChannel(d, "UTF-8"));
        request = requestParser.parse();

    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (HttpException e) {
        throw new RuntimeException(e);
    }

    AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
    if (resource == null) {
        logger.error("Invalid state. No AtmosphereResource has been suspended");
        return null;
    }
    AtmosphereRequest initialRequest = resource.getRequest();

    Map<String, Object> attributesMap = new HashMap<String, Object>();
    attributesMap.put(FrameworkConfig.WEBSOCKET_SUBPROTOCOL, FrameworkConfig.SIMPLE_HTTP_OVER_WEBSOCKET);

    // Propagate the original attribute to WebSocket message.
    attributesMap.putAll(initialRequest.attributes());

    // Determine value of path info, request URI
    String pathInfo = request.getRequestLine().getUri();
    UriBuilder pathInfoUriBuilder = UriBuilder.fromUri(pathInfo);
    URI pathInfoUri = pathInfoUriBuilder.build();
    String requestURI = pathInfoUri.getPath();

    // take the Method Type of passed http request
    methodType = request.getRequestLine().getMethod();

    // take the Content Type of passed http request
    contentType = request.getFirstHeader(HttpHeaders.CONTENT_TYPE) != null
            ? request.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue()
            : initialRequest.getContentType();

    // take the body of passed http request
    String body = null; // TODO how we can take it?

    // We need to create a new AtmosphereRequest as WebSocket message may arrive concurrently on the same connection.
    AtmosphereRequest atmosphereRequest = new AtmosphereRequest.Builder()
            // use HttpServletRequestWrapper to propagate passed http request parameters, headers, cookies and etc.
            // if some parameters (headers, cookies and etc) takes from initial request if they are missing.
            .request(new HttpServletRequestWrapper(initialRequest, request))

            .method(methodType).contentType(contentType).requestURI(requestURI).pathInfo(pathInfo)

            .attributes(attributesMap)

            .body(d) // TODO Unfortunately org.apache.http doesn't allow to take a body need to find workaround
            .destroyable(destroyable).build();

    List<AtmosphereRequest> list = new ArrayList<AtmosphereRequest>();
    list.add(atmosphereRequest);

    return list;
}

From source file:org.mobicents.servlet.restcomm.http.client.HttpRequestDescriptor.java

private URI base(final URI uri) {
    try {//from   ww w . ja va  2s  .  c o m
        URIBuilder uriBuilder = new URIBuilder();
        uriBuilder.setScheme(uri.getScheme());
        uriBuilder.setHost(uri.getHost());
        uriBuilder.setPort(uri.getPort());
        uriBuilder.setPath(uri.getPath());

        if (uri.getUserInfo() != null) {
            uriBuilder.setUserInfo(uri.getUserInfo());
        }
        return uriBuilder.build();
    } catch (final URISyntaxException ignored) {
        // This should never happen since we are using a valid URI to construct ours.
        return null;
    }
}

From source file:org.apache.ambari.server.controller.internal.AppCookieManager.java

/**
 * Returns hadoop.auth cookie, doing needed SPNego authentication
 * /*from w ww.  j av a  2s. c  o  m*/
 * @param endpoint
 *          the URL of the Hadoop service
 * @param refresh
 *          flag indicating wehther to refresh the cookie, if
 *          <code>true</code>, we do a new SPNego authentication and refresh
 *          the cookie even if the cookie already exists in local cache
 * @return hadoop.auth cookie value
 * @throws IOException
 *           in case of problem getting hadoop.auth cookie
 */
public String getAppCookie(String endpoint, boolean refresh) throws IOException {

    HttpUriRequest outboundRequest = new HttpGet(endpoint);
    URI uri = outboundRequest.getURI();
    String scheme = uri.getScheme();
    String host = uri.getHost();
    int port = uri.getPort();
    String path = uri.getPath();
    if (!refresh) {
        String appCookie = endpointCookieMap.get(endpoint);
        if (appCookie != null) {
            return appCookie;
        }
    }

    clearAppCookie(endpoint);

    DefaultHttpClient client = new DefaultHttpClient();
    SPNegoSchemeFactory spNegoSF = new SPNegoSchemeFactory(/* stripPort */true);
    // spNegoSF.setSpengoGenerator(new BouncySpnegoTokenGenerator());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, spNegoSF);
    client.getCredentialsProvider().setCredentials(new AuthScope(/* host */null, /* port */-1, /* realm */null),
            EMPTY_JAAS_CREDENTIALS);

    String hadoopAuthCookie = null;
    HttpResponse httpResponse = null;
    try {
        HttpHost httpHost = new HttpHost(host, port, scheme);
        HttpRequest httpRequest = new HttpOptions(path);
        httpResponse = client.execute(httpHost, httpRequest);
        Header[] headers = httpResponse.getHeaders(SET_COOKIE);
        hadoopAuthCookie = getHadoopAuthCookieValue(headers);
        if (hadoopAuthCookie == null) {
            LOG.error("SPNego authentication failed, can not get hadoop.auth cookie for URL: " + endpoint);
            throw new IOException("SPNego authentication failed, can not get hadoop.auth cookie");
        }
    } finally {
        if (httpResponse != null) {
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                entity.getContent().close();
            }
        }

    }

    hadoopAuthCookie = HADOOP_AUTH_EQ + quote(hadoopAuthCookie);
    setAppCookie(endpoint, hadoopAuthCookie);
    if (LOG.isInfoEnabled()) {
        LOG.info("Successful SPNego authentication to URL:" + uri.toString());
    }
    return hadoopAuthCookie;
}

From source file:edu.lternet.pasta.auditmanager.AuditManagerResourceTest.java

/**
 * Test the create service method and the get service method
 *///  w  w w .  j av  a 2  s . c  o m
@Test
public void testCreateAndGet() {
    try {
        String auditEntry = readTestAuditEntry();
        HttpHeaders httpHeaders = new DummyCookieHttpHeaders(testUser);

        // Test CREATE for OK status
        Response response = auditManagerResource.create(httpHeaders, auditEntry);
        int statusCode = response.getStatus();
        assertEquals(201, statusCode);

        MultivaluedMap<String, Object> map = response.getMetadata();
        List<Object> location = map.get(HttpHeaders.LOCATION);
        URI uri = (URI) location.get(0);
        String uriPath = uri.getPath(); // e.g. "/audit/22196"

        try {
            auditId = Integer.parseInt(uriPath.substring(uriPath.lastIndexOf('/') + 1));
        } catch (NumberFormatException e) {
            fail("Failed to return valid audit entry ID value: " + uriPath);
        }
    } catch (IOException e) {
        fail(e.getMessage());
    }

    if (auditId == null) {
        fail("Null auditId value");
    } else {
        DummyCookieHttpHeaders httpHeaders = new DummyCookieHttpHeaders(testUser);

        // Test Evaluate for OK status
        Response response = auditManagerResource.getAuditRecord(httpHeaders, auditId);
        int statusCode = response.getStatus();
        assertEquals(200, statusCode);

        // Check the message body
        String entityString = (String) response.getEntity();
        String auditReport = entityString.trim();
        assertTrue(auditReport.length() > 1);
        assertTrue(auditReport.startsWith("<auditReport>"));
        assertTrue(auditReport.contains(String.format("<oid>%d</oid>", auditId)));
        assertTrue(auditReport.endsWith("</auditReport>"));
    }
}

From source file:com.nesscomputing.migratory.loader.HttpLoader.java

@Override
public Collection<URI> loadFolder(final URI folderUri, final String searchPattern) throws IOException {
    final List<URI> results = Lists.newArrayList();
    final Pattern pattern = (searchPattern == null) ? null : Pattern.compile(searchPattern);

    final String path = folderUri.getPath();
    final URI baseUri = (path.endsWith("/") ? folderUri : folderUri.resolve(path + "/"));

    final String content = loadFile(baseUri);
    if (content == null) {
        // File not found
        return results;
    }//  ww w  .  java2  s .co m

    // The folders are a list of file names in plain text. Split it up.
    final String[] filenames = StringUtils.split(content);

    for (String filename : filenames) {
        if (pattern.matcher(filename).matches()) {
            results.add(URI.create(baseUri + filename));
        }
    }

    return results;
}

From source file:de.bitinsomnia.webdav.server.MiltonFolderResource.java

private String getRootRelativePath(File file) {
    URI toInspectURI = file.toURI();
    URI relativePath = resourceFactory.getRootFolder().toURI().relativize(toInspectURI);
    return "/" + relativePath.getPath();
}

From source file:ca.nrc.cadc.rest.SyncInput.java

/**
 * Get the complete path in the request. This is simply the path component of
 * the requestURI./*from   ww  w.  ja  v a 2 s . c o m*/
 * 
 * @return complete path
 */
public String getRequestPath() {
    String uri = getRequestURI();
    URI u = URI.create(uri);
    return u.getPath();
}

From source file:com.jtstand.swing.Main.java

private void startProject() {
    if (projectLocation == null) {
        /* if project location is not defined, default will kick in */
        /* if none of the default location is a file, then exit */
        projectLocation = "./config/project.xml";
        if (!new File(projectLocation).isFile()) {
            projectLocation = "./project.xml";
        }/*from  w ww  .  j a  v a  2  s. com*/
        if (!new File(projectLocation).isFile()) {
            projectLocation = "./src/main/resources/config/project.xml";
        }
        if (!new File(projectLocation).isFile()) {
            projectLocation = "../jtstand-demo/src/main/resources/config/project.xml";
        }
        if (!new File(projectLocation).isFile()) {
            log.fatal("Project not specified and it could not be found in default locations!");
            System.exit(1);
        } else {
            log.trace("Project file specified:" + projectLocation);
        }
    }
    if (new File(projectLocation).isFile()) {
        log.trace("Resolving: " + projectLocation);
        URI projectURI = resolve(projectLocation);
        log.trace("Project file is resolved to URI: " + projectURI);
        projectLocation = projectURI.getPath();
        log.trace("Project file path: " + projectLocation);
        if (projectLocation.charAt(2) == ':') {
            projectLocation = projectLocation.substring(1);
            log.trace("Project file path is corrected to: " + projectLocation);
        }
    }
    log.trace("Project file requested revision: " + revision);
    try {
        new MainFrame(
                TestProject.unmarshal(FileRevision.createFromUrlOrFile(projectLocation, (long) revision), true)
                        .getTestStationOrDefault(station),
                title, version);
    } catch (IOException ex) {
        log.fatal("Exception", ex);
    } catch (JAXBException ex) {
        log.fatal("Exception", ex);
        javax.swing.JOptionPane.showMessageDialog(null, "Project file is invalid!\nPress OK to exit.", "Error",
                javax.swing.JOptionPane.ERROR_MESSAGE);
        System.exit(-1);
    } catch (Exception ex) {
        log.fatal("Exception", ex);
    }
}

From source file:org.openscore.lang.cli.utils.CompilerHelperTest.java

@Test
public void testLoadSystemProperties() throws Exception {
    Map<String, Serializable> expected = new HashMap<>();
    expected.put("user.sys.props.host", "localhost");
    expected.put("user.sys.props.port", 22);
    expected.put("user.sys.props.alla", "balla");
    URI systemProperties = getClass().getResource("/properties/system_properties.yaml").toURI();
    Map<String, ? extends Serializable> result = compilerHelper
            .loadSystemProperties(Arrays.asList(systemProperties.getPath()));
    Assert.assertNotNull(result);/*from w w  w .  j a v a2 s.  com*/
    Assert.assertEquals(expected, result);
}

From source file:com.github.caldav4j.CalDAVCalendarCollectionBase.java

/**
 * Sets base path. Also set the host, based on if the path was Absolute
 * @param path Calendar Collection Root//  w ww. j a  va  2 s  . co m
 */
public void setCalendarCollectionRoot(String path) {
    URI temp = URI.create(path);
    if (temp.isAbsolute())
        setHttpHost(URIUtils.extractHost(temp));

    this.calendarCollectionRoot = UrlUtils.removeDoubleSlashes(UrlUtils.ensureTrailingSlash(temp.getPath()));
}