Example usage for java.net URL toExternalForm

List of usage examples for java.net URL toExternalForm

Introduction

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

Prototype

public String toExternalForm() 

Source Link

Document

Constructs a string representation of this URL .

Usage

From source file:com.dtolabs.rundeck.core.execution.workflow.steps.node.impl.ScriptURLNodeStepExecutor.java

public NodeStepResult executeNodeStep(StepExecutionContext context, NodeStepExecutionItem item, INodeEntry node)
        throws NodeStepException {
    if (!cacheDir.isDirectory() && !cacheDir.mkdirs()) {
        throw new RuntimeException("Unable to create cachedir: " + cacheDir.getAbsolutePath());
    }/*  w w w. ja va  2s . c o  m*/
    final ScriptURLCommandExecutionItem script = (ScriptURLCommandExecutionItem) item;
    final ExecutionService executionService = framework.getExecutionService();
    //create node context for node and substitute data references in command
    final Map<String, Map<String, String>> nodeDataContext = DataContextUtils.addContext("node",
            DataContextUtils.nodeData(node), context.getDataContext());

    final String finalUrl = expandUrlString(script.getURLString(), nodeDataContext);
    final URL url;
    try {
        url = new URL(finalUrl);
    } catch (MalformedURLException e) {
        throw new NodeStepException(e, StepFailureReason.ConfigurationFailure, node.getNodename());
    }
    if (null != context.getExecutionListener()) {
        context.getExecutionListener().log(4, "Requesting URL: " + url.toExternalForm());
    }

    String cleanUrl = url.toExternalForm().replaceAll("^(https?://)([^:@/]+):[^@/]*@", "$1$2:****@");
    String tempFileName = hashURL(url.toExternalForm()) + ".temp";
    File destinationTempFile = new File(cacheDir, tempFileName);
    File destinationCacheData = new File(cacheDir, tempFileName + ".cache.properties");

    //update from URL if necessary
    final URLFileUpdaterBuilder urlFileUpdaterBuilder = new URLFileUpdaterBuilder().setUrl(url)
            .setAcceptHeader("*/*").setTimeout(DEFAULT_TIMEOUT);
    if (USE_CACHE) {
        urlFileUpdaterBuilder.setCacheMetadataFile(destinationCacheData).setCachedContent(destinationTempFile)
                .setUseCaching(true);
    }
    final URLFileUpdater updater = urlFileUpdaterBuilder.createURLFileUpdater();
    try {
        if (null != interaction) {
            //allow mock
            updater.setInteraction(interaction);
        }
        UpdateUtils.update(updater, destinationTempFile);

        logger.debug("Updated nodes resources file: " + destinationTempFile);
    } catch (UpdateUtils.UpdateException e) {
        if (!destinationTempFile.isFile() || destinationTempFile.length() < 1) {
            throw new NodeStepException("Error requesting URL Script: " + cleanUrl + ": " + e.getMessage(), e,
                    Reason.URLDownloadFailure, node.getNodename());
        } else {
            logger.error("Error requesting URL script: " + cleanUrl + ": " + e.getMessage(), e);
        }
    }

    final String filepath; //result file path
    try {
        filepath = executionService.fileCopyFile(context, destinationTempFile, node);
    } catch (FileCopierException e) {
        throw new NodeStepException(e.getMessage(), e, StepFailureReason.IOFailure, node.getNodename());
    }

    /**
     * TODO: Avoid this horrific hack. Discover how to get SCP task to preserve the execute bit.
     */
    if (!"windows".equalsIgnoreCase(node.getOsFamily())) {
        //perform chmod+x for the file

        final NodeExecutorResult nodeExecutorResult = framework.getExecutionService().executeCommand(context,
                new String[] { "chmod", "+x", filepath }, node);
        if (!nodeExecutorResult.isSuccess()) {
            return nodeExecutorResult;
        }
    }

    final String[] args = script.getArgs();
    final String scriptInterpreter = script.getScriptInterpreter();
    final boolean interpreterargsquoted = script.getInterpreterArgsQuoted();

    //build arg list to execute the script
    ExecArgList scriptArgList = ScriptExecUtil.createScriptArgList(filepath, null, args, scriptInterpreter,
            interpreterargsquoted);

    return framework.getExecutionService().executeCommand(context, scriptArgList, node);
    //TODO: remove remote temp file after exec?
}

