Example usage for java.net URI getRawPath

List of usage examples for java.net URI getRawPath

Introduction

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

Prototype

public String getRawPath() 

Source Link

Document

Returns the raw path component of this URI.

Usage

From source file:org.hotswap.agent.watch.vfs.WatcherVFS.java

private void callListeners(final FileChangeEvent event, final FileEvent fileEvent) {
    URI uri;
    try {//from w w w  .j a  va  2s .  c  om
        uri = event.getFile().getURL().toURI();
    } catch (FileSystemException ex) {
        LOGGER.error("FileSystemException at getFile.", ex);
        return;
    } catch (URISyntaxException ex) {
        LOGGER.error("URISyntaxException at getFile.", ex);
        return;
    }

    for (Map.Entry<URI, List<WatchEventListener>> list : listeners.entrySet()) {
        for (WatchEventListener listener : list.getValue()) {

            LOGGER.debug("uri: {} , list: {}", uri.toString(), list.getKey());
            if (uri.getRawPath().startsWith(list.getKey().getRawPath())) {
                WatchFileEvent agentEvent = new HotswapWatchFileEvent(event, fileEvent);

                try {
                    listener.onEvent(agentEvent);
                } catch (Throwable e) {
                    LOGGER.error("Error in watch event '{}' listener '{}'", e, agentEvent, listener);
                }
            }
        }
    }
}

From source file:com.cisco.oss.foundation.http.AbstractHttpClient.java

protected S updateRequestUri(S request, InternalServerProxy serverProxy) {

    URI origUri = request.getUri();
    String host = serverProxy.getHost();
    String scheme = origUri.getScheme() == null ? (request.isHttpsEnabled() ? "https" : "http")
            : origUri.getScheme();// w  w  w  .j a va  2  s  .  co  m

    int port = serverProxy.getPort();

    String urlPath = "";
    if (origUri.getRawPath() != null && origUri.getRawPath().startsWith("/")) {
        urlPath = origUri.getRawPath();
    } else {
        urlPath = "/" + origUri.getRawPath();
    }

    URI newURI = null;
    try {
        if (autoEncodeUri) {
            String query = origUri.getQuery();
            newURI = new URI(scheme, origUri.getUserInfo(), host, port, urlPath, query, origUri.getFragment());
        } else {
            String query = origUri.getRawQuery();
            if (query != null) {
                newURI = new URI(scheme + "://" + host + ":" + port + urlPath + "?" + query);
            } else {
                newURI = new URI(scheme + "://" + host + ":" + port + urlPath);
            }

        }
    } catch (URISyntaxException e) {
        throw new ClientException(e.toString());
    }

    S req = (S) request.replaceUri(newURI);
    //        try {
    //            req = (S) this.clone();
    //        } catch (CloneNotSupportedException e) {
    //            throw new IllegalArgumentException(e);
    //        }
    //        req.uri = newURI;
    return req;
}

From source file:com.mcxiaoke.next.http.util.URIBuilder.java

private void digestURI(final URI uri) {
    this.scheme = uri.getScheme();
    this.encodedSchemeSpecificPart = uri.getRawSchemeSpecificPart();
    this.encodedAuthority = uri.getRawAuthority();
    this.host = uri.getHost();
    this.port = uri.getPort();
    this.encodedUserInfo = uri.getRawUserInfo();
    this.userInfo = uri.getUserInfo();
    this.encodedPath = uri.getRawPath();
    this.path = uri.getPath();
    this.encodedQuery = uri.getRawQuery();
    this.queryParams = parseQuery(uri.getRawQuery(), Charsets.UTF_8);
    this.encodedFragment = uri.getRawFragment();
    this.fragment = uri.getFragment();
}

From source file:org.cryptomator.frontend.webdav.mount.MacOsXShellScriptWebDavMounter.java

