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:com.lizardtech.expresszip.model.Job.java

public String getlog_URL() {
    String url = "";
    if (getRunState() == RunState.FinishedOK || getRunState() == RunState.Failed) {
        URL u = getUrl();
        String containerURL = u.getProtocol() + "://" + u.getAuthority();
        url = containerURL + "/exportdir/" + jobParams.getJobName() + "/" + getLogName();
    }//www . j av a2 s. co m
    return url;
}

From source file:com.lizardtech.expresszip.model.Job.java

private void emailUser() {
    ExportProps props = getExportProps();
    String email = props.getEmail();

    if (email == null || email.isEmpty() || email.equalsIgnoreCase(ExportProps.DefaultNotSupplied)) {
        logger.info("email not configured or address not given: not sending notification");
        return;/*from w w  w.  j a v a 2  s .c  o  m*/
    }

    logger.info("Sending email notification to: " + email);
    StringBuilder msgBody = new StringBuilder();
    String statuslink = getDL_URL();
    if (getRunState() == RunState.Failed) {
        URL u = getUrl();
        statuslink = u.getProtocol() + "://" + u.getAuthority() + "/ExpressZip";
    }
    msgBody.append("<p>Your ExpressZip request, Job \"");
    msgBody.append(props.getJobName());
    msgBody.append("\" completed processing at ");
    DateFormat fmttime = new SimpleDateFormat("HH:mm:ss");
    DateFormat fmtdate = new SimpleDateFormat("MM/dd/yyyy");
    Date rightnow = Calendar.getInstance().getTime();
    msgBody.append(fmttime.format(rightnow) + " on ");
    msgBody.append(fmtdate.format(rightnow));
    msgBody.append(".  You may download your data at:</p>");
    msgBody.append("<a href=\"" + statuslink + "\">" + statuslink + "</a>");

    BackgroundExecutor executor = new BackgroundExecutor.Factory().getBackgroundExecutor();
    executor.getMailServices().sendEmail(email, "ExpressZip@" + getUrl().getHost(),
            "Job " + props.getJobName() + " has finished processing", msgBody.toString(), "text/html");
}

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

/**
 * Computes the full URL based on a base url and a possibly relative link found
 * in the href param of an HTML anchor./*from w  ww  .  j av a 2  s.c  o m*/
 * @param baseUrl the base url from where the link was found
 * @param link the absolute or relative link
 * @return the string version of the full URL
 */
protected String computeFullUrl(URL baseUrl, String link) {
  if(link == null || link.length() == 0) {
    return null;
  }
  if(!link.startsWith("http")) {
    if(link.startsWith("/")) {
      link = baseUrl.getProtocol() + "://" + baseUrl.getAuthority() + link;
    } else {
      if(link.contains(":")) {
        return null; // Skip non-relative URLs
      }
      String path = baseUrl.getPath();
      if(!path.endsWith("/")) {
        int sep = path.lastIndexOf("/");
        String file = path.substring(sep+1);
        if(file.contains(".") || file.contains("?"))
          path = path.substring(0,sep);
      }
      link = baseUrl.getProtocol() + "://" + baseUrl.getAuthority() + path + "/" + link;
    }
  }
  link = normalizeUrlEnding(link);
  String l = link.toLowerCase(Locale.ROOT);
  // Simple brute force skip images
  if(l.endsWith(".jpg") || l.endsWith(".jpeg") || l.endsWith(".png") || l.endsWith(".gif")) {
    return null; // Skip images
  }
  return link;
}

From source file:com.xpn.xwiki.user.impl.xwiki.XWikiAuthServiceImpl.java

/**
 * The authentication library we are using (SecurityFilter) requires that its URLs do not contain the context path,
 * in order to be usable with <tt>RequestDispatcher.forward</tt>. Since our URL factory include the context path in
 * the generated URLs, we use this method to remove (if needed) the context path.
 * /* ww  w. j  a v  a 2 s . c o m*/
 * @param url The URL to process.
 * @param context The ubiquitous XWiki request context.
 * @return A <code>String</code> representation of the contextpath-free URL.
 */
protected String stripContextPathFromURL(URL url, XWikiContext context) {
    String contextPath = context.getWiki().getWebAppPath(context);
    // XWiki uses contextPath in the wrong way, putting a / at the end, and not at the start. Fix this here.
    if (contextPath.endsWith("/") && !contextPath.startsWith("/")) {
        contextPath = "/" + StringUtils.chop(contextPath);
    }

    // URLFactory.getURL applies Util.escapeURL, which might convert the contextPath into an %NN escaped string.
    // Apply the same escape method to compensate this.
    contextPath = Util.escapeURL(contextPath);

    String urlPrefix = url.getProtocol() + "://" + url.getAuthority() + contextPath;
    return StringUtils.removeStart(url.toExternalForm(), urlPrefix);
}

