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:com.ibm.jaggr.core.impl.AbstractAggregatorImpl.java

protected void processResourceRequest(HttpServletRequest req, HttpServletResponse resp, IResource res,
        String path) {/*from  w  w  w  .j  a  va2s . c om*/
    final String sourceMethod = "processRequest"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod,
                new Object[] { req, resp, res, path });
    }
    try {
        URI uri = res.getURI();
        if (path != null && path.length() > 0 && !uri.getPath().endsWith("/")) { //$NON-NLS-1$
            // Make sure we resolve against a folder path
            uri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath() + "/", uri.getQuery(), //$NON-NLS-1$
                    uri.getFragment());
            res = newResource(uri);
        }
        IResource resolved = res.resolve(path);
        if (!resolved.exists()) {
            throw new NotFoundException(resolved.getURI().toString());
        }
        resp.setDateHeader("Last-Modified", resolved.lastModified()); //$NON-NLS-1$
        int expires = getConfig().getExpires();
        resp.addHeader("Cache-Control", //$NON-NLS-1$
                "public" + (expires > 0 ? (", max-age=" + expires) : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        );
        InputStream is = res.resolve(path).getInputStream();
        OutputStream os = resp.getOutputStream();
        CopyUtil.copy(is, os);
    } catch (NotFoundException e) {
        if (log.isLoggable(Level.INFO)) {
            log.log(Level.INFO, e.getMessage() + " - " + req.getRequestURI(), e); //$NON-NLS-1$
        }
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } catch (Exception e) {
        if (log.isLoggable(Level.WARNING)) {
            log.log(Level.WARNING, e.getMessage() + " - " + req.getRequestURI(), e); //$NON-NLS-1$
        }
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    if (isTraceLogging) {
        log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
    }

}

From source file:org.eclipse.thym.core.plugin.CordovaPluginManager.java

/**
 * Installs a Cordova plug-in from a git repository. 
 * This method delegates to {@link #doInstallPlugin(File)} after cloning the
 * repository to a temporary location to complete the installation of the 
 * plug-in. //from ww w.  j  av a 2  s  . com
 * <br/>
 * If commit is not null the cloned repository will be checked out to 
 * commit. 
 * <br/>
 * If subdir is not null it is assumed that the subdir path exists and installation 
 * will be done from that location. 
 * 
 * @param uri
 * @param overwrite
 * @param isDependency 
 * @param monitor 
 * @param commit 
 * @param subdir
 * @throws CoreException
 */
public void installPlugin(URI uri, FileOverwriteCallback overwrite, boolean isDependency,
        IProgressMonitor monitor) throws CoreException {
    File tempRepoDirectory = new File(FileUtils.getTempDirectory(),
            "cordova_plugin_tmp_" + Long.toString(System.currentTimeMillis()));
    tempRepoDirectory.deleteOnExit();
    try {
        if (monitor.isCanceled())
            return;
        monitor.subTask("Clone plugin repository");
        String gitUrl = uri.getScheme() + ":" + uri.getSchemeSpecificPart();
        Git git = Git.cloneRepository().setDirectory(tempRepoDirectory).setURI(gitUrl).call();
        File pluginDirectory = tempRepoDirectory;
        String fragment = uri.getFragment();
        String commit = null;
        String subdir = null;

        if (fragment != null) {
            int idx = fragment.indexOf(':');
            if (idx < 0) {
                idx = fragment.length();
            }
            commit = fragment.substring(0, idx);
            subdir = fragment.substring(Math.min(idx + 1, fragment.length()));
            if (monitor.isCanceled()) {
                throw new CanceledException("Plug-in installation cancelled");
            }
            if (commit != null && !commit.isEmpty()) {
                git.checkout().setName(commit).call();
            }
            monitor.worked(1);

            if (subdir != null && !subdir.isEmpty()) {
                pluginDirectory = new File(tempRepoDirectory, subdir);
                if (!pluginDirectory.isDirectory()) {
                    throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID,
                            NLS.bind("{0} directory does not exist in this git repository", subdir)));
                }
            }
        }
        SubProgressMonitor sm = new SubProgressMonitor(monitor, 1);

        Document doc = readPluginXML(pluginDirectory);
        this.doInstallPlugin(pluginDirectory, doc, overwrite, sm);
        String id = CordovaPluginXMLHelper.getAttributeValue(doc.getDocumentElement(), "id");
        JsonObject source = new JsonObject();
        source.addProperty("type", "git");
        source.addProperty("url", gitUrl);
        if (subdir != null && !subdir.isEmpty()) {
            source.addProperty("subdir", subdir);
        }
        if (commit != null && !commit.isEmpty()) {
            source.addProperty("ref", commit);
        }
        this.saveFetchMetadata(source, id, monitor);
        if (!isDependency) {//update config.xml 
            List<IPluginInstallationAction> actions = new ArrayList<IPluginInstallationAction>(1);
            Map<String, String> params = new HashMap<String, String>();
            params.put("url", uri.toString());
            actions.add(getPluginInstallRecordAction(doc, params));
            runActions(actions, false, overwrite, monitor);
        }
    } catch (GitAPIException e) {
        throw new CoreException(
                new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "Error cloning the plugin repository", e));
    } finally {
        monitor.done();
    }
}

