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:com.cloud.utils.UriUtils.java

public static Long getRemoteSize(String url) {
    Long remoteSize = (long) 0;
    HttpURLConnection httpConn = null;
    HttpsURLConnection httpsConn = null;
    try {/*w  w  w .j av  a 2 s .  c om*/
        URI uri = new URI(url);
        if (uri.getScheme().equalsIgnoreCase("http")) {
            httpConn = (HttpURLConnection) uri.toURL().openConnection();
            if (httpConn != null) {
                httpConn.setConnectTimeout(2000);
                httpConn.setReadTimeout(5000);
                String contentLength = httpConn.getHeaderField("content-length");
                if (contentLength != null) {
                    remoteSize = Long.parseLong(contentLength);
                }
                httpConn.disconnect();
            }
        } else if (uri.getScheme().equalsIgnoreCase("https")) {
            httpsConn = (HttpsURLConnection) uri.toURL().openConnection();
            if (httpsConn != null) {
                String contentLength = httpsConn.getHeaderField("content-length");
                if (contentLength != null) {
                    remoteSize = Long.parseLong(contentLength);
                }
                httpsConn.disconnect();
            }
        }
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid URL " + url);
    } catch (IOException e) {
        throw new IllegalArgumentException("Unable to establish connection with URL " + url);
    }
    return remoteSize;
}

From source file:org.eclipse.osee.framework.core.util.HttpProcessor.java

public static boolean isAlive(URI uri) {
    boolean isAlive = false;
    try {//from   ww w  .j  ava 2s. c  o  m
        isAlive = isAlive(uri.toURL());
    } catch (MalformedURLException ex) {
        // do nothing
    }
    return isAlive;
}

From source file:Main.java

public static void copyCompletely(URI input, URI output) throws IOException {
    try {/*from w  ww .  j  av a 2  s.co m*/
        InputStream in = null;
        try {
            File f = new File(input);
            if (f.exists())
                in = new FileInputStream(f);
        } catch (Exception notAFile) {
        }

        File out = new File(output);
        File dir = out.getParentFile();
        dir.mkdirs();

        if (in == null)
            in = input.toURL().openStream();

        copyCompletely(in, new FileOutputStream(out));
    } catch (IllegalArgumentException e) {
        throw new IOException("Cannot copy to " + output);
    }
}

From source file:org.apache.ode.axis2.hooks.ODEAxisService.java

public static AxisService createService(AxisConfiguration axisConfig, ProcessConf pconf, QName wsdlServiceName,
        String portName) throws AxisFault {
    Definition wsdlDefinition = pconf.getDefinitionForService(wsdlServiceName);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Create AxisService:" + " service=" + wsdlServiceName + " port=" + portName + " WSDL="
                + wsdlDefinition.getDocumentBaseURI() + " BPEL=" + pconf.getBpelDocument());
    }//from  www .j a v  a 2  s  . c  o  m

    InputStream is = null;
    try {
        URI baseUri = pconf.getBaseURI().resolve(wsdlDefinition.getDocumentBaseURI());
        is = baseUri.toURL().openStream();
        WSDL11ToAxisPatchedBuilder serviceBuilder = new WSDL11ToAxisPatchedBuilder(is, wsdlServiceName,
                portName);
        serviceBuilder.setBaseUri(baseUri.toString());
        serviceBuilder.setCustomResolver(new Axis2UriResolver());
        serviceBuilder.setCustomWSLD4JResolver(new Axis2WSDLLocator(baseUri));
        serviceBuilder.setServerSide(true);

        String axisServiceName = ODEAxisService.extractServiceName(pconf, wsdlServiceName, portName);

        AxisService axisService = serviceBuilder.populateService();
        axisService.setParent(axisConfig);
        axisService.setName(axisServiceName);
        axisService.setWsdlFound(true);
        axisService.setCustomWsdl(true);
        axisService.setClassLoader(axisConfig.getServiceClassLoader());

        URL wsdlUrl = null;
        for (File file : pconf.getFiles()) {
            if (file.getAbsolutePath().indexOf(wsdlDefinition.getDocumentBaseURI()) > 0)
                wsdlUrl = file.toURI().toURL();
        }
        if (wsdlUrl != null)
            axisService.setFileName(wsdlUrl);

        // axis2 service configuration
        URL service_file = pconf.getBaseURI().resolve(wsdlServiceName.getLocalPart() + ".axis2").toURL();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Looking for Axis2 service configuration file: " + service_file);
        }
        try {
            AxisUtils.configureService(axisService, service_file);
        } catch (FileNotFoundException except) {
            LOG.debug("Axis2 service configuration not found: " + service_file);
        } catch (IOException except) {
            LOG.warn("Exception while configuring service: " + service_file, except);
        }

        final WSDL11Endpoint endpoint = new WSDL11Endpoint(wsdlServiceName, portName);
        final Map<String, String> properties = pconf.getEndpointProperties(endpoint);
        if (properties.get(Properties.PROP_SECURITY_POLICY) != null) {
            AxisUtils.applySecurityPolicy(axisService, properties.get(Properties.PROP_SECURITY_POLICY));
        }

        // In doc/lit we need to declare a mapping between operations and message element names
        // to be able to route properly.
        declarePartsElements(wsdlDefinition, wsdlServiceName, axisServiceName, portName);

        Iterator operations = axisService.getOperations();
        ODEMessageReceiver msgReceiver = new ODEMessageReceiver();
        while (operations.hasNext()) {
            AxisOperation operation = (AxisOperation) operations.next();
            if (operation.getMessageReceiver() == null) {
                operation.setMessageReceiver(msgReceiver);
            }
        }

        // Set the JMS destination name on the Axis Service
        if (isJmsEndpoint(pconf, wsdlServiceName, portName)) {
            axisService.addParameter(new Parameter(JMSConstants.PARAM_DESTINATION,
                    extractJMSDestinationName(axisServiceName, deriveBaseServiceUri(pconf))));
        }

        return axisService;
    } catch (Exception e) {
        throw AxisFault.makeFault(e);
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException ioe) {
            //Ignoring
        }
    }
}

