Example usage for java.net URI getFragment

List of usage examples for java.net URI getFragment

Introduction

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

Prototype

public String getFragment() 

Source Link

Document

Returns the decoded fragment component of this URI.

Usage

From source file:org.soyatec.windowsazure.blob.internal.BlockBlob.java

boolean uploadData(IBlobProperties blobProperties, BlobStream stream, long length, boolean overwrite,
        String eTag, NameValueCollection queryParameters, int action) throws Exception {

    // fix root container
    boolean isRoot = container.getName().equals(IBlobContainer.ROOT_CONTAINER);
    String containerName = isRoot ? "" : container.getName();
    ResourceUriComponents uriComponents = new ResourceUriComponents(container.getAccountName(), containerName,
            blobProperties.getName());/*from w ww  .  j  a v a  2s . c om*/
    URI blobUri = HttpUtilities.createRequestUri(container.getBaseUri(), container.isUsePathStyleUris(),
            container.getAccountName(), containerName, blobProperties.getName(), container.getTimeout(),
            queryParameters, uriComponents, container.getCredentials());

    if (SSLProperties.isSSL()) {
        try {
            URI newBlobUri = new URI("https", null, blobUri.getHost(), 443, blobUri.getPath(),
                    blobUri.getQuery(), blobUri.getFragment());
            blobUri = newBlobUri;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    HttpRequest request = createHttpRequestForPutBlob(blobUri, HttpMethod.Put, blobProperties, length,
            overwrite, eTag);
    // if (isRoot) {
    // request.addHeader(HeaderNames.ApiVersion,
    // XmsVersion.VERSION_2009_07_17);
    // }
    request.setHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2009_09_19);
    if (action == BLOB_ACTION || action == BLOCK_ACTION) { // small blob or
        // block
        request.addHeader(HeaderNames.BlobType, BlobType.BlockBlob.getLiteral());
    }

    boolean retval = false;
    BlobStream requestStream = new BlobMemoryStream();
    Utilities.copyStream(stream, requestStream, (int) length);
    byte[] body = requestStream.getBytes();
    ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body));

    processMD5(blobProperties, request, body, action);

    container.credentials.signRequest(request, uriComponents);

    HttpWebResponse response = null;
    if (SSLProperties.isSSL()) {
        SSLSocketFactory factory = SslUtil.createSSLSocketFactory(SSLProperties.getKeyStore(),
                SSLProperties.getKeyStorePasswd(), SSLProperties.getTrustStore(),
                SSLProperties.getTrustStorePasswd(), SSLProperties.getKeyAlias());
        response = HttpUtilities.getSSLReponse((HttpUriRequest) request, factory);
    } else {
        response = HttpUtilities.getResponse(request);
    }
    if (response.getStatusCode() == HttpStatus.SC_CREATED) {
        retval = true;
    } else if (!overwrite && (response.getStatusCode() == HttpStatus.SC_PRECONDITION_FAILED
            || response.getStatusCode() == HttpStatus.SC_NOT_MODIFIED)) {
        retval = false;
    } else {
        retval = false;
        HttpUtilities.processUnexpectedStatusCode(response);
    }

    blobProperties.setLastModifiedTime(response.getLastModified());
    blobProperties.setETag(response.getHeader(HeaderNames.ETag));
    requestStream.close();
    response.close();
    return retval;
}

From source file:com.box.restclientv2.httpclientsupport.HttpClientURIBuilder.java

private void digestURI(final URI uri) throws URISyntaxException {
    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(), HttpClientConsts.UTF_8);
    this.encodedFragment = uri.getRawFragment();
    this.fragment = uri.getFragment();
}

From source file:org.mcxiaoke.commons.http.util.URIBuilderEx.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(), URIUtilsEx.UTF_8);
    this.encodedFragment = uri.getRawFragment();
    this.fragment = uri.getFragment();
}

From source file:org.eclipse.orion.server.git.servlets.GitDiffHandlerV1.java

private boolean identifyNewDiffResource(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    try {//from  www . j  a  va 2 s. c om
        StringWriter writer = new StringWriter();
        IOUtilities.pipe(request.getReader(), writer, false, false);
        JSONObject requestObject = new JSONObject(writer.toString());
        URI u = getURI(request);
        IPath p = new Path(u.getPath());
        IPath np = new Path("/"); //$NON-NLS-1$
        for (int i = 0; i < p.segmentCount(); i++) {
            String s = p.segment(i);
            if (i == 2) {
                s += ".."; //$NON-NLS-1$
                s += GitUtils.encode(requestObject.getString(GitConstants.KEY_COMMIT_NEW));
            }
            np = np.append(s);
        }
        if (p.hasTrailingSeparator())
            np = np.addTrailingSeparator();
        URI nu = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), np.toString(), u.getQuery(),
                u.getFragment());
        JSONObject result = new JSONObject();
        result.put(ProtocolConstants.KEY_LOCATION, nu.toString());
        OrionServlet.writeJSONResponse(request, response, result);
        response.setHeader(ProtocolConstants.HEADER_LOCATION, resovleOrionURI(request, nu).toString());
        return true;
    } catch (Exception e) {
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "An error occured when identifying a new Diff resource.", e));
    }
}

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')));
    }//  www  .j av  a2  s  .c om

    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);
        }
    }
}