From source file:com.ehsy.solr.util.SimplePostTool.java

/**
 * Computes the full URL based on a base url and a possibly relative link found
 * in the href param of an HTML anchor.//  w  ww  .  j  av a  2s .c  o  m
 * @param baseUrl the base url from where the link was found
 * @param link the absolute or relative link
 * @return the string version of the full URL
 */
protected String computeFullUrl(URL baseUrl, String link) {
    if (link == null || link.length() == 0) {
        return null;
    }
    if (!link.startsWith("http")) {
        if (link.startsWith("/")) {
            link = baseUrl.getProtocol() + "://" + baseUrl.getAuthority() + link;
        } else {
            if (link.contains(":")) {
                return null; // Skip non-relative URLs
            }
            String path = baseUrl.getPath();
            if (!path.endsWith("/")) {
                int sep = path.lastIndexOf("/");
                String file = path.substring(sep + 1);
                if (file.contains(".") || file.contains("?"))
                    path = path.substring(0, sep);
            }
            link = baseUrl.getProtocol() + "://" + baseUrl.getAuthority() + path + "/" + link;
        }
    }
    link = normalizeUrlEnding(link);
    String l = link.toLowerCase(Locale.ROOT);
    // Simple brute force skip images
    if (l.endsWith(".jpg") || l.endsWith(".jpeg") || l.endsWith(".png") || l.endsWith(".gif")) {
        return null; // Skip images
    }
    return link;
}

From source file:com.stoutner.privacybrowser.MainWebViewActivity.java