From source file:org.eclipse.ebr.maven.AboutFilesUtil.java

private void appendAndDownloadLicenseInfo(final StrBuilder text, final File downloadDir,
        final Artifact artifact, final List<License> licenses) throws MojoExecutionException {
    boolean first = true;
    for (final Iterator<License> stream = licenses.iterator(); stream.hasNext();) {
        final License license = stream.next();
        if (!first && !stream.hasNext()) {
            text.append(" and ");
        } else if (!first && stream.hasNext()) {
            text.append(", ");
        } else {//from w  ww  . jav a 2  s. com
            first = false;
        }
        final String localLicenseFile = getLocalLicenseFile(downloadDir, license);
        final String url = license.getUrl();
        boolean wroteUrl = false;
        String licenseFileName = null;
        if (null != localLicenseFile) {
            // prefer configured local if available
            getLog().info(
                    format("Using local license file (%s) for '%s'.", localLicenseFile, license.getName()));
            licenseFileName = localLicenseFile;
        } else if (isPotentialWebUrl(url)) {
            // try download if we have a web url
            try {
                final URL licenseUrl = toUrl(url); // parse as url to avoid surprises
                text.append("<a href=\"").append(licenseUrl.toExternalForm()).append("\" target=\"_blank\">");
                wroteUrl = true;
                try {
                    getLog().info(format("Downloading license '%s' (%s).", license.getName(),
                            licenseUrl.toExternalForm()));
                    licenseFileName = downloadLicenseFile(downloadDir, license, licenseUrl);
                    getLog().info(format("  -> %s.", licenseFileName));
                } catch (final IOException e) {
                    licenseFileName = null;
                    getLog().debug(e);
                    getLog().warn(format(
                            "Unable to download license file from '%s'. Please add manually to recipe project. %s",
                            licenseUrl.toExternalForm(), e.getMessage()));
                }

            } catch (final MalformedURLException e) {
                getLog().debug(e);
                getLog().warn(
                        format("Invalid license url '%s' in artifact pom '%s'.", url, artifact.getFile()));
            }
        }
        text.append(escapeHtml4(license.getName()));
        if (wroteUrl) {
            text.append("</a>");
        }
        if (licenseFileName != null) {
            text.append(" (<a href=\"").append(licenseFileName).append("\" target=\"_blank\">")
                    .append(FilenameUtils.getName(licenseFileName)).append("</a>)");
        }
    }
}

From source file:com.adaptris.util.text.xml.Resolver.java

/**
 * @see URIResolver#resolve(java.lang.String, java.lang.String)
 *///from   w w w  . ja v  a 2s. c o m
@Override
public Source resolve(String href, String base) throws TransformerException {
    debugLog("Resolving [{}][{}]", href, base);
    StreamSource result = null;
    try {
        URL myUrl = null;
        try {
            myUrl = new URL(href);
        } catch (Exception ex) {
            // Indicates that the URL was probably relative and therefore Malformed
            int end = base.lastIndexOf('/');
            String url = base.substring(0, end + 1);
            myUrl = new URL(url + href);
        }
        StreamSource ret = new StreamSource(retrieveAndCache(new URLString(myUrl)), myUrl.toExternalForm());
        result = ret;
    } catch (Exception e) {
        debugLog("Couldn't handle [{}][{}], fallback to default parser behaviour", href, base);
        result = null;
    }
    return result;
}

From source file:org.eclipse.ebr.maven.AboutFilesUtil.java