From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java

private URI buildUri(HttpRequest request, Joiner joiner) {
    URI requestUri = request.getUri();

    Map<String, Collection<String>> queryParams = request.getQueryParams();
    if (queryParams != null && !queryParams.isEmpty()) {
        URIBuilder uriBuilder = new URIBuilder();
        StringBuilder queryStringBuilder = new StringBuilder();
        boolean hasQuery = !queryParams.isEmpty();
        for (Map.Entry<String, Collection<String>> stringCollectionEntry : queryParams.entrySet()) {
            String key = stringCollectionEntry.getKey();
            Collection<String> queryParamsValueList = stringCollectionEntry.getValue();
            if (request.isQueryParamsParseAsMultiValue()) {
                for (String queryParamsValue : queryParamsValueList) {
                    uriBuilder.addParameter(key, queryParamsValue);
                    queryStringBuilder.append(key).append("=").append(queryParamsValue).append("&");
                }//  ww w .  j ava 2 s.co  m
            } else {
                String value = joiner.join(queryParamsValueList);
                uriBuilder.addParameter(key, value);
                queryStringBuilder.append(key).append("=").append(value).append("&");
            }
        }
        uriBuilder.setFragment(requestUri.getFragment());
        uriBuilder.setHost(requestUri.getHost());
        uriBuilder.setPath(requestUri.getPath());
        uriBuilder.setPort(requestUri.getPort());
        uriBuilder.setScheme(requestUri.getScheme());
        uriBuilder.setUserInfo(requestUri.getUserInfo());
        try {

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

                if (hasQuery) {
                    String query = queryStringBuilder.substring(0, queryStringBuilder.length() - 1);
                    requestUri = new URI(requestUri.getScheme() + "://" + requestUri.getHost() + ":"
                            + requestUri.getPort() + urlPath + "?" + query);
                } else {
                    requestUri = new URI(requestUri.getScheme() + "://" + requestUri.getHost() + ":"
                            + requestUri.getPort() + urlPath);
                }
            } else {
                requestUri = uriBuilder.build();
            }
        } catch (URISyntaxException e) {
            LOGGER.warn("could not update uri: {}", requestUri);
        }
    }
    return requestUri;
}

From source file:org.apache.ogt.http.impl.client.DefaultRedirectStrategy.java

public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }//from  w  ww  . j av a  2 s  .  c o  m
    //get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    String location = locationHeader.getValue();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    URI uri = createLocationURI(location);

    HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (target == null) {
            throw new IllegalStateException("Target host not available " + "in the HTTP context");
        }
        try {
            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new RedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

From source file:spaceRedirectStrategy.java

public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }//from www .  jav  a  2  s .co  m
    //get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    String location = locationHeader.getValue().replaceAll(" ", "%20");
    ;
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    URI uri = createLocationURI(location);

    HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (target == null) {
            throw new IllegalStateException("Target host not available " + "in the HTTP context");
        }
        try {
            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new RedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            //redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

From source file:podd.tab.TabImporter.java

/**
 * Fetches or Creates a ParentReferencePoddEntity given its object name and the column index
 * @param objectName/*w ww.  ja v  a  2  s  .  c  o m*/
 * @param columnIndex
 * @return
 */
private PoddEntityWrapper fetchCreatePoddEntity(URI objectTypeURI, int columnIndex) {
    String key = getPoddEntityKey(objectTypeURI.getFragment(), columnIndex);
    PoddEntityWrapper prpe = columnPoddEntityMap.get(key);
    if (prpe == null) {
        prpe = new PoddEntityWrapper();

        PoddEntity poddEntity = new PoddEntity();
        poddEntity.setObjectTypeURI(objectTypeURI);

        prpe.setPoddEntity(poddEntity);

        columnPoddEntityMap.put(key, prpe);
    }

    return prpe;
}

From source file:org.apache.synapse.transport.nhttp.ClientHandler.java

private void setHeaders(HttpContext context, HttpResponse response, MessageContext outMsgCtx,
        MessageContext responseMsgCtx) {
    Header[] headers = response.getAllHeaders();
    if (headers != null && headers.length > 0) {

        Map<String, String> headerMap = new TreeMap<String, String>(new Comparator<String>() {
            public int compare(String o1, String o2) {
                return o1.compareToIgnoreCase(o2);
            }//w  w w . j av a2s.c  om
        });
        String endpointURLPrefix = (String) context.getAttribute(NhttpConstants.ENDPOINT_PREFIX);

        String servicePrefix = (String) outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX);
        for (int i = 0; i < headers.length; i++) {
            Header header = headers[i];

            // if this header is already added
            if (headerMap.containsKey(header.getName())) {
                /* this is a multi-value header */
                // generate the key
                String key = NhttpConstants.EXCESS_TRANSPORT_HEADERS;
                // get the old value
                String oldValue = headerMap.get(header.getName());
                // adds additional values to a list in a property of message
                // context
                Map map;
                if (responseMsgCtx.getProperty(key) != null) {
                    map = (Map) responseMsgCtx.getProperty(key);
                    map.put(header.getName(), oldValue);
                } else {
                    map = new MultiValueMap();
                    map.put(header.getName(), oldValue);
                    // set as a property in message context
                    responseMsgCtx.setProperty(key, map);
                }

            }

            if ("Location".equals(header.getName()) && endpointURLPrefix != null && servicePrefix != null) {
                // Here, we are changing only the host name and the port of
                // the new URI - value of the Location
                // header.
                // If the new URI is again referring to a resource in the
                // server to which the original request
                // is sent, then replace the hostname and port of the URI
                // with the hostname and port of synapse
                // We are not changing the request url here, only the host
                // name and the port.
                try {
                    URI serviceURI = new URI(servicePrefix);
                    URI endpointURI = new URI(endpointURLPrefix);
                    URI locationURI = new URI(header.getValue());

                    if (locationURI.getHost().equalsIgnoreCase(endpointURI.getHost())) {
                        URI newURI = new URI(locationURI.getScheme(), locationURI.getUserInfo(),
                                serviceURI.getHost(), serviceURI.getPort(), locationURI.getPath(),
                                locationURI.getQuery(), locationURI.getFragment());
                        headerMap.put(header.getName(), newURI.toString());
                        responseMsgCtx.setProperty(NhttpConstants.SERVICE_PREFIX,
                                outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX));
                    }
                } catch (URISyntaxException e) {
                    log.error(e.getMessage(), e);
                }
            } else {
                headerMap.put(header.getName(), header.getValue());
            }
        }
        responseMsgCtx.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap);
    }
}