private void loadUrlFromTextBox() throws UnsupportedEncodingException {
    // Get the text from urlTextBox and convert it to a string.
    String unformattedUrlString = urlTextBox.getText().toString();
    URL unformattedUrl = null;
    Uri.Builder formattedUri = new Uri.Builder();

    // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
    if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
        // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
        if (!unformattedUrlString.startsWith("http")) {
            unformattedUrlString = "http://" + unformattedUrlString;
        }/* w  w  w  .ja va2 s . co  m*/

        // Convert unformattedUrlString to a URL, then to a URI, and then back to a string, which sanitizes the input and adds in any missing components.
        try {
            unformattedUrl = new URL(unformattedUrlString);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
        final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
        final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
        final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
        final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
        final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;

        formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
        formattedUrlString = formattedUri.build().toString();
    } else {
        // Sanitize the search input and convert it to a DuckDuckGo search.
        final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");

        // Use the correct search URL based on javaScriptEnabled.
        if (javaScriptEnabled) {
            formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
        } else { // JavaScript is disabled.
            formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
        }
    }

    mainWebView.loadUrl(formattedUrlString);

    // Hides the keyboard so we can see the webpage.
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(
            Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
}

From source file:com.alibaba.citrus.maven.eclipse.base.eclipse.EclipsePlugin.java

private void writeAdditionalConfig() throws MojoExecutionException {
    if (additionalConfig != null) {
        for (int j = 0; j < additionalConfig.length; j++) {
            EclipseConfigFile file = additionalConfig[j];
            File projectRelativeFile = new File(eclipseProjectDir, file.getName());
            if (projectRelativeFile.isDirectory()) {
                // just ignore?
                getLog().warn(Messages.getString("EclipsePlugin.foundadir", //$NON-NLS-1$
                        projectRelativeFile.getAbsolutePath()));
            }/*from   w  ww. j av  a  2 s . co m*/

            try {
                projectRelativeFile.getParentFile().mkdirs();
                if (file.getContent() == null) {
                    if (file.getLocation() != null) {
                        InputStream inStream = locator.getResourceAsInputStream(file.getLocation());
                        OutputStream outStream = new FileOutputStream(projectRelativeFile);
                        try {
                            IOUtil.copy(inStream, outStream);
                        } finally {
                            IOUtil.close(inStream);
                            IOUtil.close(outStream);
                        }
                    } else {
                        URL url = file.getURL();
                        String endPointUrl = url.getProtocol() + "://" + url.getAuthority();
                        // Repository Id should be ignored by Wagon ...
                        Repository repository = new Repository("additonal-configs", endPointUrl);
                        Wagon wagon = wagonManager.getWagon(repository);
                        ;
                        if (logger.isDebugEnabled()) {
                            Debug debug = new Debug();
                            wagon.addSessionListener(debug);
                            wagon.addTransferListener(debug);
                        }
                        wagon.setTimeout(1000);
                        Settings settings = mavenSettingsBuilder.buildSettings();
                        ProxyInfo proxyInfo = null;
                        if (settings != null && settings.getActiveProxy() != null) {
                            Proxy settingsProxy = settings.getActiveProxy();

                            proxyInfo = new ProxyInfo();
                            proxyInfo.setHost(settingsProxy.getHost());
                            proxyInfo.setType(settingsProxy.getProtocol());
                            proxyInfo.setPort(settingsProxy.getPort());
                            proxyInfo.setNonProxyHosts(settingsProxy.getNonProxyHosts());
                            proxyInfo.setUserName(settingsProxy.getUsername());
                            proxyInfo.setPassword(settingsProxy.getPassword());
                        }

                        if (proxyInfo != null) {
                            wagon.connect(repository, wagonManager.getAuthenticationInfo(repository.getId()),
                                    proxyInfo);
                        } else {
                            wagon.connect(repository, wagonManager.getAuthenticationInfo(repository.getId()));
                        }

                        wagon.get(url.getPath(), projectRelativeFile);
                    }
                } else {
                    FileUtils.fileWrite(projectRelativeFile.getAbsolutePath(), file.getContent());
                }
            } catch (WagonException e) {
                throw new MojoExecutionException(Messages.getString("EclipsePlugin.remoteexception", //$NON-NLS-1$
                        new Object[] { file.getURL(), e.getMessage() }));
            } catch (IOException e) {
                throw new MojoExecutionException(Messages.getString("EclipsePlugin.cantwritetofile", //$NON-NLS-1$
                        projectRelativeFile.getAbsolutePath()));
            } catch (ResourceNotFoundException e) {
                throw new MojoExecutionException(Messages.getString("EclipsePlugin.cantfindresource", //$NON-NLS-1$
                        file.getLocation()));
            } catch (XmlPullParserException e) {
                throw new MojoExecutionException(Messages.getString("EclipsePlugin.settingsxmlfailure",
                        //$NON-NLS-1$
                        e.getMessage()));
            }
        }
    }
}

From source file:org.opentravel.schemacompiler.repository.RepositoryManager.java

/**
 * @see org.opentravel.schemacompiler.repository.Repository#createRootNamespace(java.lang.String)
 *///from   w  ww .j  a  v  a 2s.  c o m
@Override
public void createRootNamespace(String rootNamespace) throws RepositoryException {
    String rootNS = RepositoryNamespaceUtils.normalizeUri(rootNamespace);
    boolean success = false;
    try {
        fileManager.startChangeSet();
        File rootNSFolder = fileManager.getNamespaceFolder(rootNS, null);
        File nsidFile = new File(rootNSFolder, RepositoryFileManager.NAMESPACE_ID_FILENAME);

        // Validation Check - Make sure the namespace follows a proper URL format
        try {
            URL nsUrl = new URL(rootNamespace);

            if ((nsUrl.getProtocol() == null) || (nsUrl.getAuthority() == null)) {
                throw new MalformedURLException(); // URLs without protocols or authorities are
                                                   // not valid for the repository
            }
            if (rootNamespace.indexOf('?') >= 0) {
                throw new RepositoryException("Query strings are not allowed on root namespace URIs.");
            }
        } catch (MalformedURLException e) {
            throw new RepositoryException("The root namespace does not conform to the required URI format.");
        }

        // Validation Check - Look for a file conflict with an existing namespace
        if (nsidFile.exists()) {
            throw new RepositoryException(
                    "The root namespace cannot be created because it conflicts with an existing one.");
        }

        // Validation Check - Check to see if the new root is a parent or child of an existing
        // root namespace
        String repositoryBaseFolder = fileManager.getRepositoryLocation().getAbsolutePath();
        List<String> existingRootNSFolderPaths = new ArrayList<String>();
        String rootNSTestPath = rootNSFolder.getAbsolutePath();

        if (!rootNSTestPath.endsWith("/")) {
            rootNSTestPath += "/";
        }

        for (String existingRootNS : listRootNamespaces()) {
            File existingRootNSFolder = fileManager.getNamespaceFolder(existingRootNS, null);

            if (rootNSTestPath.startsWith(existingRootNSFolder.getAbsolutePath())) {
                throw new RepositoryException(
                        "The root namespace cannot be created because it conflicts with an existing one.");
            }
            while ((existingRootNSFolder != null)
                    && !repositoryBaseFolder.equals(existingRootNSFolder.getAbsolutePath())) {
                existingRootNSFolderPaths.add(existingRootNSFolder.getAbsolutePath());
                existingRootNSFolder = existingRootNSFolder.getParentFile();
            }
        }
        if (existingRootNSFolderPaths.contains(rootNSFolder.getAbsolutePath())) {
            throw new RepositoryException(
                    "The root namespace cannot be created because it conflicts with an existing one.");
        }

        // Create the new root namespace if all of the validation checks passed
        fileManager.createNamespaceIdFiles(rootNS);
        rootNamespaces.add(rootNS);
        saveLocalRepositoryMetadata();
        success = true;

        log.info("Successfully created root namespace: " + rootNS + " by " + fileManager.getCurrentUserId());

    } finally {
        // Commit or roll back the changes based on the result of the operation
        if (success) {
            fileManager.commitChangeSet();
        } else {
            try {
                fileManager.rollbackChangeSet();
            } catch (Throwable t) {
                log.error("Error rolling back the current change set.", t);
            }
        }
    }
}

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

/**
 * ImplicitFlow???.// w  w w  .j  a  v  a  2  s  .  com
 * @param clientId
 * @param redirectUri
 * @param baseUri
 */
private void checkImplicitParam(String clientId, String redirectUri, URI baseUri) {
    if (redirectUri == null || clientId == null) {
        // TODO ?null??????
        throw DcCoreAuthnException.INVALID_TARGET;
    }

    URL objClientId = null;
    URL objRedirectUri = null;
    try {
        objClientId = new URL(clientId);
    } catch (MalformedURLException e) {
        throw DcCoreException.Auth.REQUEST_PARAM_CLIENTID_INVALID;
    }
    try {
        objRedirectUri = new URL(redirectUri);
    } catch (MalformedURLException e) {
        throw DcCoreException.Auth.REQUEST_PARAM_REDIRECT_INVALID;
    }

    if ((redirectUri.contains("\n") || redirectUri.contains("\r"))) {
        throw DcCoreException.Auth.REQUEST_PARAM_REDIRECT_INVALID;
    }
    if ((clientId.contains("\n") || clientId.contains("\r"))) {
        throw DcCoreException.Auth.REQUEST_PARAM_CLIENTID_INVALID;
    }

    // baseurl???
    String bPath = baseUri.getPath();

    // client_id?redirect_uri??baseUri??
    String cPath = objClientId.getPath().substring(bPath.length());
    String rPath = objRedirectUri.getPath().substring(bPath.length());

    // client_id?redirect_uri?/?
    String[] cPaths = StringUtils.split(cPath, "/");
    String[] rPaths = StringUtils.split(rPath, "/");

    // client_id?redirect_uri???????
    // ?URL???
    if (!objClientId.getAuthority().equals(objRedirectUri.getAuthority()) || !cPaths[0].equals(rPaths[0])) {
        throw DcCoreException.Auth.REQUEST_PARAM_REDIRECT_INVALID;
    }

    // client_id???Cell???????????
    if (cPaths[0].equals(this.cell.getName())) {
        throw DcCoreException.Auth.REQUEST_PARAM_CLIENTID_INVALID;
    }

}

From source file:io.personium.core.rs.cell.AuthzEndPointResource.java

/**
 * ImplicitFlow???.//  w w w  .  j  av a2  s . c o  m
 * @param clientId
 * @param redirectUri
 * @param baseUri
 */
private void checkImplicitParam(String clientId, String redirectUri, URI baseUri) {
    if (redirectUri == null || clientId == null) {
        // TODO ?null??????
        throw PersoniumCoreAuthnException.INVALID_TARGET;
    }

    URL objClientId = null;
    URL objRedirectUri = null;
    try {
        objClientId = new URL(clientId);
    } catch (MalformedURLException e) {
        throw PersoniumCoreException.Auth.REQUEST_PARAM_CLIENTID_INVALID;
    }
    try {
        objRedirectUri = new URL(redirectUri);
    } catch (MalformedURLException e) {
        throw PersoniumCoreException.Auth.REQUEST_PARAM_REDIRECT_INVALID;
    }

    if (redirectUri.contains("\n") || redirectUri.contains("\r")) {
        throw PersoniumCoreException.Auth.REQUEST_PARAM_REDIRECT_INVALID;
    }
    if (clientId.contains("\n") || clientId.contains("\r")) {
        throw PersoniumCoreException.Auth.REQUEST_PARAM_CLIENTID_INVALID;
    }

    // baseurl???
    String bPath = baseUri.getPath();

    // client_id?redirect_uri??baseUri??
    String cPath = objClientId.getPath().substring(bPath.length());
    String rPath = objRedirectUri.getPath().substring(bPath.length());

    // client_id?redirect_uri?/?
    String[] cPaths = StringUtils.split(cPath, "/");
    String[] rPaths = StringUtils.split(rPath, "/");

    // client_id?redirect_uri???????
    // ?URL???
    if (!objClientId.getAuthority().equals(objRedirectUri.getAuthority()) || !cPaths[0].equals(rPaths[0])) {
        throw PersoniumCoreException.Auth.REQUEST_PARAM_REDIRECT_INVALID;
    }

    // client_id???Cell???????????
    if (cPaths[0].equals(this.cell.getName())) {
        throw PersoniumCoreException.Auth.REQUEST_PARAM_CLIENTID_INVALID;
    }

}