private String getDevelopedByInfo(final Artifact artifact, final Model artifactPom) {
    final StrBuilder developedByInfo = new StrBuilder();

    // prefer organization if available
    if (null != artifactPom.getOrganization()) {
        final String url = artifactPom.getOrganization().getUrl();
        boolean wroteUrl = false;
        if (isPotentialWebUrl(url)) {
            try {
                final URL organizationUrl = toUrl(url); // parse as URL to avoid surprises
                developedByInfo.append("<a href=\"").append(organizationUrl.toExternalForm())
                        .append("\" target=\"_blank\">");
                wroteUrl = true;/* w w  w .  j  a v  a 2  s  .  c  om*/
            } catch (final MalformedURLException e) {
                getLog().debug(e);
                getLog().warn(format("Invalide organization url '%s' in artifact pom '%s'.", url,
                        artifact.getFile()));
            }
        }
        if (StringUtils.isNotBlank(artifactPom.getOrganization().getName())) {
            developedByInfo.append(escapeHtml4(artifactPom.getOrganization().getName()));
        } else if (StringUtils.isNotBlank(url)) {
            developedByInfo.append(escapeHtml4(removeWebProtocols(url)));
        }
        if (wroteUrl) {
            developedByInfo.append("</a>");
        }
    }

    // use to developers if no organization is available
    if (developedByInfo.isEmpty()) {
        if (!artifactPom.getDevelopers().isEmpty()) {
            appendDeveloperInfo(developedByInfo, artifactPom);
        } else {
            getLog().warn(format(
                    "Neither organization nor developer information is available for artifact '%s:%s:%s'. Please fill in manually.",
                    artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()));
            developedByInfo.append("someone");
        }
    }
    return developedByInfo.toString();
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlFileInputTest.java

/**
 * @throws Exception if the test fails//from  w  w w.  j a v  a2 s.  com
 */
@Test
public void contentType() throws Exception {
    final String firstContent = "<html><head></head><body>\n" + "<form enctype='multipart/form-data' action='"
            + URL_SECOND + "' method='POST'>\n" + "  <input type='file' name='image' />\n"
            + "  <input type='submit' name='mysubmit'/>\n" + "</form>\n" + "</body>\n" + "</html>";
    final String secondContent = "<html><head><title>second</title></head></html>";
    final WebClient client = getWebClient();

    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setResponse(URL_FIRST, firstContent);
    webConnection.setResponse(URL_SECOND, secondContent);

    client.setWebConnection(webConnection);

    final HtmlPage firstPage = client.getPage(URL_FIRST);
    final HtmlForm f = firstPage.getForms().get(0);
    final HtmlFileInput fileInput = f.getInputByName("image");

    final URL fileURL = getClass().getClassLoader().getResource("testfiles/empty.png");

    fileInput.setValueAttribute(fileURL.toExternalForm());
    f.getInputByName("mysubmit").click();
    final KeyDataPair pair = (KeyDataPair) webConnection.getLastParameters().get(0);
    assertNotNull(pair.getFile());
    assertFalse("Content type: " + pair.getMimeType(), "text/webtest".equals(pair.getMimeType()));

    fileInput.setContentType("text/webtest");
    f.getInputByName("mysubmit").click();
    final KeyDataPair pair2 = (KeyDataPair) webConnection.getLastParameters().get(0);
    assertNotNull(pair2.getFile());
    assertEquals("text/webtest", pair2.getMimeType());
}

From source file:com.google.gwt.resources.rg.GssResourceGenerator.java

public static SourceCode readUrlContent(URL fileUrl, TreeLogger logger) throws UnableToCompleteException {
    TreeLogger branchLogger = logger.branch(TreeLogger.DEBUG,
            "Reading GSS stylesheet " + fileUrl.toExternalForm());
    try {/* w  w w. j ava  2s .  c o  m*/
        ByteSource byteSource = Resources.asByteSource(fileUrl);
        // default charset
        Charset charset = Charsets.UTF_8;

        // check if the stylesheet doesn't include a @charset at-rule
        String styleSheetCharset = extractCharset(byteSource);
        if (styleSheetCharset != null) {
            try {
                charset = Charset.forName(styleSheetCharset);
            } catch (UnsupportedCharsetException e) {
                logger.log(Type.ERROR, "Unsupported charset found: " + styleSheetCharset);
                throw new UnableToCompleteException();
            }
        }

        String fileContent = byteSource.asCharSource(charset).read();
        // If the stylesheet specified a charset, we have to remove the at-rule otherwise the GSS
        // compiler will fail.
        if (styleSheetCharset != null) {
            int charsetAtRuleLength = CHARSET_MIN_LENGTH + styleSheetCharset.length();
            // replace charset at-rule by blanks to keep correct source location of the rest of
            // the stylesheet.
            fileContent = Strings.repeat(" ", charsetAtRuleLength) + fileContent.substring(charsetAtRuleLength);
        }
        return new SourceCode(fileUrl.getFile(), fileContent);

    } catch (IOException e) {
        branchLogger.log(TreeLogger.ERROR, "Unable to parse CSS", e);
    }
    throw new UnableToCompleteException();
}

From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientRemoteStorage.java

@Override
public void storeItem(final ProxyRepository repository, final StorageItem item)
        throws UnsupportedStorageOperationException, RemoteStorageException {
    if (!(item instanceof StorageFileItem)) {
        throw new UnsupportedStorageOperationException("Storing of non-files remotely is not supported!");
    }/*  w w w. j av a2s  .  com*/

    final StorageFileItem fileItem = (StorageFileItem) item;

    final ResourceStoreRequest request = new ResourceStoreRequest(item);

    final URL remoteUrl = appendQueryString(getAbsoluteUrlFromBase(repository, request), repository);

    final HttpPut method = new HttpPut(remoteUrl.toExternalForm());

    final InputStreamEntity entity;
    try {
        entity = new InputStreamEntity(fileItem.getInputStream(), fileItem.getLength());
    } catch (IOException e) {
        throw new RemoteStorageException(
                e.getMessage() + " [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                        + request.getRequestPath() + "\", remoteUrl=\"" + remoteUrl.toString() + "\"]",
                e);
    }

    entity.setContentType(fileItem.getMimeType());
    method.setEntity(entity);

    final HttpResponse httpResponse = executeRequestAndRelease(repository, request, method);
    final int statusCode = httpResponse.getStatusLine().getStatusCode();

    if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
            && statusCode != HttpStatus.SC_NO_CONTENT && statusCode != HttpStatus.SC_ACCEPTED) {
        throw new RemoteStorageException("Unexpected response code while executing " + method.getMethod()
                + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                + request.getRequestPath() + "\", remoteUrl=\"" + remoteUrl.toString()
                + "\"]. Expected: \"any success (2xx)\". Received: " + statusCode + " : "
                + httpResponse.getStatusLine().getReasonPhrase());
    }
}