From source file:com.fujitsu.dc.core.rs.cell.AuthzEndPointResource.java

/**
 * ImplicitFlow????????????./*w  w  w  .j ava  2 s.  c  om*/
 * @param response ??
 * @return true: ?? false:?
 */
protected boolean isSuccessAuthorization(Response response) {
    // ??302?????????????
    if (Status.FOUND.getStatusCode() != response.getStatus()) {
        return false;
    }

    // Location???URL???????
    String locationStr = (String) response.getMetadata().getFirst(HttpHeaders.LOCATION);
    try {
        URI uri = new URI(locationStr);
        String fragment = uri.getFragment();
        // ?????API?I/F????
        if (null == fragment) {
            return false;
        }
        if (fragment.indexOf(OAuth2Helper.Key.ERROR + "=") >= 0
                && fragment.indexOf(OAuth2Helper.Key.ERROR_DESCRIPTION + "=") >= 0
                && fragment.indexOf(OAuth2Helper.Key.STATE + "=") >= 0
                && fragment.indexOf(OAuth2Helper.Key.CODE + "=") >= 0) {
            return false;
        }
    } catch (URISyntaxException e) {
        return false;
    }
    return true;
}

From source file:uk.ac.diamond.scisoft.ncd.passerelle.actors.service.DataReductionServiceImpl.java

private void createDetectorNode(String detector, int entry_id, String inputfilePath)
        throws HDF5Exception, URISyntaxException {

    int detector_id = NcdNexusUtils.makegroup(entry_id, detector, Nexus.DATA);

    int file_handle = H5.H5Fopen(inputfilePath, HDF5Constants.H5F_ACC_RDONLY, HDF5Constants.H5P_DEFAULT);
    int entry_group_id = H5.H5Gopen(file_handle, "entry1", HDF5Constants.H5P_DEFAULT);
    int detector_group_id = H5.H5Gopen(entry_group_id, detector, HDF5Constants.H5P_DEFAULT);
    int input_data_id = H5.H5Dopen(detector_group_id, "data", HDF5Constants.H5P_DEFAULT);

    boolean isNAPImount = H5.H5Aexists(input_data_id, "napimount");
    if (isNAPImount) {
        int attr_id = H5.H5Aopen(input_data_id, "napimount", HDF5Constants.H5P_DEFAULT);
        int type_id = H5.H5Aget_type(attr_id);
        int size = H5.H5Tget_size(type_id);
        byte[] link = new byte[size];
        H5.H5Aread(attr_id, type_id, link);

        String str = new String(link);
        final URI ulink = new URI(str);
        if (ulink.getScheme().equals("nxfile")) {
            String lpath = ulink.getPath();
            String ltarget = ulink.getFragment();
            File f = new File(lpath);
            if (!f.exists()) {
                logger.debug("SCISOFT NCD: Linked file, {}, does not exist!", lpath);

                // see if linked file in same directory
                File file = new File(inputfilePath);
                f = new File(file.getParent(), f.getName());
                if (!f.exists()) {
                    H5.H5Tclose(type_id);
                    H5.H5Aclose(attr_id);

                    H5.H5Gclose(detector_id);

                    H5.H5Dclose(input_data_id);
                    H5.H5Gclose(detector_group_id);
                    H5.H5Gclose(entry_group_id);
                    H5.H5Fclose(file_handle);

                    throw new HDF5Exception("File, " + lpath + ", does not exist");
                }/*from w ww . j  a  v a2  s.c  om*/
            }
            lpath = f.getAbsolutePath();
            H5.H5Lcreate_external(lpath, ltarget, detector_id, "data", HDF5Constants.H5P_DEFAULT,
                    HDF5Constants.H5P_DEFAULT);
        } else {
            logger.error("SCISOFT NCD: Linked file has incompatible type: " + ulink.getScheme());
        }
        H5.H5Tclose(type_id);
        H5.H5Aclose(attr_id);
    } else {
        H5.H5Lcreate_external(inputfilePath, "/entry1/" + detector + "/data", detector_id, "data",
                HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT);
    }

    boolean exists = H5.H5Lexists(detector_group_id, "errors", HDF5Constants.H5P_DEFAULT);
    if (exists) {
        H5.H5Lcreate_external(inputfilePath, "/entry1/" + detector + "/errors", detector_id, "errors",
                HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT);
    }

    H5.H5Gclose(detector_id);

    H5.H5Dclose(input_data_id);
    H5.H5Gclose(detector_group_id);
    H5.H5Gclose(entry_group_id);
    H5.H5Fclose(file_handle);
}