From source file:net.antidot.semantic.rdf.rdb2rdf.r2rml.tools.R2RMLToolkit.java

/**
 * The URL-safe version of a string is obtained by an URL encoding to a
 * string value.//from   www. ja v a  2s . c om
 * 
 * @throws R2RMLDataError
 * @throws MalformedURLException
 */
public static String getURLSafeVersion(String value) throws R2RMLDataError {
    if (value == null)
        return null;
    URL url = null;
    try {
        url = new URL(value);
    } catch (MalformedURLException mue) {
        // This template should be not a url : no encoding
        return value;
    }
    // No exception raised, this template is a valid url : perform
    // percent-encoding
    try {
        java.net.URI uri = new java.net.URI(url.getProtocol(), url.getAuthority(), url.getPath(),
                url.getQuery(), url.getRef());
        String result = uri.toURL().toString();
        // Percent encoding : complete with no supported char in this
        // treatment
        result = result.replaceAll("\\,", "%2C");
        return result;
    } catch (URISyntaxException e) {
        throw new R2RMLDataError("[R2RMLToolkit:getIRISafeVersion] This value " + value
                + " can not be percent-encoded because " + e.getMessage());
    } catch (MalformedURLException e) {
        throw new R2RMLDataError("[R2RMLToolkit:getIRISafeVersion] This value " + value
                + " can not be percent-encoded because " + e.getMessage());
    }
}

From source file:com.microsoft.tfs.client.common.ui.browser.BrowserFacade.java

private static void launchWithWorkbenchBrowserSupport(final URI uri, final String title, final String tooltip,
        final String browserId, final LaunchMode launchMode) throws IllegalArgumentException, SecurityException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    URL url;//from w w w . j a  va2  s  .co  m
    try {
        url = uri.toURL();
    } catch (final MalformedURLException e) {
        throw new RuntimeException(e);
    }

    /*
     * compute style int for IWorkbenchBrowserSupport.createBrowser
     */
    int style = 0;
    if (launchMode == LaunchMode.EXTERNAL) {
        style |= (1 << 7); // IWorkbenchBrowserSupport.AS_EXTERNAL
    } else if (launchMode == LaunchMode.INTERNAL) {
        style |= (1 << 5); // IWorkbenchBrowserSupport.AS_EDITOR
    }

    /*
     * Method: IWorkbench#getBrowserSupport
     */
    final Method getBrowserSupportMethod = IWorkbench.class.getDeclaredMethod("getBrowserSupport", //$NON-NLS-1$
            new Class[] {});

    /*
     * Interface: IWorkbenchBrowserSupport
     */
    final Class iWorkbenchBrowserSupportInterface = getBrowserSupportMethod.getReturnType();

    /*
     * Object: workbench browser support object
     */
    final Object workbenchBrowserSupport = getBrowserSupportMethod.invoke(PlatformUI.getWorkbench(),
            (Object[]) null);

    /*
     * Method: IWorkbenchBrowserSupport#createBrowser(int, String, String,
     * String)
     */
    final Method createBrowserMethod = iWorkbenchBrowserSupportInterface.getDeclaredMethod("createBrowser", //$NON-NLS-1$
            new Class[] { Integer.TYPE, String.class, String.class, String.class });

    /*
     * Interface: IWebBrowser
     */
    final Class iWebBrowserInterface = createBrowserMethod.getReturnType();

    /*
     * Object: web browser object
     */
    final Object webBrowser = createBrowserMethod.invoke(workbenchBrowserSupport,
            new Object[] { new Integer(style), browserId, title, tooltip });

    /*
     * Launch the browser: IWebBrowser#openURL
     */
    iWebBrowserInterface.getDeclaredMethod("openURL", new Class[] //$NON-NLS-1$
    { URL.class }).invoke(webBrowser, new Object[] { url });
}