@Override
public WebDavMount mount(URI uri, Map<MountParam, Optional<String>> mountParams) throws CommandFailedException {
    final String mountName = mountParams.getOrDefault(MountParam.MOUNT_NAME, Optional.empty())
            .orElseThrow(() -> {/*from ww  w  .  j a v  a2s .c  om*/
                return new IllegalArgumentException("Missing mount parameter MOUNT_NAME.");
            });

    // we don't use the uri to derive a path, as it *could* be longer than 255 chars.
    final String path = "/Volumes/Cryptomator_" + UUID.randomUUID().toString();
    final Script mountScript = Script
            .fromLines("mkdir \"$MOUNT_PATH\"",
                    "mount_webdav -S -v $MOUNT_NAME \"$DAV_AUTHORITY$DAV_PATH\" \"$MOUNT_PATH\"")
            .addEnv("DAV_AUTHORITY", uri.getRawAuthority()).addEnv("DAV_PATH", uri.getRawPath())
            .addEnv("MOUNT_PATH", path).addEnv("MOUNT_NAME", mountName);
    mountScript.execute();
    return new MacWebDavMount(path);
}

From source file:fedorax.server.module.storage.IrodsExternalContentManager.java

/**
 * @param params//from   ww  w  .  java2 s. c om
 * @return
 */
private MIMETypedStream getFromIrods(URI uri, String mimeType)
        throws HttpServiceNotFoundException, GeneralException {
    try {
        LOG.debug("uri: " + uri);
        IRODSFileFactory ff = IRODSFileSystem.instance().getIRODSFileFactory(irodsAccount);
        IRODSFile file = ff.instanceIRODSFile(URLDecoder.decode(uri.getRawPath(), "UTF-8"));
        InputStream result = ff.instanceIRODSFileInputStream(file);
        final long start = System.currentTimeMillis();
        result = new BufferedInputStream(result, this.irodsReadBufferSize) {
            int bytes = 0;

            @Override
            public void close() throws IOException {
                if (LOG.isInfoEnabled()) {
                    long time = System.currentTimeMillis() - start;
                    if (time > 0) {
                        LOG.info("closed irods stream: " + bytes + " bytes at " + (bytes / time) + " kb/sec");
                    }
                }
                super.close();
            }

            @Override
            public synchronized int read() throws IOException {
                bytes++;
                return super.read();
            }

            @Override
            public synchronized int read(byte[] b, int off, int len) throws IOException {
                bytes = bytes + len;
                return super.read(b, off, len);
            }

        };

        // if mimeType was not given, try to determine it automatically
        if (mimeType == null || mimeType.equalsIgnoreCase("")) {
            String irodsFilename = file.getName();
            if (irodsFilename != null) {
                mimeType = new MimetypesFileTypeMap().getContentType(irodsFilename);
            }
            if (mimeType == null || mimeType.equalsIgnoreCase("")) {
                mimeType = DEFAULT_MIMETYPE;
            }
        }
        return new MIMETypedStream(mimeType, result, getPropertyArray(mimeType), file.length());
        /*
         * } catch (AuthzException ae) { LOG.error(ae.getMessage(), ae);
         * throw new
         * HttpServiceNotFoundException("Policy blocked datastream resolution"
         * , ae); } catch (GeneralException me) { LOG.error(me.getMessage(),
         * me); throw me; }
         */

    } catch (JargonException e) {
        throw new GeneralException("Problem getting iRODS input stream", e);
    } catch (Throwable th) {
        th.printStackTrace(System.err);
        // catch anything but generalexception
        LOG.error(th.getMessage(), th);
        throw new HttpServiceNotFoundException(
                "[FileExternalContentManager] " + "returned an error.  The underlying error was a "
                        + th.getClass().getName() + "  The message " + "was  \"" + th.getMessage() + "\"  .  ",
                th);
    }
}

From source file:org.cryptomator.frontend.webdav.mount.WindowsWebDavMounter.java