From source file:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java

private String append(String base, Map<String, ?> query, Map<String, String> keys, boolean fragment) {

    UriComponentsBuilder template = UriComponentsBuilder.newInstance();
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(base);
    URI redirectUri;
    try {/*  w ww . j  av a  2  s. com*/
        // assume it's encoded to start with (if it came in over the wire)
        redirectUri = builder.build(true).toUri();
    } catch (Exception e) {
        // ... but allow client registrations to contain hard-coded non-encoded values
        redirectUri = builder.build().toUri();
        builder = UriComponentsBuilder.fromUri(redirectUri);
    }
    template.scheme(redirectUri.getScheme()).port(redirectUri.getPort()).host(redirectUri.getHost())
            .userInfo(redirectUri.getUserInfo()).path(redirectUri.getPath());

    if (fragment) {
        StringBuilder values = new StringBuilder();
        if (redirectUri.getFragment() != null) {
            String append = redirectUri.getFragment();
            values.append(append);
        }
        for (String key : query.keySet()) {
            if (values.length() > 0) {
                values.append("&");
            }
            String name = key;
            if (keys != null && keys.containsKey(key)) {
                name = keys.get(key);
            }
            values.append(name + "={" + key + "}");
        }
        if (values.length() > 0) {
            template.fragment(values.toString());
        }
        UriComponents encoded = template.build().expand(query).encode();
        builder.fragment(encoded.getFragment());
    } else {
        for (String key : query.keySet()) {
            String name = key;
            if (nonNull(keys) && keys.containsKey(key)) {
                name = keys.get(key);
            }
            template.queryParam(name, "{" + key + "}");
        }
        template.fragment(redirectUri.getFragment());
        UriComponents encoded = template.build().expand(query).encode();
        builder.query(encoded.getQuery());
    }

    return builder.build().toUriString();
}

From source file:org.chiba.xml.xforms.connector.file.FileURIResolver.java

/**
 * Performs link traversal of the <code>file</code> URI and returns the
 * result as a DOM document.//  w  w  w.  j  a  va 2 s  .  c  o  m
 *
 * @return a DOM node parsed from the <code>file</code> URI.
 * @throws XFormsException if any error occurred during link traversal.
 */
public Object resolve() throws XFormsException {
    try {
        // create uri
        URI uri = new URI(getURI());

        // use scheme specific part in order to handle UNC names
        String fileName = uri.getSchemeSpecificPart();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("loading file '" + fileName + "'");
        }

        // create file
        File file = new File(fileName);

        // check for directory
        if (file.isDirectory()) {
            return FileURIResolver.buildDirectoryListing(file);
        }

        // parse file
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        Document document = factory.newDocumentBuilder().parse(file);

        // check for fragment identifier
        if (uri.getFragment() != null) {
            return document.getElementById(uri.getFragment());
        }

        return document;
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler.java

private static Path getExistingDistCacheFilePath(Configuration conf, URL url) throws IOException {
    URI[] cacheFileUris = DistributedCache.getCacheFiles(conf);
    if (cacheFileUris != null) {
        String fileName = url.getRef() == null ? FilenameUtils.getName(url.getPath()) : url.getRef();
        for (URI cacheFileUri : cacheFileUris) {
            Path path = new Path(cacheFileUri);
            String cacheFileName = cacheFileUri.getFragment() == null ? path.getName()
                    : cacheFileUri.getFragment();
            // Match
            //     - if both filenames are same and no symlinks (or)
            //     - if both symlinks are same (or)
            //     - symlink of existing cache file is same as the name of the new file to be added.
            //         That would be the case when hbase-0.98.4.jar#hbase.jar is configured via Oozie
            // and register hbase.jar is done in the pig script.
            // If two different files are symlinked to the same name, then there is a conflict
            // and hadoop itself does not guarantee which file will be symlinked to that name.
            // So we are good.
            if (fileName.equals(cacheFileName)) {
                return path;
            }/*from   ww  w . j a v  a 2s .c  o m*/
        }
    }
    return null;
}