Example usage for java.net URI toURL

List of usage examples for java.net URI toURL

Introduction

In this page you can find the example usage for java.net URI toURL.

Prototype

public URL toURL() throws MalformedURLException 

Source Link

Document

Constructs a URL from this URI.

Usage

From source file:org.deeplearning4j.models.embeddings.inmemory.InMemoryLookupTable.java

/**
 * Render the words via TSNE/*w w w .  j ava 2  s. c om*/
 *
 * @param tsne           the tsne to use
 * @param numWords
 * @param connectionInfo
 */
@Override
public void plotVocab(BarnesHutTsne tsne, int numWords, UiConnectionInfo connectionInfo) {
    try {
        final List<String> labels = fitTnseAndGetLabels(tsne, numWords);
        final INDArray reducedData = tsne.getData();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < reducedData.rows() && i < numWords; i++) {
            String word = labels.get(i);
            INDArray wordVector = reducedData.getRow(i);
            for (int j = 0; j < wordVector.length(); j++) {
                sb.append(String.valueOf(wordVector.getDouble(j))).append(",");
            }
            sb.append(word);
        }

        String address = connectionInfo.getFirstPart() + "/tsne/post/" + connectionInfo.getSessionId();
        //            System.out.println("ADDRESS: " + address);
        URI uri = new URI(address);

        HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        //            connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Content-Type", "multipart/form-data");
        connection.setDoOutput(true);

        DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
        dos.writeBytes(sb.toString());
        dos.flush();
        dos.close();

        try {
            int responseCode = connection.getResponseCode();
            System.out.println("RESPONSE CODE: " + responseCode);

            if (responseCode != 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                log.warn("Error posting to remote UI - received response code {}\tContent: {}", response,
                        response.toString());
            }
        } catch (IOException e) {
            log.warn("Error posting to remote UI at {}", uri, e);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.axis2.jaxws.util.CatalogWSDLLocator.java

/**
 * Return the wsdlLocation in URL form. WsdlLocation could be URL, relative
 * module path, full absolute path.//w ww  .  ja v a  2 s. c o  m
 * 
 * @param wsdlLocation
 *            the location of a WSDL document in the form of a URL string, a
 *            relative pathname (relative to the root of a module, or a
 *            full-qualified absolute pathname
 * @return the location of the WSDL document in the form of a URL
 */
public URL getWsdlUrl(String wsdlLocation) {
    URL streamURL = null;
    InputStream is = null;
    URI pathURI = null;

    // If the WSDL is present in the catalog, use the location specified 
    // in the catalog.  If this attempt results in failure, use the original
    // location
    // TODO:  Provide Allowance for Catalog
    // Note:  This method is not called.

    try {
        streamURL = new URL(wsdlLocation);
        is = streamURL.openStream();
        is.close();
    } catch (Throwable t) {
        // No FFDC required
    }

    if (is == null) {
        try {
            pathURI = new URI(wsdlLocation);
            streamURL = pathURI.toURL();
            is = streamURL.openStream();
            is.close();
        } catch (Throwable t) {
            // No FFDC required
        }
    }

    if (is == null) {
        try {
            File file = new File(wsdlLocation);
            streamURL = file.toURL();
            is = streamURL.openStream();
            is.close();
        } catch (Throwable t) {
            // No FFDC required
        }
    }

    if (log.isDebugEnabled() && streamURL == null) {
        log.debug("Absolute wsdlLocation could not be determined: " + wsdlLocation);
    }

    return streamURL;
}

From source file:nya.miku.wishmaster.chans.dobrochan.DobroModule.java

private String sanitizeUrl(String urlStr) {
    if (urlStr == null)
        return null;
    try {//w ww  .j a v a  2 s .  c  om
        URL url = new URL(urlStr);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        return uri.toURL().toString();
    } catch (Exception e) {
        Logger.e(TAG, "sanitize url", e);
        return urlStr;
    }
}

From source file:org.deegree.ogcwebservices.wass.wss.operation.DoServiceHandler.java

/**
 * Resets all the url in the response body with the facade urls
 *
 * @param op//from   ww w .ja  v  a  2s .  c  o m
 *            the operation which has the secured service url in it
 * @param facadeURI
 *            the url of this wss.
 */
private void setNewOnlineResource(Operation op, URI facadeURI) {

    if (op.getDCPs() != null) {
        for (int i = 0; i < op.getDCPs().length; i++) {
            HTTP http = (HTTP) op.getDCPs()[i].getProtocol();
            try {
                if (http.getGetOnlineResources().length > 0) {
                    URL urls[] = new URL[http.getGetOnlineResources().length];
                    for (int k = 0; k < http.getGetOnlineResources().length; ++k)
                        urls[k] = facadeURI.toURL();

                    http.setGetOnlineResources(urls);
                }
                if (http.getPostOnlineResources().length > 0) {
                    URL urls[] = new URL[http.getPostOnlineResources().length];
                    for (int k = 0; k < http.getPostOnlineResources().length; ++k) {
                        urls[k] = facadeURI.toURL();
                    }

                    http.setPostOnlineResources(urls);
                }
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            }
        }
    }

}

From source file:com.mirth.connect.connectors.ws.WebServiceConnectorService.java

private WsdlInterface getWsdlInterface(URI wsdlUrl, String username, String password) throws Exception {
    /* add the username:password to the URL if using authentication */
    if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
        String hostWithCredentials = username + ":" + password + "@" + wsdlUrl.getHost();
        wsdlUrl = new URI(wsdlUrl.getScheme(), hostWithCredentials, wsdlUrl.getPath(), wsdlUrl.getQuery(),
                wsdlUrl.getFragment());//from ww  w .j a  v  a 2s .  c om
    }

    // 
    SoapUI.setSoapUICore(new EmbeddedSoapUICore());
    WsdlProject wsdlProject = new WsdlProjectFactory().createNew();
    WsdlLoader wsdlLoader = new UrlWsdlLoader(wsdlUrl.toURL().toString());

    try {
        Future<WsdlInterface> future = importWsdlInterface(wsdlProject, wsdlUrl, wsdlLoader);
        return future.get(30, TimeUnit.SECONDS);
    } catch (Exception e) {
        wsdlLoader.abort();
        throw e;
    }
}

From source file:dip.world.variant.VariantManager.java

/** 
 *   Internal getResource() implementation
 *///from ww  w .  j a v a 2  s . c  o m
private static synchronized URL getResource(MapRecObj mro, URI uri) {
    // ensure we have been initialized...
    checkVM();
    assert (mro != null);

    if (uri == null) {
        throw new IllegalArgumentException("null URI");
    }

    // if we are in webstart, assume that this is a webstart jar. 
    if (vm.isInWebstart) {
        URL url = getWSResource(mro, uri);

        // if cannot get it, fall through.
        if (url != null) {
            return url;
        }
    }

    // if URI has a defined scheme, convert to a URL (if possible) and return it.
    if (uri.getScheme() != null) {
        try {
            return uri.toURL();
        } catch (MalformedURLException e) {
            return null;
        }
    }

    // find the URL
    if (mro.getURL() != null) {
        return getClassLoader(mro.getURL()).findResource(uri.toString());
    }

    return null;
}

From source file:org.apache.ws.scout.transport.SaajTransport.java

public Element send(Element request, URI endpointURL) throws TransportException {
    if (log.isDebugEnabled()) {
        String requestMessage = XMLUtils.convertNodeToXMLString(request);
        log.debug("Request message: %s\n%s" + endpointURL + ":" + requestMessage);
    }//w ww .  j ava  2 s. com

    Element response = null;
    try {
        SOAPMessage message = this.createSOAPMessage(request);
        //Make the SAAJ Call now
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = soapConnectionFactory.createConnection();
        SOAPMessage soapResponse = connection.call(message, endpointURL.toURL());

        SOAPBody soapBody = soapResponse.getSOAPBody();
        boolean hasFault = soapBody.hasFault();
        if (hasFault) {
            SOAPFault soapFault = soapBody.getFault();
            String faultStr = soapFault.getFaultCode() + "::" + soapFault.getFaultString();
            throw new RegistryException(faultStr);
        }
        response = getFirstChildElement(soapBody);
    } catch (Exception ex) {
        log.error("Exception::" + ex.getMessage(), ex);
        throw new TransportException(ex);
    }
    if (log.isDebugEnabled()) {
        String responseMessage = XMLUtils.convertNodeToXMLString(response);
        log.debug("Response message: %s" + responseMessage);
    }

    return response;
}

From source file:com.ibm.jaggr.core.impl.cache.GzipCacheImpl.java

@Override
public InputStream getInputStream(final String key, final URI source, final MutableInt retLength)
        throws IOException {
    final String sourceMethod = "getInputStream"; //$NON-NLS-1$
    final boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(sourceClass, sourceMethod, new Object[] { key, source, retLength });
    }//w w  w.  java2 s .  co m

    InputStream in = null, result = null;
    CacheEntry tryCacheEntry = (CacheEntry) super.get(key);
    URLConnection connection = source.toURL().openConnection();

    try {
        long lastModified = connection.getLastModified();
        if (tryCacheEntry != null) {
            // Make local copies of volatile CacheEntry fields
            byte[] bytes = tryCacheEntry.bytes;
            File file = tryCacheEntry.file;
            if (bytes != null) {
                // Important - CacheEntry.lastModified is set before CacheEntry.bytes so we can
                // safely
                // check CacheEntry.lastModified here even though we're not synchronized.
                if (lastModified != tryCacheEntry.lastModified) {
                    // stale cache entry. Remove it and create a new one below
                    cacheMap.remove(key, tryCacheEntry);
                } else {
                    retLength.setValue(tryCacheEntry.bytes.length);
                    result = new ByteArrayInputStream(tryCacheEntry.bytes);
                }
            } else if (file != null) {
                // Some platforms round file last modified times to nearest second.
                if (Math.abs(lastModified - file.lastModified()) > 1000) {
                    // Stale cache entry, remove it and create a new one below
                    cacheMap.remove(key, tryCacheEntry);
                    // also delete the associated cache file asynchronously.
                    cacheManager.deleteFileDelayed(file.getName());
                } else {
                    try {
                        retLength.setValue(file.length());
                        result = new FileInputStream(file);
                    } catch (FileNotFoundException ex) {
                        // File doesn't exist (was probably deleted outside this program)
                        // Not fatal, just fall through and create it again.
                        cacheMap.remove(key, tryCacheEntry);
                    }
                }
            }
            if (result != null) {
                // found result in cache. Return it.
                log.exiting(sourceClass, sourceMethod, result);
                return result;
            }
        }

        // Result not in cache (or we removed it). Try to create a new cache entry.
        CacheEntry newCacheEntry = new CacheEntry();
        CacheEntry oldCacheEntry = (CacheEntry) cacheMap.putIfAbsent(key, newCacheEntry);
        final CacheEntry cacheEntry = oldCacheEntry != null ? oldCacheEntry : newCacheEntry;

        // Synchronize on the cache entry so that more than one thread won't try to create the
        // zipped content.
        synchronized (cacheEntry) {
            if (cacheEntry.ex != null) {
                // An exception occurred trying to create the gzip response in another thread.
                // Re-throw the exception here.
                throw cacheEntry.ex;
            }
            // First, check to make sure that another thread didn't beat us to the punch.
            // Even though we're synchronized on the cacheEntry object, cacheEntry.bytes can be
            // cleared by the createCacheFileAsync callback, so we need to copy this volatile
            // field
            // to a local variable and access it from there.
            byte[] bytes = cacheEntry.bytes;
            if (bytes != null) {
                retLength.setValue(bytes.length);
                result = new ByteArrayInputStream(bytes);
            } else if (cacheEntry.file != null) { // once set, cacheEntry.file does not change
                // by convention
                retLength.setValue(cacheEntry.file.length());
                result = new FileInputStream(cacheEntry.file);
            } else {
                // Gzip encode the resource and save the result in the cache entry until the
                // cache
                // file is written asynchronously.
                try {
                    in = connection.getInputStream();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    VariableGZIPOutputStream compress = new VariableGZIPOutputStream(bos, 10240);
                    compress.setLevel(Deflater.BEST_COMPRESSION);
                    CopyUtil.copy(in, compress);

                    // Important - CacheEntry.lastModified must be set before cacheEntry.bytes
                    cacheEntry.lastModified = lastModified;
                    cacheEntry.bytes = bos.toByteArray();
                    result = new ByteArrayInputStream(cacheEntry.bytes);
                    retLength.setValue(cacheEntry.bytes.length);

                    // Call the cache manager to asynchronously save the gzipped response to
                    // disk
                    // Include the filename part of the source URI in the cached filename
                    String path = source.getPath();
                    int idx = path.lastIndexOf("/"); //$NON-NLS-1$
                    String fname = (idx != -1) ? path.substring(idx + 1) : path;
                    cacheManager.createCacheFileAsync(fname + ".gzip.", //$NON-NLS-1$
                            new ByteArrayInputStream(cacheEntry.bytes),
                            new ICacheManager.CreateCompletionCallback() {
                                @Override
                                public void completed(String filename, Exception e) {
                                    if (e != null && log.isLoggable(Level.SEVERE)) {
                                        // Exception occurred saving file. Not much we can do
                                        // except log the error
                                        log.logp(Level.SEVERE, sourceClass, sourceMethod, e.getMessage(), e);
                                        return;
                                    }
                                    File cacheFile = new File(cacheManager.getCacheDir(), filename);
                                    cacheFile.setLastModified(cacheEntry.lastModified);
                                    // Important - cacheEntry.file must be set before clearing
                                    // cacheEntry.bytes
                                    cacheEntry.file = cacheFile;
                                    cacheEntry.bytes = null;
                                }
                            });
                } catch (Throwable t) {
                    cacheEntry.ex = (t instanceof IOException) ? (IOException) t : new IOException(t);
                    cacheMap.remove(key, cacheEntry);
                    throw cacheEntry.ex;
                }
            }
        }
    } finally {
        // URLConnection doesn't have a close method. The only way to make sure a connection is
        // closed is to close the input or output stream which is obtained from the connection.
        if (in != null) {
            in.close();
        } else {
            connection.getInputStream().close();
        }
    }
    if (isTraceLogging) {
        log.exiting(sourceClass, sourceClass, result);
    }
    return result;
}