From source file:clj_httpc.CustomRedirectStrategy.java

public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }/*www  .  j  a  va 2  s .  c  o  m*/
    //get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    String location = locationHeader.getValue();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    URI uri = createLocationURI(location);

    HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (target == null) {
            throw new IllegalStateException("Target host not available " + "in the HTTP context");
        }
        try {
            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        CustomRedirectLocations redirectLocations = (CustomRedirectLocations) context
                .getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new CustomRedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            int statusCode = response.getStatusLine().getStatusCode();
            redirectLocations.add(redirectURI, statusCode);
        }
    }

    return uri;
}

From source file:podd.tab.TabImporter.java

/**
 * Rollback any objects that have created. 
 * TODO: But how to rollback objects that have been edited.
 * @return/* www. j ava2s . com*/
 */
public boolean rollbackCreatedObjects() {
    if (_INFO) {
        LOGGER.info("Rolling back created objects");
    }
    try {
        if (null != processingOrder) {
            List<URI> reversedProcessingOrder = new ArrayList<URI>();
            reversedProcessingOrder.addAll(processingOrder);
            Collections.reverse(reversedProcessingOrder);

            for (URI uri : reversedProcessingOrder) {

                String poddObjectId = uri.getFragment();

                if (_INFO) {
                    LOGGER.info("Deleting podd object that was created: " + poddObjectId);
                }

                PoddObject object = objectDao.load(poddObjectId);
                if (object != null) {
                    objectDao.forceDelete(object);
                }
            }
        }
    } catch (DataAccessException e) {
        LOGGER.error("Found exception", e);
        e.printStackTrace();
        return false;
    }

    if (_INFO) {
        LOGGER.info("Rollback successful");
    }

    return true;
}

From source file:org.apache.hadoop.fs.azure.NativeAzureFileSystem.java

/**
 * Puts in the authority of the default file system if it is a WASB file
 * system and the given URI's authority is null.
 * /*from  w  w w .ja v  a2  s  .  co  m*/
 * @return The URI with reconstructed authority if necessary and possible.
 */
private static URI reconstructAuthorityIfNeeded(URI uri, Configuration conf) {
    if (null == uri.getAuthority()) {
        // If WASB is the default file system, get the authority from there
        URI defaultUri = FileSystem.getDefaultUri(conf);
        if (defaultUri != null && isWasbScheme(defaultUri.getScheme())) {
            try {
                // Reconstruct the URI with the authority from the default URI.
                return new URI(uri.getScheme(), defaultUri.getAuthority(), uri.getPath(), uri.getQuery(),
                        uri.getFragment());
            } catch (URISyntaxException e) {
                // This should never happen.
                throw new Error("Bad URI construction", e);
            }
        }
    }
    return uri;
}