From source file:com.nextep.designer.sqlgen.ui.editors.SQLTextHtmlHover.java

@SuppressWarnings("unchecked")
@Override/*  ww  w.j  a  v  a 2s.  com*/
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
    final int offset = hoverRegion.getOffset();
    final IDocument document = textViewer.getDocument();
    if (document == null)
        return null;

    IRegion lineInfo;
    String line;
    try {
        lineInfo = document.getLineInformationOfOffset(offset);
        line = document.get(lineInfo.getOffset(), lineInfo.getLength());
    } catch (BadLocationException ex) {
        return null;
    }

    // Retrieving proposals
    ITypedObjectTextProvider provider = SQLEditorUIServices.getInstance().getTypedObjectTextProvider();
    List<String> allProposals = provider.listProvidedElements();
    for (String s : allProposals) {
        if (line.toUpperCase().contains(s.toUpperCase())) {
            // More accurate search
            Pattern p = Pattern.compile("(\\W|\\s|^)" + s.toUpperCase() + "(\\W|\\s|$)"); //$NON-NLS-1$ //$NON-NLS-2$
            Matcher m = p.matcher(line.toUpperCase());
            while (m.find()) {
                if (offset >= (m.start() + lineInfo.getOffset())
                        && offset <= (m.end() + lineInfo.getOffset())) {

                    final ITypedObject obj = provider.getElement(s);
                    final StringBuffer buf = new StringBuffer();
                    final INamedObject named = (INamedObject) obj;
                    buf.append("<html>"); //$NON-NLS-1$
                    addStyleSheet(buf);
                    appendColors(buf, FontFactory.BLACK.getRGB(), FontFactory.LIGHT_YELLOW.getRGB());
                    // buf.append("\n<table BORDER=0 BORDERCOLOR=\"#000000\" CELLPADDING=0 cellspacing=0 >\n");
                    // buf.append("<tr><td>\n");
                    URL u = ImageService.getInstance()
                            .getImageURL(ImageFactory.getImageDescriptor(obj.getType().getIcon()));
                    buf.append("<table border=0><tr valign=\"CENTER\"><td><img src=\"" //$NON-NLS-1$
                            + u.toExternalForm() + "\"/>&nbsp;"); //$NON-NLS-1$
                    buf.append("</td><td><b>" + obj.getType().getName() + " " + named.getName() //$NON-NLS-1$ //$NON-NLS-2$
                            + "</b></td></tr></table>"); //$NON-NLS-1$
                    if (named.getDescription() != null && !"".equals(named.getDescription().trim())) { //$NON-NLS-1$
                        buf.append("<i>" + named.getDescription() + "</i><br><br>"); //$NON-NLS-1$ //$NON-NLS-2$
                    } else {
                        buf.append("<i>"); //$NON-NLS-1$
                        buf.append(SQLMessages.getString("sqlHover.noDesc")); //$NON-NLS-1$
                        buf.append("</i><br><br>"); //$NON-NLS-1$
                    }
                    // Temporarily adding table definition here
                    if (obj instanceof IBasicTable) {
                        final IBasicTable t = (IBasicTable) obj;
                        buf.append("<table BORDER=1 BORDERCOLOR=\"#000000\" CELLPADDING=4 cellspacing=0 >\n"); // + //$NON-NLS-1$
                        buf.append("<tr bgcolor=\""); //$NON-NLS-1$
                        appendColor(buf, new RGB(220, 250, 220));
                        buf.append("\"><td><b>"); //$NON-NLS-1$
                        buf.append(SQLMessages.getString("sqlHover.columnNameCol")); //$NON-NLS-1$
                        buf.append("</b></td><td><b>"); //$NON-NLS-1$
                        buf.append(SQLMessages.getString("sqlHover.datatypeCol")); //$NON-NLS-1$
                        buf.append("</b></td><td><b>"); //$NON-NLS-1$
                        buf.append(SQLMessages.getString("sqlHover.descriptionCol")); //$NON-NLS-1$
                        buf.append("</b></td></tr>\n"); //$NON-NLS-1$
                        // /*cellspacing=\"0\" callpadding=\"0\" */  "border=\"1\" align=\"left\" width=\"350\">\n");
                        for (IBasicColumn c : t.getColumns()) {
                            buf.append("<tr>\n"); //$NON-NLS-1$
                            buf.append("<td>" + c.getName() + "</td>\n"); //$NON-NLS-1$ //$NON-NLS-2$
                            buf.append("<td>" + c.getDatatype() + "</td>\n"); //$NON-NLS-1$ //$NON-NLS-2$
                            final String desc = c.getDescription();
                            buf.append("<td>" + (desc == null ? "" : desc) + "</td>\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                            buf.append("</tr>"); //$NON-NLS-1$
                        }
                        buf.append("</table><br>"); //$NON-NLS-1$
                    } else {
                        buf.append("<br>"); //$NON-NLS-1$
                    }
                    if (obj instanceof IReferencer) {
                        Collection<IReference> refs = ((IReferencer) obj).getReferenceDependencies();
                        if (refs != null && !refs.isEmpty()) {
                            buf.append("<b>"); //$NON-NLS-1$
                            buf.append(SQLMessages.getString("sqlHover.dependentOf")); //$NON-NLS-1$
                            buf.append("</b><br><span>"); //$NON-NLS-1$
                            for (IReference r : refs) {
                                IReferenceable ref = VersionHelper.getReferencedItem(r);
                                buf.append("<li>" + ((ITypedObject) ref).getType().getName() //$NON-NLS-1$
                                        + "&nbsp;<u>" + ((INamedObject) ref).getName() //$NON-NLS-1$
                                        + "</u></li>"); //$NON-NLS-1$
                                // buf.append(Designer.getInstance().getQualifiedName(ref)
                                // + "<br>");
                            }
                            buf.append("</span><br>"); //$NON-NLS-1$
                        }
                    }
                    if (obj instanceof IReferenceable && invRefMap != null) {
                        Collection<IReferencer> referencers = (Collection<IReferencer>) invRefMap
                                .get(((IReferenceable) obj).getReference());
                        if (referencers != null && !referencers.isEmpty()) {
                            buf.append("<b>"); //$NON-NLS-1$
                            buf.append(SQLMessages.getString("sqlHover.dependencies")); //$NON-NLS-1$
                            buf.append("</b><br><span>"); //$NON-NLS-1$
                            for (IReferencer r : referencers) {
                                buf.append("<li>" + ((ITypedObject) r).getType().getName() //$NON-NLS-1$
                                        + "&nbsp;<u>" + ((INamedObject) r).getName() //$NON-NLS-1$
                                        + "</u></li>"); //$NON-NLS-1$
                            }
                        }
                        buf.append("</span>"); //$NON-NLS-1$
                    }
                    // buf.append("</td></tr></table>");
                    buf.append("</body></html>"); //$NON-NLS-1$
                    return buf.toString();
                }
            }
        }
    }
    return null;
}