From source file:org.codice.ddf.spatial.ogc.catalog.resource.impl.OgcUrlResourceReader.java

/**
 * Retrieves a {@link ddf.catalog.resource.Resource} based on a {@link URI} and provided
 * arguments. A connection is made to the {@link URI} to obtain the
 * {@link ddf.catalog.resource.Resource}'s {@link InputStream} and build a
 * {@link ResourceResponse} from that. The {@link ddf.catalog.resource.Resource}'s name gets set
 * to the {@link URI} passed in. Calls {@link URLResourceReader}, if the mime-type is
 * "text/html" it will inject a simple script to redirect to the resourceURI instead of
 * attempting to download it./*from  www .j  ava2  s .  c  o m*/
 *
 * @param resourceURI
 *            A {@link URI} that defines what {@link Resource} to retrieve and how to do it.
 * @param properties
 *            Any additional arguments that should be passed to the
 *            {@link ddf.catalog.resource.ResourceReader}.
 * @return A {@link ResourceResponse} containing the retrieved {@link Resource}.
 * @throws ResourceNotSupportedException
 */
public ResourceResponse retrieveResource(URI resourceURI, Map<String, Serializable> properties)
        throws IOException, ResourceNotFoundException, ResourceNotSupportedException {
    LOGGER.debug("Calling URLResourceReader.retrieveResource()");
    ResourceResponse response = urlResourceReader.retrieveResource(resourceURI, properties);
    Resource resource = response.getResource();
    MimeType mimeType = resource.getMimeType();
    LOGGER.debug("mimeType: {}", mimeType);
    if (mimeType != null) {
        String mimeTypeStr = mimeType.toString();
        String detectedMimeType = "";
        if (UNKNOWN_MIME_TYPES.contains(mimeTypeStr)) {
            detectedMimeType = tika.detect(resourceURI.toURL());
        }
        if (StringUtils.contains(detectedMimeType, MediaType.TEXT_HTML)
                || StringUtils.contains(mimeTypeStr, MediaType.TEXT_HTML)) {
            LOGGER.debug("Detected \"text\\html\". Building redirect script");
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.append("<html><script type=\"text/javascript\">window.location.replace(\"");
            strBuilder.append(resourceURI);
            strBuilder.append("\");</script></html>");
            return new ResourceResponseImpl(new ResourceImpl(
                    new ByteArrayInputStream(strBuilder.toString().getBytes(StandardCharsets.UTF_8)),
                    detectedMimeType, resource.getName()));
        }
    }
    return response;
}

