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:net.www_eee.portal.channels.ProxyChannel.java

/**
 * Construct the final {@linkplain URI#isAbsolute() absolute} {@link URL} for the
 * {@linkplain #createProxyRequest(Page.Request, Channel.Mode, CloseableHttpClient) proxied} file by resolving the
 * relative {@linkplain #getProxiedFileLocalURI(Page.Request, Channel.Mode, boolean) proxied file local URI} against
 * the {@linkplain #getProxiedBaseURI(Page.Request) base URI}, and if the result isn't absolute, against the
 * {@linkplain ConfigManager#getContextResourceLocalHostURI(UriInfo, String, Map, String, boolean) local host context}
 * ./*from   w  w w . j  a va  2s.c o  m*/
 * 
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param mode The {@link net.www_eee.portal.Channel.Mode Mode} of the request.
 * @param validate Should any {@linkplain #isParentFoldersRestrictionDisabled(Page.Request) parent folder} or
 * {@linkplain #isDefaultPathRestrictionEnabled(Page.Request) default path} restrictions be evaluated?
 * @return The proxied file {@link URL}.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @throws WebApplicationException If a problem occurred while determining the result.
 * @see #createProxyRequest(Page.Request, Channel.Mode, CloseableHttpClient)
 * @see #PROXIED_FILE_URL_HOOK
 */
protected URL getProxiedFileURL(final Page.Request pageRequest, final Mode mode, final boolean validate)
        throws WWWEEEPortal.Exception, WebApplicationException {
    final Object[] context = new Object[] { mode, Boolean.valueOf(validate) };
    URL proxiedFileURL = PROXIED_FILE_URL_HOOK.value(plugins, context, pageRequest);
    if (proxiedFileURL == null) {

        try {
            final URI proxiedFileLocalURI = getProxiedFileLocalURI(pageRequest, mode, validate);
            final URI baseURI = getProxiedBaseURI(pageRequest);
            if (proxiedFileLocalURI != null) {

                final URI proxiedFileURI = baseURI.resolve(proxiedFileLocalURI);
                if (proxiedFileURI.isAbsolute()) {
                    proxiedFileURL = proxiedFileURI.toURL();
                } else {
                    proxiedFileURL = ConfigManager
                            .getContextResourceLocalHostURI(pageRequest.getUriInfo(), proxiedFileURI.getPath(),
                                    NetUtil.getQueryParams(proxiedFileURI), proxiedFileURI.getFragment(), true)
                            .toURL();
                }

            } else {

                if (baseURI.isAbsolute()) {
                    proxiedFileURL = baseURI.toURL();
                } else {
                    proxiedFileURL = ConfigManager.getContextResourceLocalHostURI(pageRequest.getUriInfo(),
                            baseURI.getPath(), NetUtil.getQueryParams(baseURI), baseURI.getFragment(), true)
                            .toURL();
                }

            }
        } catch (MalformedURLException mue) {
            throw new WWWEEEPortal.SoftwareException(mue);
        }

    }
    proxiedFileURL = PROXIED_FILE_URL_HOOK
            .requireFilteredResult(PROXIED_FILE_URL_HOOK.filter(plugins, context, pageRequest, proxiedFileURL));
    return proxiedFileURL;
}

From source file:org.apache.nifi.web.api.ApplicationResource.java

/**
 * Generate a resource uri based off of the specified parameters.
 *
 * @param path path/*ww  w  .j a  v  a  2  s  . c o  m*/
 * @return resource uri
 */
protected String generateResourceUri(final String... path) {
    final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
    uriBuilder.segment(path);
    URI uri = uriBuilder.build();
    try {

        // check for proxy settings
        final String scheme = httpServletRequest.getHeader(PROXY_SCHEME_HTTP_HEADER);
        final String host = httpServletRequest.getHeader(PROXY_HOST_HTTP_HEADER);
        final String port = httpServletRequest.getHeader(PROXY_PORT_HTTP_HEADER);
        String baseContextPath = httpServletRequest.getHeader(PROXY_CONTEXT_PATH_HTTP_HEADER);

        // if necessary, prepend the context path
        String resourcePath = uri.getPath();
        if (baseContextPath != null) {
            // normalize context path
            if (!baseContextPath.startsWith("/")) {
                baseContextPath = "/" + baseContextPath;
            }

            // determine the complete resource path
            resourcePath = baseContextPath + resourcePath;
        }

        // determine the port uri
        int uriPort = uri.getPort();
        if (port != null) {
            if (StringUtils.isWhitespace(port)) {
                uriPort = -1;
            } else {
                try {
                    uriPort = Integer.parseInt(port);
                } catch (final NumberFormatException nfe) {
                    logger.warn(String.format(
                            "Unable to parse proxy port HTTP header '%s'. Using port from request URI '%s'.",
                            port, uriPort));
                }
            }
        }

        // construct the URI
        uri = new URI((StringUtils.isBlank(scheme)) ? uri.getScheme() : scheme, uri.getUserInfo(),
                (StringUtils.isBlank(host)) ? uri.getHost() : host, uriPort, resourcePath, uri.getQuery(),
                uri.getFragment());

    } catch (final URISyntaxException use) {
        throw new UriBuilderException(use);
    }
    return uri.toString();
}

From source file:com.emc.atmos.api.test.AtmosApiClientTest.java

@Test
public void testDisableSslValidation() throws Exception {
    Assume.assumeFalse(isVipr);//from w w  w. j av a 2  s.c  o m
    config.setDisableSslValidation(true);
    api = new AtmosApiClient(config);
    List<URI> sslUris = new ArrayList<URI>();
    for (URI uri : config.getEndpoints()) {
        sslUris.add(new URI("https", uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(),
                uri.getQuery(), uri.getFragment()));
    }
    config.setEndpoints(sslUris.toArray(new URI[sslUris.size()]));

    cleanup.add(api.createObject("Hello SSL!", null));
}

From source file:com.buaa.cfs.fs.FileSystem.java

/**
 * Canonicalize the given URI./*from  ww w.  j  a v  a2 s.  c  om*/
 * <p>
 * This is filesystem-dependent, but may for example consist of canonicalizing the hostname using DNS and adding the
 * default port if not specified.
 * <p>
 * The default implementation simply fills in the default port if not specified and if the filesystem has a default
 * port.
 *
 * @return URI
 */
protected URI canonicalizeUri(URI uri) {
    if (uri.getPort() == -1 && getDefaultPort() > 0) {
        // reconstruct the uri with the default port set
        try {
            uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), getDefaultPort(), uri.getPath(),
                    uri.getQuery(), uri.getFragment());
        } catch (URISyntaxException e) {
            // Should never happen!
            throw new AssertionError("Valid URI became unparseable: " + uri);
        }
    }

    return uri;
}

