Example usage for java.net URL getAuthority

List of usage examples for java.net URL getAuthority

Introduction

In this page you can find the example usage for java.net URL getAuthority.

Prototype

public String getAuthority() 

Source Link

Document

Gets the authority part of this URL .

Usage

From source file:org.exoplatform.wiki.commons.Utils.java

public static WikiContext createWikiContext(UIWikiPortlet wikiPortlet) throws Exception {
    PortalRequestContext portalRequestContext = Util.getPortalRequestContext();
    WikiMode currentMode = wikiPortlet.getWikiMode();
    List<WikiMode> editModes = Arrays.asList(new WikiMode[] { WikiMode.EDITPAGE, WikiMode.ADDPAGE,
            WikiMode.EDITTEMPLATE, WikiMode.ADDTEMPLATE });
    UIPortal uiPortal = Util.getUIPortal();
    String portalURI = portalRequestContext.getPortalURI();
    URL requestURL = new URL(portalRequestContext.getRequest().getRequestURL().toString());
    String domainURL = requestURL.getProtocol() + "://" + requestURL.getAuthority();
    String portalURL = domainURL + portalURI;
    String pageNodeSelected = uiPortal.getSelectedUserNode().getURI();
    String treeRestURL = getCurrentRestURL().concat("/wiki/tree/children/");

    WikiContext wikiContext = new WikiContext();
    wikiContext.setPortalURL(portalURL);
    wikiContext.setTreeRestURI(treeRestURL);
    wikiContext.setRestURI(getCurrentRestURL());
    wikiContext.setRedirectURI(wikiPortlet.getRedirectURL());
    wikiContext.setPortletURI(pageNodeSelected);
    WikiPageParams params = Utils.getCurrentWikiPageParams();
    wikiContext.setType(params.getType());
    wikiContext.setOwner(params.getOwner());
    if (editModes.contains(currentMode)) {
        wikiContext.setSyntax(getDefaultSyntax());
    } else {/* www. ja v  a  2s .c  o  m*/
        WikiService service = (WikiService) PortalContainer.getComponent(WikiService.class);
        Page currentPage = service.getPageById(params.getType(), params.getOwner(), params.getPageId());
        if (currentPage != null) {
            wikiContext.setSyntax(currentPage.getSyntax());
        }
    }
    if (wikiPortlet.getWikiMode() == WikiMode.ADDPAGE) {
        wikiContext.setPageId(org.exoplatform.wiki.utils.Utils.getPageNameForAddingPage());
    } else {
        wikiContext.setPageId(params.getPageId());
    }
    wikiContext.setBaseUrl(getBaseUrl());
    return wikiContext;
}

From source file:com.mber.client.MberClient.java

public static String baseUrlWithPath(final String url, String path) throws MalformedURLException {
    if (!path.endsWith("/")) {
        path += "/";
    }/*from w ww .  j  av  a 2s  .  co  m*/
    URL base = new URL(url);
    URL baseUrl = new URL(base.getProtocol() + "://" + base.getAuthority());
    URL resolvedUrl = new URL(baseUrl, path);
    return resolvedUrl.toString();
}

From source file:com.eucalyptus.imaging.manifest.DownloadManifestFactory.java

/**
 * Generates download manifest based on bundle manifest and puts in into
 * system owned bucket//from   ww  w . j  a v a2s  . c  om
 * 
 * @param baseManifest
 *          the base manifest
 * @param keyToUse
 *          public key that used for encryption
 * @param manifestName
 *          name for generated manifest file
 * @param expirationHours
 *          expiration policy in hours for pre-signed URLs
 * @param urlForNc
 *          indicates if urs are constructed for NC use
 * @return pre-signed URL that can be used to download generated manifest
 * @throws DownloadManifestException
 */