From source file:com.aurel.track.util.PluginUtils.java

/**
 * Transforms the given URL which may contain escaping characters (like %20 for space)
 * to an URL which may conatin illegal URL characters (like space) but is valid for creating a file based on the resulting URL
 * The escape characters will be changed back to characters that are illegal in URLs (like space) because the file could be
 * constructed just in such a way in some servlet containers like Tomcat5.5
 * @param url/* w w  w. j  a v a2s.  co m*/
 * @return
 */
public static URL createValidFileURL(URL url) {
    File file;
    URL fileUrl;
    if (url == null) {
        return null;
    }
    if (url.getPath() != null) {
        file = new File(url.getPath());
        //we have no escape characters or the servlet container can deal with escape characters
        if (file.exists()) {
            //valid url
            return url;
        }
    }
    //valid file through URI?
    //see Bug ID:  4466485 (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4466485)
    URI uri = null;
    try {
        //get rid of spaces
        uri = new URI(url.toString());
    } catch (URISyntaxException e1) {
    }
    if (uri == null) {
        return null;
    }
    if (uri.getPath() != null) {
        //the decoded path component of this URI
        file = new File(uri.getPath());
        if (file.exists()) {
            try {
                //file.toURL() does not automatically escape characters that are illegal in URLs
                fileUrl = file.toURL(); // revert, problems with Windows?
                if (fileUrl != null) {
                    return fileUrl;
                }
            } catch (MalformedURLException e) {
            }
        }
    }
    //back to URL from URI
    try {
        url = uri.toURL();
    } catch (MalformedURLException e) {
    }
    if (url != null && url.getPath() != null) {
        file = new File(url.getPath());
        if (file.exists()) {
            //valid url
            return url;
        }
    }
    return null;
}