private CommandResult mount(URI uri, String driveLetter) throws CommandFailedException {
    try {//from  w w  w. j  a v  a2  s . c  o m
        addProxyOverrides(uri);
    } catch (IOException e) {
        throw new CommandFailedException(e);
    }

    final String driveLetterStr = AUTO_ASSIGN_DRIVE_LETTER.equals(driveLetter) ? AUTO_ASSIGN_DRIVE_LETTER
            : driveLetter + ":";
    final Script mountScript = fromLines(
            "net use %DRIVE_LETTER% \\\\%DAV_HOST%@%DAV_PORT%\\DavWWWRoot%DAV_UNC_PATH% /persistent:no");
    mountScript.addEnv("DRIVE_LETTER", driveLetterStr);
    mountScript.addEnv("DAV_HOST", uri.getHost());
    mountScript.addEnv("DAV_PORT", String.valueOf(uri.getPort()));
    mountScript.addEnv("DAV_UNC_PATH", uri.getRawPath().replace('/', '\\'));
    return mountScript.execute(MOUNT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
}

From source file:HttpDownloadManager.java

public Download download(URI uri, Listener l) throws IOException {
    if (released)
        throw new IllegalStateException("Can't download() after release()");

    // Get info from the URI
    String scheme = uri.getScheme();
    if (scheme == null || !scheme.equals("http"))
        throw new IllegalArgumentException("Must use 'http:' protocol");
    String hostname = uri.getHost();
    int port = uri.getPort();
    if (port == -1)
        port = 80; // Use default port if none specified
    String path = uri.getRawPath();
    if (path == null || path.length() == 0)
        path = "/";
    String query = uri.getRawQuery();
    if (query != null)
        path += "?" + query;

    // Create a Download object with the pieces of the URL
    Download download = new DownloadImpl(hostname, port, path, l);

    // Add it to the list of pending downloads. This is a synchronized list
    pendingDownloads.add(download);//from w  w  w .  ja v a  2s .  c om

    // And ask the thread to stop blocking in the select() call so that
    // it will notice and process this new pending Download object.
    selector.wakeup();

    // Return the Download so that the caller can monitor it if desired.
    return download;
}

From source file:pl.psnc.synat.wrdz.zmd.input.ObjectCreationRequestBuilder.java

/**
 * Parses metadata files and returns map with names and URI of them.
 * //from   w  w  w .  ja  va 2s  .  com
 * @param objectMetadata
 *            map of metadata files
 * @return parsed map of metadata files
 * @throws IncompleteDataException
 *             when some data are missing
 * @throws InvalidDataException
 *             when some data are invalid
 */
private Map<String, URI> parseObjectMetadata(Map<String, String> objectMetadata)
        throws IncompleteDataException, InvalidDataException {
    Map<String, URI> uriObjectMetadata = new HashMap<String, URI>();
    for (String metadata : objectMetadata.keySet()) {
        URI uriMetadata = null;
        try {
            uriMetadata = new URI(metadata);
        } catch (URISyntaxException e) {
            logger.debug("Object metadata URI " + metadata + " is invalid.", e);
            throw new InvalidDataException("Object metadata URI " + metadata + " is invalid.");
        }
        String name = objectMetadata.get(metadata);
        if (name == null) {
            name = uriMetadata.getRawPath();
            if (name != null) {
                name = FilenameUtils.getName(name);
            }
        }
        if (name == null || name.isEmpty()) {
            logger.debug("Name for the metadata " + metadata + " is missing.");
            throw new IncompleteDataException("Name for the metadata " + metadata + " is missing.");
        }
        uriObjectMetadata.put(name, uriMetadata);
    }
    return uriObjectMetadata;
}

From source file:com.subgraph.vega.internal.http.proxy.VegaHttpRequestParser.java

@Override
public HttpMessage parse() throws IOException, HttpException {
    RequestLine requestLine;/*www. j a  va  2  s.  c o m*/
    try {
        requestLine = parseRequestLine(sessionBuffer);
    } catch (ParseException px) {
        throw new ProtocolException(px.getMessage(), px);
    }

    List<CharArrayBuffer> headerLines = new ArrayList<CharArrayBuffer>();
    Header[] headers = AbstractMessageParser.parseHeaders(sessionBuffer, maxHeaderCount, maxLineLen, lineParser,
            headerLines);

    if (conn.isSslConnection()) {
        URI uri;
        try {
            uri = new URI(requestLine.getUri());
        } catch (URISyntaxException e) {
            throw new ProtocolException("Invalid URI: " + requestLine.getUri(), e);
        }
        if (uri.getScheme() == null) {
            final Header hostHeader = getFirstHeader(headers, HTTP.TARGET_HOST);
            final StringBuilder buf = new StringBuilder();
            if (hostHeader != null) {
                // REVISIT: does using the Host header value instead of the SSL host risk opening another connection?
                buf.append("https://");
                buf.append(hostHeader.getValue());
            } else {
                buf.append(conn.getSslHost().toURI());
            }
            buf.append(uri.getRawPath());
            if (uri.getRawQuery() != null) {
                buf.append("?");
                buf.append(uri.getRawQuery());
            }

            requestLine = new BasicRequestLine(requestLine.getMethod(), buf.toString(),
                    requestLine.getProtocolVersion());
        }
    }

    HttpMessage message = requestFactory.newHttpRequest(requestLine);
    message.setHeaders(headers);
    return message;
}

From source file:com.fatwire.dta.sscrawler.App.java

protected void doWork(final CommandLine cmd) throws Exception {
    final Crawler crawler = new Crawler();

    URI startUri = null;

    startUri = URI.create(cmd.getArgs()[1]);
    if (cmd.hasOption('m')) {
        crawler.setMaxPages(Integer.parseInt(cmd.getOptionValue('m')));
    }/*  ww  w  . j  a va2s.  com*/

    final int threads = Integer.parseInt(cmd.getOptionValue('t', "5"));

    if (startUri == null) {
        throw new IllegalArgumentException("startUri is not set");
    }
    final int t = startUri.toASCIIString().indexOf("/ContentServer");
    if (t == -1) {
        throw new IllegalArgumentException("/ContentServer is not found on the startUri.");
    }

    crawler.setStartUri(new URI(null, null, null, -1, startUri.getRawPath(), startUri.getRawQuery(),
            startUri.getFragment()));
    final HostConfig hc = createHostConfig(URI.create(startUri.toASCIIString().substring(0, t)));

    final String proxyUsername = cmd.getOptionValue("pu");
    final String proxyPassword = cmd.getOptionValue("pw");
    final String proxyHost = cmd.getOptionValue("ph");
    final int proxyPort = Integer.parseInt(cmd.getOptionValue("", "8080"));

    if (StringUtils.isNotBlank(proxyUsername) && StringUtils.isNotBlank(proxyUsername)) {
        hc.setProxyCredentials(new UsernamePasswordCredentials(proxyUsername, proxyPassword));
    }

    if (StringUtils.isNotBlank(proxyHost)) {
        hc.setProxyHost(new ProxyHost(proxyHost, proxyPort));
    } else if (StringUtils.isNotBlank(System.getProperty("http.proxyhost"))
            && StringUtils.isNotBlank(System.getProperty("http.proxyport"))) {
        hc.setProxyHost(new ProxyHost(System.getProperty("http.proxyhost"),
                Integer.parseInt(System.getProperty("http.proxyport"))));

    }
    crawler.setHostConfig(hc);

    SSUriHelper helper = null;

    if (cmd.hasOption('f')) {
        final UriHelperFactory f = (UriHelperFactory) Class.forName(cmd.getOptionValue('f')).newInstance();
        helper = f.create(crawler.getStartUri().getPath());
    } else {
        helper = new SSUriHelper(crawler.getStartUri().getPath());
    }
    final ThreadPoolExecutor readerPool = new RenderingThreadPool(threads);
    final MBeanServer platform = java.lang.management.ManagementFactory.getPlatformMBeanServer();
    try {
        platform.registerMBean(readerPool, new ObjectName("com.fatwire.crawler:name=readerpool"));
    } catch (final Throwable x) {
        LogFactory.getLog(App.class).error(x.getMessage(), x);
    }

    crawler.setExecutor(readerPool);
    File path = null;
    if (cmd.hasOption('d')) {
        path = new File(cmd.getOptionValue("d"));
    } else {
        path = getOutputDir();
    }
    if (path != null) {
        final SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmm");
        path = new File(path, df.format(new Date()));
        path.mkdirs();
    }
    crawler.setReporters(createReporters(path, helper));
    crawler.setUriHelper(helper);
    try {
        crawler.work();
    } finally {
        readerPool.shutdown();
        try {
            platform.unregisterMBean(new ObjectName("com.fatwire.crawler:name=readerpool"));
        } catch (final Throwable x) {
            LogFactory.getLog(App.class).error(x.getMessage(), x);
        }
    }
}