public static String generateDownloadManifest(final ImageManifestFile baseManifest, final PublicKey keyToUse,
        final String manifestName, int expirationHours, boolean urlForNc) throws DownloadManifestException {
    EucaS3Client s3Client = null;
    try {
        try {
            s3Client = s3ClientsPool.borrowObject();
        } catch (Exception ex) {
            throw new DownloadManifestException("Can't borrow s3Client from the pool");
        }
        // prepare to do pre-signed urls
        if (!urlForNc)
            s3Client.refreshEndpoint(true);
        else
            s3Client.refreshEndpoint();

        Date expiration = new Date();
        long msec = expiration.getTime() + 1000 * 60 * 60 * expirationHours;
        expiration.setTime(msec);

        // check if download-manifest already exists
        if (objectExist(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName)) {
            LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName)
                    + "' is already created and has not expired. Skipping creation");
            URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME,
                    DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET);
            return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(),
                    s.getQuery());
        } else {
            LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName) + "' does not exist");
        }

        UrlValidator urlValidator = new UrlValidator();

        final String manifest = baseManifest.getManifest();
        if (manifest == null) {
            throw new DownloadManifestException("Can't generate download manifest from null base manifest");
        }
        final Document inputSource;
        final XPath xpath;
        Function<String, String> xpathHelper;
        DocumentBuilder builder = XMLParser.getDocBuilder();
        inputSource = builder.parse(new ByteArrayInputStream(manifest.getBytes()));
        if (!"manifest".equals(inputSource.getDocumentElement().getNodeName())) {
            LOG.error("Expected image manifest. Got " + nodeToString(inputSource, false));
            throw new InvalidBaseManifestException("Base manifest does not have manifest element");
        }

        StringBuilder signatureSrc = new StringBuilder();
        Document manifestDoc = builder.newDocument();
        Element root = (Element) manifestDoc.createElement("manifest");
        manifestDoc.appendChild(root);
        Element el = manifestDoc.createElement("version");
        el.appendChild(manifestDoc.createTextNode("2014-01-14"));
        signatureSrc.append(nodeToString(el, false));
        root.appendChild(el);
        el = manifestDoc.createElement("file-format");
        el.appendChild(manifestDoc.createTextNode(baseManifest.getManifestType().getFileType().toString()));
        root.appendChild(el);
        signatureSrc.append(nodeToString(el, false));

        xpath = XPathFactory.newInstance().newXPath();
        xpathHelper = new Function<String, String>() {
            @Override
            public String apply(String input) {
                try {
                    return (String) xpath.evaluate(input, inputSource, XPathConstants.STRING);
                } catch (XPathExpressionException ex) {
                    return null;
                }
            }
        };

        // extract keys
        // TODO: move this?
        if (baseManifest.getManifestType().getFileType() == FileType.BUNDLE) {
            String encryptedKey = xpathHelper.apply("/manifest/image/ec2_encrypted_key");
            String encryptedIV = xpathHelper.apply("/manifest/image/ec2_encrypted_iv");
            String size = xpathHelper.apply("/manifest/image/size");
            EncryptedKey encryptKey = reEncryptKey(new EncryptedKey(encryptedKey, encryptedIV), keyToUse);
            el = manifestDoc.createElement("bundle");
            Element key = manifestDoc.createElement("encrypted-key");
            key.appendChild(manifestDoc.createTextNode(encryptKey.getKey()));
            Element iv = manifestDoc.createElement("encrypted-iv");
            iv.appendChild(manifestDoc.createTextNode(encryptKey.getIV()));
            el.appendChild(key);
            el.appendChild(iv);
            Element sizeEl = manifestDoc.createElement("unbundled-size");
            sizeEl.appendChild(manifestDoc.createTextNode(size));
            el.appendChild(sizeEl);
            root.appendChild(el);
            signatureSrc.append(nodeToString(el, false));
        }

        el = manifestDoc.createElement("image");
        String bundleSize = xpathHelper.apply(baseManifest.getManifestType().getSizePath());
        if (bundleSize == null) {
            throw new InvalidBaseManifestException("Base manifest does not have size element");
        }
        Element size = manifestDoc.createElement("size");
        size.appendChild(manifestDoc.createTextNode(bundleSize));
        el.appendChild(size);

        Element partsEl = manifestDoc.createElement("parts");
        el.appendChild(partsEl);
        // parts
        NodeList parts = (NodeList) xpath.evaluate(baseManifest.getManifestType().getPartsPath(), inputSource,
                XPathConstants.NODESET);
        if (parts == null) {
            throw new InvalidBaseManifestException("Base manifest does not have parts");
        }

        for (int i = 0; i < parts.getLength(); i++) {
            Node part = parts.item(i);
            String partIndex = part.getAttributes().getNamedItem("index").getNodeValue();
            String partKey = ((Node) xpath.evaluate(baseManifest.getManifestType().getPartUrlElement(), part,
                    XPathConstants.NODE)).getTextContent();
            String partDownloadUrl = partKey;
            if (baseManifest.getManifestType().signPartUrl()) {
                GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                        baseManifest.getBaseBucket(), partKey, HttpMethod.GET);
                generatePresignedUrlRequest.setExpiration(expiration);
                URL s = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
                partDownloadUrl = s.toString();
            } else {
                // validate url per EUCA-9144
                if (!urlValidator.isEucalyptusUrl(partDownloadUrl))
                    throw new DownloadManifestException(
                            "Some parts in the manifest are not stored in the OS. Its location is outside Eucalyptus:"
                                    + partDownloadUrl);
            }
            Node digestNode = null;
            if (baseManifest.getManifestType().getDigestElement() != null)
                digestNode = ((Node) xpath.evaluate(baseManifest.getManifestType().getDigestElement(), part,
                        XPathConstants.NODE));
            Element aPart = manifestDoc.createElement("part");
            Element getUrl = manifestDoc.createElement("get-url");
            getUrl.appendChild(manifestDoc.createTextNode(partDownloadUrl));
            aPart.setAttribute("index", partIndex);
            aPart.appendChild(getUrl);
            if (digestNode != null) {
                NamedNodeMap nm = digestNode.getAttributes();
                if (nm == null)
                    throw new DownloadManifestException(
                            "Some parts in manifest don't have digest's verification algorithm");
                Element digest = manifestDoc.createElement("digest");
                digest.setAttribute("algorithm", nm.getNamedItem("algorithm").getTextContent());
                digest.appendChild(manifestDoc.createTextNode(digestNode.getTextContent()));
                aPart.appendChild(digest);
            }
            partsEl.appendChild(aPart);
        }
        root.appendChild(el);
        signatureSrc.append(nodeToString(el, false));
        String signatureData = signatureSrc.toString();
        Element signature = manifestDoc.createElement("signature");
        signature.setAttribute("algorithm", "RSA-SHA256");
        signature.appendChild(manifestDoc
                .createTextNode(Signatures.SHA256withRSA.trySign(Eucalyptus.class, signatureData.getBytes())));
        root.appendChild(signature);
        String downloadManifest = nodeToString(manifestDoc, true);
        // TODO: move this ?
        createManifestsBucketIfNeeded(s3Client);
        putManifestData(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName,
                downloadManifest, expiration);
        // generate pre-sign url for download manifest
        URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME,
                DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET);
        return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(),
                s.getQuery());
    } catch (Exception ex) {
        LOG.error("Got an error", ex);
        throw new DownloadManifestException("Can't generate download manifest");
    } finally {
        if (s3Client != null)
            try {
                s3ClientsPool.returnObject(s3Client);
            } catch (Exception e) {
                // sad, but let's not break instances run
                LOG.warn("Could not return s3Client to the pool");
            }
    }
}