From source file:edu.mayo.informatics.lexgrid.convert.directConversions.NCIThesaurusHistoryFileToSQL.java

private static BufferedReader getReader(URI filePath) throws MalformedURLException, IOException {
    BufferedReader reader;/*from  w  ww  . j a va2s .c o  m*/
    if (filePath.getScheme().equals("file")) {
        reader = new BufferedReader(new FileReader(new File(filePath)));
    } else {
        reader = new BufferedReader(new InputStreamReader(filePath.toURL().openConnection().getInputStream()));
    }
    return reader;
}

From source file:Main.java

/**
 * Create URL using base URI.//from www .ja va2s  .co  m
 * 
 * @param url a URL string.
 * @param baseURI a base url string to assist in creating a URL.
 * @return newly created URL.
 * @throws MalformedURLException if a malformed URL has occurred.
 */
public static URL createURL(String url, String baseURI) throws MalformedURLException {
    URL returnURL = null;
    URI uri = null;
    try {
        returnURL = new URL(url);
        uri = new URI(url);
        uri = uri.normalize();
        returnURL = new URL(uri.toString());
    }

    catch (Exception mue) {
        int i = baseURI.lastIndexOf('/');
        int j = baseURI.lastIndexOf('\\');
        if (j > i)
            i = j;
        try {
            uri = new URI(baseURI.substring(0, i + 1) + url);
            uri = uri.normalize();
            returnURL = uri.toURL();
        } catch (Exception e) {
            return new URL(baseURI.substring(0, i + 1) + url);
        }
    }
    return returnURL;
}

From source file:com.dragome.web.helpers.serverside.DragomeCompilerLauncher.java

private static Classpath runProguard(File file, DragomeConfigurator configurator) throws Exception {
    URI uri = DragomeCompilerLauncher.class.getResource("/proguard.conf").toURI();
    Properties properties = System.getProperties();
    properties.put("in-jar-filename", file.getAbsolutePath());
    String outFilename = file.getAbsolutePath().replace(".jar", "-proguard.jar");
    new File(outFilename).deleteOnExit();
    properties.put("out-jar-filename", outFilename);
    ConfigurationParser parser = new ConfigurationParser(uri.toURL(), properties);
    URL additionalCodeKeepConfigFile = configurator.getAdditionalCodeKeepConfigFile();
    Configuration configuration = new Configuration();
    parser.parse(configuration);// www.j ava2 s . c  om

    if (additionalCodeKeepConfigFile != null) {
        ConfigurationParser parserForAdditionalKeepCodeConfigFile = new ConfigurationParser(
                additionalCodeKeepConfigFile, properties);
        parserForAdditionalKeepCodeConfigFile.parse(configuration);
    }

    new ProGuard(configuration).execute();
    return new Classpath(JarClasspathEntry.createFromPath(outFilename));
}

From source file:org.lanternpowered.server.network.vanilla.message.handler.play.HandlerPlayInChatMessage.java

private static Text newTextWithLinks(String message, TextTemplate template, boolean allowMissingHeader) {
    Text.Builder builder = null;/*from  w w w . ja  va 2 s .c  om*/
    StringBuilder lastMessage = null;

    Matcher matcher = URL_PATTERN.matcher(message);
    int lastEnd = 0;
    while (matcher.find()) {
        int start = matcher.start();
        int end = matcher.end();

        String part = message.substring(lastEnd, start);
        if (part.length() > 0) {
            if (lastMessage != null) {
                lastMessage.append(part);
            } else {
                lastMessage = new StringBuilder(part);
            }
        }

        lastEnd = end;
        String url = message.substring(start, end);
        URL urlInstance = null;

        try {
            URI uri = new URI(url);
            if (uri.getScheme() == null) {
                if (!allowMissingHeader) {
                    uri = null;
                } else {
                    uri = new URI("http://" + url);
                }
            }
            if (uri != null) {
                urlInstance = uri.toURL();
            }
        } catch (URISyntaxException | MalformedURLException ignored) {
        }

        if (urlInstance == null) {
            if (lastMessage != null) {
                lastMessage.append(url);
            } else {
                lastMessage = new StringBuilder(url);
            }
        } else {
            if (builder == null) {
                builder = Text.builder();
            }
            if (lastMessage != null) {
                builder.append(Text.of(lastMessage.toString()));
                lastMessage = null;
            }

            builder.append(template.apply(ImmutableMap.of(URL_ARGUMENT, url))
                    .onClick(TextActions.openUrl(urlInstance)).build());
        }
    }

    if (builder == null) {
        return Text.of(message);
    } else {
        if (lastMessage != null) {
            builder.append(Text.of(lastMessage.toString()));
        }
        String end = message.substring(lastEnd);
        if (end.length() > 0) {
            builder.append(Text.of(message.substring(lastEnd)));
        }
        return builder.build();
    }
}