From source file:czd.lib.network.AsyncHttpClient.java

/**
 * Simple interface method, to enable or disable redirects. If you set manually RedirectHandler
 * on underlying HttpClient, effects of this method will be canceled.
 *
 * @param enableRedirects boolean/*  www. j av a  2s  .co  m*/
 */
public void setEnableRedirects(final boolean enableRedirects) {
    if (enableRedirects) {
        httpClient.setRedirectHandler(new DefaultRedirectHandler() {
            @Override
            public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
                if (response == null) {
                    throw new IllegalArgumentException("HTTP response may not be null");
                }
                int statusCode = response.getStatusLine().getStatusCode();
                switch (statusCode) {
                case HttpStatus.SC_MOVED_TEMPORARILY:
                case HttpStatus.SC_MOVED_PERMANENTLY:
                case HttpStatus.SC_SEE_OTHER:
                case HttpStatus.SC_TEMPORARY_REDIRECT:
                    return true;
                default:
                    return false;
                }
            }

            @Override
            public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
                if (response == null) {
                    throw new IllegalArgumentException("HTTP response may not be null");
                }
                //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");
                }
                //HERE IS THE MODIFIED LINE OF CODE
                String location = locationHeader.getValue().replaceAll(" ", "%20");

                URI uri;
                try {
                    uri = new URI(location);
                } catch (URISyntaxException ex) {
                    throw new ProtocolException("Invalid redirect URI: " + location, ex);
                }

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

                    HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

                    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("http.protocol.redirect-locations");

                    if (redirectLocations == null) {
                        redirectLocations = new RedirectLocations();
                        context.setAttribute("http.protocol.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:org.sakaiproject.lessonbuildertool.service.LessonBuilderEntityProducer.java

/**
 * Takes a URL and then decides if it should be replaced.
 * /*from  w  w w . j  a  va 2s.c o  m*/
 * @param value
 * @return
 */
private String processUrl(ContentCopyContext context, String value, String contentUrl,
        Map<Long, Long> itemMap) {
    // Need to deal with backticks.
    // - /access/group/{siteId}/
    // - /web/{siteId}/
    // - /dav/{siteId}/
    // http(s)://weblearn.ox.ac.uk/ - needs trimming
    try {
        URI uri = new URI(value);
        uri = uri.normalize();
        if (value.startsWith(ITEMDUMMY)) {
            String num = value.substring(ITEMDUMMYLEN);
            int i = num.indexOf("/");
            if (i >= 0)
                num = num.substring(0, i);
            else
                return value;
            long oldItem = 0;
            try {
                oldItem = Long.parseLong(num);
            } catch (Exception e) {
                return value;
            }
            Long newItem = itemMap.get(oldItem);
            if (newItem == null)
                return value;
            return ITEMDUMMY + newItem + "/";
        } else if ("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) {
            if (uri.getHost() != null) {
                // oldserver is the server that this archive is coming from
                // oldserver null means it's a local copy, e.g. duplicate site
                // for null we match URL against all of our server names
                String oldServer = context.getOldServer();
                if (oldServer == null && servers.contains(uri.getHost()) || uri.getHost().equals(oldServer)) {
                    // Drop the protocol and the host.
                    uri = new URI(null, null, null, -1, uri.getPath(), uri.getQuery(), uri.getFragment());
                }
            }
        }
        // Only do replacement on our URLs.
        if (uri.getHost() == null && uri.getPath() != null) {
            // Need to attempt todo path replacement now.
            String path = uri.getPath();
            Matcher matcher = pathPattern.matcher(path);

            if (matcher.matches() && context.getOldSiteId().equals(matcher.group(1))) {
                // Need to push the old URL onto the list of resources to
                // process. Except that we can't do that inside Lesson Builder
                //          addPath(context, path);
                String replacementPath = path.substring(0, matcher.start(1)) + context.getNewSiteId()
                        + path.substring(matcher.end(1));
                // Create a new URI with the new path
                uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), replacementPath,
                        uri.getQuery(), uri.getFragment());
            } else if (!path.startsWith("/") && contentUrl != null) {
                // Relative URL.
                try {
                    URI base = new URI(contentUrl);
                    URI link = base.resolve(uri);
                    // sorry, no can do
                    //addPath(context, link.getPath());
                } catch (URISyntaxException e) {
                    System.err.println("Supplied contentUrl isn't valid: " + contentUrl);
                }
            }
        }
        return uri.toString();
    } catch (URISyntaxException e) {
        // Log this so we may get an idea of the things that are breaking
        // the parser.
        System.err.println("Failed to parse URL: " + value + " " + e.getMessage());
    }
    return value;
}

From source file:ddf.catalog.impl.CatalogFrameworkImpl.java

/**
 * Retrieves a resource by URI./*from   w w w.  j  a v a2 s.c  o m*/
 * <p>
 * The {@link ResourceRequest} can specify either the product's URI or ID. If the product ID is
 * specified, then the matching {@link Metacard} must first be retrieved and the product URI
 * extracted from this {@link Metacard}.
 *
 * @param resourceRequest
 * @param site
 * @param isEnterprise
 * @param federatedSite
 * @param requestProperties
 * @return
 * @throws ResourceNotSupportedException
 * @throws ResourceNotFoundException
 */
protected ResourceInfo getResourceInfo(ResourceRequest resourceRequest, String site, boolean isEnterprise,
        StringBuilder federatedSite, Map<String, Serializable> requestProperties)
        throws ResourceNotSupportedException, ResourceNotFoundException {

    Metacard metacard;
    URI resourceUri;
    String name = resourceRequest.getAttributeName();
    try {
        if (ResourceRequest.GET_RESOURCE_BY_PRODUCT_URI.equals(name)) {
            // because this is a get resource by product uri, we already
            // have the product uri to return
            LOGGER.debug("get resource by product uri");
            Object value = resourceRequest.getAttributeValue();

            if (value instanceof URI) {
                resourceUri = (URI) value;
                if (StringUtils.isNotBlank(resourceUri.getFragment())) {
                    resourceRequest.getProperties().put(ContentItem.QUALIFIER, resourceUri.getFragment());
                    try {
                        resourceUri = new URI(resourceUri.getScheme(), resourceUri.getSchemeSpecificPart(),
                                null);
                    } catch (URISyntaxException e) {
                        throw new ResourceNotFoundException(
                                "Could not resolve URI by doing a URI based query: " + value);
                    }
                }

                Query propertyEqualToUriQuery = createPropertyIsEqualToQuery(Metacard.RESOURCE_URI,
                        resourceUri.toString());

                // if isEnterprise, go out and obtain the actual source
                // where the product's metacard is stored.
                QueryRequest queryRequest = new QueryRequestImpl(propertyEqualToUriQuery, isEnterprise,
                        Collections.singletonList(site == null ? this.getId() : site),
                        resourceRequest.getProperties());

                QueryResponse queryResponse = query(queryRequest, null, true);
                if (queryResponse.getResults().size() > 0) {
                    metacard = queryResponse.getResults().get(0).getMetacard();
                    federatedSite.append(metacard.getSourceId());
                    LOGGER.debug("Trying to lookup resource URI {} for metacardId: {}", resourceUri,
                            resourceUri);

                    if (!requestProperties.containsKey(Metacard.ID)) {
                        requestProperties.put(Metacard.ID, metacard.getId());
                    }
                    if (!requestProperties.containsKey(Metacard.RESOURCE_URI)) {
                        requestProperties.put(Metacard.RESOURCE_URI, metacard.getResourceURI());
                    }
                } else {
                    throw new ResourceNotFoundException(
                            "Could not resolve source id for URI by doing a URI based query: " + resourceUri);
                }
            } else {
                throw new ResourceNotSupportedException("The GetResourceRequest with attribute value of class '"
                        + value.getClass() + "' is not supported by this instance of the CatalogFramework.");
            }
        } else if (ResourceRequest.GET_RESOURCE_BY_ID.equals(name)) {
            // since this is a get resource by id, we need to obtain the
            // product URI
            LOGGER.debug("get resource by id");
            Object value = resourceRequest.getAttributeValue();
            if (value instanceof String) {
                String metacardId = (String) value;
                LOGGER.debug("metacardId = {},   site = {}", metacardId, site);
                QueryRequest queryRequest = new QueryRequestImpl(createMetacardIdQuery(metacardId),
                        isEnterprise, Collections.singletonList(site == null ? this.getId() : site),
                        resourceRequest.getProperties());

                QueryResponse queryResponse = query(queryRequest, null, true);
                if (queryResponse.getResults().size() > 0) {
                    metacard = queryResponse.getResults().get(0).getMetacard();
                    resourceUri = metacard.getResourceURI();
                    federatedSite.append(metacard.getSourceId());
                    LOGGER.debug("Trying to lookup resource URI {} for metacardId: {}", resourceUri,
                            metacardId);
                } else {
                    throw new ResourceNotFoundException(
                            "Could not resolve source id for URI by doing an id based query: " + metacardId);
                }

                if (!requestProperties.containsKey(Metacard.ID)) {
                    requestProperties.put(Metacard.ID, metacardId);
                }
                if (!requestProperties.containsKey(Metacard.RESOURCE_URI)) {
                    requestProperties.put(Metacard.RESOURCE_URI, resourceUri);
                }
            } else {
                throw new ResourceNotSupportedException("The GetResourceRequest with attribute value of class '"
                        + value.getClass() + "' is not supported by this instance of the CatalogFramework.");
            }
        } else {
            throw new ResourceNotSupportedException("The GetResourceRequest with attribute name '" + name
                    + "' is not supported by this instance of the CatalogFramework.");
        }
    } catch (UnsupportedQueryException | FederationException e) {

        throw new ResourceNotFoundException(DEFAULT_RESOURCE_NOT_FOUND_MESSAGE, e);
    }

    LOGGER.debug("Returning resourceURI: {}", resourceUri);
    if (resourceUri == null) {
        throw new ResourceNotFoundException(DEFAULT_RESOURCE_NOT_FOUND_MESSAGE);
    }

    return new ResourceInfo(metacard, resourceUri);
}

From source file:org.apache.hadoop.hive.metastore.HiveMetaStoreClientPreCatalog.java

private void resolveUris() throws MetaException {
    String metastoreUrisString[] = MetastoreConf.getVar(conf, ConfVars.THRIFT_URIS).split(",");

    List<URI> metastoreURIArray = new ArrayList<URI>();
    try {//from  www  .j  a v a  2s .  c om
        int i = 0;
        for (String s : metastoreUrisString) {
            URI tmpUri = new URI(s);
            if (tmpUri.getScheme() == null) {
                throw new IllegalArgumentException("URI: " + s + " does not have a scheme");
            }
            if (uriResolverHook != null) {
                metastoreURIArray.addAll(uriResolverHook.resolveURI(tmpUri));
            } else {
                metastoreURIArray.add(new URI(tmpUri.getScheme(), tmpUri.getUserInfo(),
                        HadoopThriftAuthBridge.getBridge().getCanonicalHostName(tmpUri.getHost()),
                        tmpUri.getPort(), tmpUri.getPath(), tmpUri.getQuery(), tmpUri.getFragment()));
            }
        }
        metastoreUris = new URI[metastoreURIArray.size()];
        for (int j = 0; j < metastoreURIArray.size(); j++) {
            metastoreUris[j] = metastoreURIArray.get(j);
        }

        if (MetastoreConf.getVar(conf, ConfVars.THRIFT_URI_SELECTION).equalsIgnoreCase("RANDOM")) {
            List uriList = Arrays.asList(metastoreUris);
            Collections.shuffle(uriList);
            metastoreUris = (URI[]) uriList.toArray();
        }
    } catch (IllegalArgumentException e) {
        throw (e);
    } catch (Exception e) {
        MetaStoreUtils.logAndThrowMetaException(e);
    }
}

From source file:org.openhab.io.rest.internal.resources.SitemapResource.java

static private WidgetBean createWidgetBean(String sitemapName, Widget widget, boolean drillDown, URI uri,
        String widgetId) {//  w ww  .  jav  a2s  .com
    ItemUIRegistry itemUIRegistry = RESTApplication.getItemUIRegistry();

    // Test visibility
    if (itemUIRegistry.getVisiblity(widget) == false)
        return null;

    WidgetBean bean = new WidgetBean();
    if (widget.getItem() != null) {
        Item item = ItemResource.getItem(widget.getItem());
        if (item != null) {
            bean.item = ItemResource.createItemBean(item, false,
                    UriBuilder.fromUri(uri).build().toASCIIString());
        }
    }
    bean.widgetId = widgetId;
    bean.icon = itemUIRegistry.getIcon(widget);
    bean.labelcolor = itemUIRegistry.getLabelColor(widget);
    bean.valuecolor = itemUIRegistry.getValueColor(widget);
    bean.label = itemUIRegistry.getLabel(widget);
    bean.type = widget.eClass().getName();
    if (widget instanceof LinkableWidget) {
        LinkableWidget linkableWidget = (LinkableWidget) widget;
        EList<Widget> children = itemUIRegistry.getChildren(linkableWidget);
        if (widget instanceof Frame) {
            int cntWidget = 0;
            for (Widget child : children) {
                widgetId += "_" + cntWidget;
                WidgetBean subWidget = createWidgetBean(sitemapName, child, drillDown, uri, widgetId);
                if (subWidget != null) {
                    bean.widgets.add(subWidget);
                    cntWidget++;
                }
            }
        } else if (children.size() > 0) {
            String pageName = itemUIRegistry.getWidgetId(linkableWidget);
            bean.linkedPage = createPageBean(sitemapName, itemUIRegistry.getLabel(widget),
                    itemUIRegistry.getIcon(widget), pageName, drillDown ? children : null, drillDown,
                    isLeaf(children), uri);
        }
    }
    if (widget instanceof Switch) {
        Switch switchWidget = (Switch) widget;
        for (Mapping mapping : switchWidget.getMappings()) {
            MappingBean mappingBean = new MappingBean();
            mappingBean.command = mapping.getCmd();
            mappingBean.label = mapping.getLabel();
            bean.mappings.add(mappingBean);
        }
    }
    if (widget instanceof Selection) {
        Selection selectionWidget = (Selection) widget;
        for (Mapping mapping : selectionWidget.getMappings()) {
            MappingBean mappingBean = new MappingBean();
            mappingBean.command = mapping.getCmd();
            mappingBean.label = mapping.getLabel();
            bean.mappings.add(mappingBean);
        }
    }
    if (widget instanceof Slider) {
        Slider sliderWidget = (Slider) widget;
        bean.sendFrequency = sliderWidget.getFrequency();
        bean.switchSupport = sliderWidget.isSwitchEnabled();
    }
    if (widget instanceof List) {
        List listWidget = (List) widget;
        bean.separator = listWidget.getSeparator();
    }
    if (widget instanceof Image || widget instanceof Video || widget instanceof Webview
            || widget instanceof Mapview) {

        if (widget instanceof Image) {
            Image imageWidget = (Image) widget;
            if (imageWidget.getRefresh() > 0) {
                bean.refresh = imageWidget.getRefresh();
            }
            bean.url = imageWidget.getUrl();
        } else if (widget instanceof Video) {
            Video videoWidget = (Video) widget;
            if (videoWidget.getEncoding() != null) {
                bean.encoding = videoWidget.getEncoding();
            }
            bean.url = videoWidget.getUrl();
        } else if (widget instanceof Webview) {
            Webview webViewWidget = (Webview) widget;
            bean.height = webViewWidget.getHeight();
            bean.url = webViewWidget.getUrl();
        } else if (widget instanceof Mapview) {
            Mapview mapViewWidget = (Mapview) widget;
            bean.height = mapViewWidget.getHeight();
        }

        String wId = itemUIRegistry.getWidgetId(widget);

        StringBuilder sbBaseUrl = new StringBuilder();
        sbBaseUrl.append(uri.getScheme()).append("://").append(uri.getHost());
        if (uri.getPort() >= 0 && uri.getPort() != 80) {
            sbBaseUrl.append(":").append(uri.getPort());
        }
        StringBuilder sb = new StringBuilder();
        sb.append("/proxy?");
        sb.append("sitemap=").append(sitemapName).append(".sitemap&");
        sb.append("widgetId=").append(wId);
        if (bean.url != null && bean.url.startsWith("/")) {
            try {
                sb.append("&").append("baseUrl=").append(URLEncoder.encode(sbBaseUrl.toString(), "UTF-8"));
            } catch (UnsupportedEncodingException ex) {
                throw new RuntimeException(ex.getMessage(), ex);
            }
        }
        if (uri.getFragment() != null) {
            sb.append("#" + uri.getFragment());
        }
        sbBaseUrl.append(sb.toString());
        bean.url = sbBaseUrl.toString();
    }
    if (widget instanceof Chart) {
        Chart chartWidget = (Chart) widget;
        bean.service = chartWidget.getService();
        bean.period = chartWidget.getPeriod();
        if (chartWidget.getRefresh() > 0) {
            bean.refresh = chartWidget.getRefresh();
        }
    }
    if (widget instanceof Setpoint) {
        Setpoint setpointWidget = (Setpoint) widget;
        bean.minValue = setpointWidget.getMinValue();
        bean.maxValue = setpointWidget.getMaxValue();
        bean.step = setpointWidget.getStep();
    }
    return bean;
}

From source file:com.zimbra.client.ZMailbox.java

public static String resolveUrl(String url, boolean isAdmin) throws ZClientException {
    try {/*w  ww  . j  ava2s.  c om*/
        URI uri = new URI(url);

        if (isAdmin && uri.getPort() == -1) {
            uri = new URI("https", uri.getUserInfo(), uri.getHost(), ADMIN_PORT, uri.getPath(), uri.getQuery(),
                    uri.getFragment());
            url = uri.toString();
        }

        String service = (uri.getPort() == ADMIN_PORT) ? AdminConstants.ADMIN_SERVICE_URI
                : AccountConstants.USER_SERVICE_URI;
        if (uri.getPath() == null || uri.getPath().length() <= 1) {
            if (url.charAt(url.length() - 1) == '/') {
                url = url.substring(0, url.length() - 1) + service;
            } else {
                url = url + service;
            }
        }
        return url;
    } catch (URISyntaxException e) {
        throw ZClientException.CLIENT_ERROR("invalid URL: " + url, e);
    }
}