From source file:org.openqa.selenium.server.browserlaunchers.LauncherUtils.java

/**
 * Strips the specified URL so it only includes a protocal, hostname and
 * port//from  w  w w  . ja  v  a 2s.c  o m
 * 
 * @throws MalformedURLException
 */
public static String stripStartURL(String url) {
    try {
        URL u = new URL(url);
        String path = u.getPath();
        if (path != null && !"".equals(path) && !path.endsWith("/")) {
            log.warn("It looks like your baseUrl (" + url
                    + ") is pointing to a file, not a directory (it doesn't end with a /).  We're going to have to strip off the last part of the pathname.");
        }
        return u.getProtocol() + "://" + u.getAuthority();
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.fujitsu.dc.test.unit.core.UrlUtils.java

/**
 * Host?getter./*from   w ww  . j  av  a 2  s  .  c o m*/
 * @return baseUrl
 */
public static String getHost() {
    URL url;
    try {
        url = new URL(UrlUtils.baseUrl);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    StringBuilder host = new StringBuilder();
    host.append(url.getAuthority());
    return host.toString();
}

From source file:com.odoko.solrcli.actions.CrawlPostAction.java

/**
 * Appends to the path of the URL//from ww  w.  j  a  v a2  s  .c  o m
 * @param url the URL
 * @param append the path to append
 * @return the final URL version 
 */
protected static URL appendUrlPath(URL url, String append) throws MalformedURLException {
  return new URL(url.getProtocol() + "://" + url.getAuthority() + url.getPath() + append + (url.getQuery() != null ? "?"+url.getQuery() : ""));
}

From source file:opendap.threddsHandler.ThreddsCatalogUtil.java

public static String getUrlInfo(URL url) throws InterruptedException {
    String info = "URL:\n";

    info += "    getHost():         " + url.getHost() + "\n";
    info += "    getAuthority():    " + url.getAuthority() + "\n";
    info += "    getFile():         " + url.getFile() + "\n";
    info += "    getSystemPath():         " + url.getPath() + "\n";
    info += "    getDefaultPort():  " + url.getDefaultPort() + "\n";
    info += "    getPort():         " + url.getPort() + "\n";
    info += "    getProtocol():     " + url.getProtocol() + "\n";
    info += "    getQuery():        " + url.getQuery() + "\n";
    info += "    getRef():          " + url.getRef() + "\n";
    info += "    getUserInfo():     " + url.getUserInfo() + "\n";

    return info;/*w ww  .j a v  a  2 s  .  c  o  m*/
}

From source file:com.gargoylesoftware.htmlunit.util.UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified reference.
 * @param u the URL on which to base the returned URL
 * @param newRef the new reference to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified reference
 * @throws MalformedURLException if there is a problem creating the new URL
 *//*ww w . j  a v a 2s  .  c om*/
public static URL getUrlWithNewRef(final URL u, final String newRef) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getAuthority(), u.getPath(), newRef, u.getQuery());
}

From source file:com.gargoylesoftware.htmlunit.util.UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified protocol.
 * @param u the URL on which to base the returned URL
 * @param newProtocol the new protocol to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified protocol
 * @throws MalformedURLException if there is a problem creating the new URL
 *///from   w w  w.  j a  v  a2  s  .c  o  m
public static URL getUrlWithNewProtocol(final URL u, final String newProtocol) throws MalformedURLException {
    return createNewUrl(newProtocol, u.getAuthority(), u.getPath(), u.getRef(), u.getQuery());
}

From source file:com.gargoylesoftware.htmlunit.util.UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified path.
 * @param u the URL on which to base the returned URL
 * @param newPath the new path to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified path
 * @throws MalformedURLException if there is a problem creating the new URL
 *//*w ww .j a  v a2  s. co  m*/
public static URL getUrlWithNewPath(final URL u, final String newPath) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getAuthority(), newPath, u.getRef(), u.getQuery());
}