From source file:org.eclipse.skalli.model.ext.maven.internal.HttpMavenPomResolverBase.java

private void logResponse(URL url, HttpEntity entity) throws IOException {
    try {/*w  w w  . j  a  va  2  s.co m*/
        StringWriter writer = new StringWriter();

        String encoding = null;
        if (entity.getContentEncoding() != null) {
            encoding = entity.getContentEncoding().getValue();
        }
        IOUtils.copy(entity.getContent(), writer, encoding);
        String content = writer.toString();

        StringBuilder sb = new StringBuilder();
        sb.append("Response from ").append(url.toExternalForm()).append(":\n");
        Header contentType = entity.getContentType();
        sb.append("Content-Type: ")
                .append(contentType == null ? "<not available>" : entity.getContentType().getValue())
                .append("\n");
        sb.append("Content-Encoding: ").append(encoding == null ? "<not available>" : encoding).append("\n");
        sb.append("\n").append(content);
        LOG.error(sb.toString());
    } catch (IOException e) {
        throw new IOException(MessageFormat.format(
                "Unexpected exception while trying to consume the response from {0}", url.toExternalForm()), e);
    }
}

From source file:com.dawg6.d3api.server.D3IO.java

public ItemInformation readItemInformation(Realm realm, String tooltipParams)
        throws JsonParseException, IOException {

    URL url = new URL(UrlHelper.itemInformationUrl(this.itemRealm, tooltipParams) + getApiKey());
    String urlString = url.toExternalForm();

    synchronized (itemCache) {
        ItemInformation item = itemCache.get(urlString);

        if (item != null) {
            // log.info("Item Cache hit: " + server + "/" + tooltipParams);
            cacheHit++;//from  w w  w .  j a v  a2s  .c  o  m
            return item;
        } else {
            cacheMiss++;
            // log.info("Item Cache miss: " + server + "/" + tooltipParams);
        }
    }

    ObjectMapper mapper = new ObjectMapper();
    throttle();
    ItemInformation out = readValue(mapper, url, ItemInformation.class);

    if (out.code == null) {
        synchronized (itemCache) {
            itemCache.put(urlString, out);
        }

        newItem(out);
    }

    return out;

}