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.aurel.track.util.PluginUtils.java

/**
 * Gets a file with a given path relativ to classes directory from the WEB-INF
 * @param url/* w w  w  . ja v a  2 s.c o  m*/
 * @return
 */
public static File getFileFromURL(URL url) {
    File file;
    if (url == null) {
        return null;
    }
    if (url.getPath() != null) {
        file = new File(url.getPath());
        if (file.exists()) {
            //valid url
            return file;
        }
    }

    //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) {
        file = new File(uri.getPath());
        if (file.exists()) {
            return file;
        }
    }
    //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 file;
        }
    }
    return null;
}

From source file:org.bndtools.rt.repository.client.RemoteRestRepository.java

@Override
public PutResult put(InputStream inputStream, PutOptions options) throws Exception {
    URI postUri = new URI(baseUri.getScheme(), baseUri.getUserInfo(), baseUri.getHost(), baseUri.getPort(),
            baseUri.getPath() + "/bundles", null, null);

    HttpURLConnection conn = (HttpURLConnection) postUri.toURL().openConnection();
    conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM);
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);/*from   w  ww  .j ava  2  s.  com*/

    // Send the data
    byte[] buffer = new byte[1024];
    OutputStream postStream = conn.getOutputStream();
    try {
        while (true) {
            int bytesRead = inputStream.read(buffer, 0, 1024);
            if (bytesRead < 0)
                break;
            postStream.write(buffer, 0, bytesRead);
        }
        postStream.flush();
    } finally {
        IO.close(postStream);
    }

    // Read the response header
    int response = conn.getResponseCode();
    if (response < 200 || response >= 300)
        throw new Exception(String.format("Server returned error code %d", response));
    String location = conn.getHeaderField("Location");
    if (location == null)
        throw new Exception("Server did not return a Location header");

    PutResult result = new PutResult();
    result.artifact = new URI(location);
    result.digest = null;

    return result;
}

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

public String send(String request, URI endpointURL) throws TransportException {
    Service service = null;/*from  www .j  a  v  a2  s .  c o m*/
    Call call = null;
    String response = null;

    log.debug("\nRequest message:\n" + request);

    try {

        service = new Service();
        call = (Call) service.createCall();
        call.setTargetEndpointAddress(endpointURL.toURL());

        SOAPBodyElement body = new SOAPBodyElement(new ByteArrayInputStream(request.getBytes("UTF-8")));
        Object[] soapBodies = new Object[] { body };

        Vector result = (Vector) call.invoke(soapBodies);
        if (result.size() > 0) {
            response = ((SOAPBodyElement) result.elementAt(0)).getAsString();
        }
    } catch (AxisFault fault) {

        try {
            Message msg = call.getResponseMessage();
            response = msg.getSOAPEnvelope().getFirstBody().getAsString();
        } catch (Exception ex) {
            throw new TransportException(ex);
        }
    } catch (Exception ex) {
        throw new TransportException(ex);
    }

    log.debug("\nResponse message:\n" + response);

    return response;
}

From source file:org.geoserver.wms.web.data.ExternalGraphicPanel.java

/**
 * Validates the external graphic and returns a connection to the graphic.
 * If validation fails, error messages will be added to the passed form
 * // ww w. jav a 2s  .  c o m
 * @param target
 * @param form
 * @return URLConnection to the External Graphic file
 */
protected URLConnection getExternalGraphic(AjaxRequestTarget target, Form<?> form) {
    onlineResource.processInput();
    if (onlineResource.getModelObject() != null) {
        URL url = null;
        try {
            String baseUrl = baseURL(form);
            String external = onlineResource.getModelObject().toString();

            URI uri = new URI(external);
            if (uri.isAbsolute()) {
                url = uri.toURL();
                if (!external.startsWith(baseUrl)) {
                    form.warn("Recommend use of styles directory at " + baseUrl);
                }
            } else {
                WorkspaceInfo wsInfo = ((StyleInfo) getDefaultModelObject()).getWorkspace();
                if (wsInfo != null) {
                    url = new URL(ResponseUtils.appendPath(baseUrl, "styles", wsInfo.getName(), external));
                } else {
                    url = new URL(ResponseUtils.appendPath(baseUrl, "styles", external));
                }
            }

            URLConnection conn = url.openConnection();
            if ("text/html".equals(conn.getContentType())) {
                form.error("Unable to access url");
                return null; // error message back!
            }
            return conn;

        } catch (FileNotFoundException notFound) {
            form.error("Unable to access " + url);
        } catch (Exception e) {
            e.printStackTrace();
            form.error("Recommend use of styles directory at " + e);
        }
    }
    return null;
}

From source file:org.jahia.osgi.BundleStarter.java

void startInitialBundlesIfNeeded() {
    File marker = new File(deployedBundlesDir, MARKER_INITIAL_BUNDLES);
    if (!marker.exists()) {
        return;//from   w  w w .  ja  v  a2 s.c o  m
    }
    logger.info("Installing and starting initial bundles");

    // there is a timing issue somewhere in the Karaf code, sleep for 5 seconds
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        logger.error(e.getMessage(), e);
    }

    BundleContext ctx = getBundleContext();
    File startupPropsFile = new File(System.getProperty(ConfigProperties.PROP_KARAF_ETC),
            Main.STARTUP_PROPERTIES_FILE_NAME);
    org.apache.felix.utils.properties.Properties startupProps = PropertiesLoader
            .loadPropertiesOrFail(startupPropsFile);

    List<File> bundleDirs = getBundleRepos();
    ArtifactResolver resolver = new SimpleMavenResolver(bundleDirs);

    List<Bundle> bundlesToStart = new LinkedList<>();
    for (String key : startupProps.keySet()) {
        Integer startLevel = new Integer(startupProps.getProperty(key).trim());
        try {
            URI resolvedURI = resolver.resolve(new URI(key));
            Bundle b = ctx.installBundle(key, resolvedURI.toURL().openStream());
            b.adapt(BundleStartLevel.class).setStartLevel(startLevel);
            if (!BundleUtils.isFragment(b)) {
                bundlesToStart.add(b);
            }
        } catch (Exception e) {
            throw new RuntimeException("Error installing bundle listed in " + startupPropsFile + " with url: "
                    + key + " and startlevel: " + startLevel, e);
        }
    }
    for (Bundle b : bundlesToStart) {
        try {
            b.start();
        } catch (Exception e) {
            throw new RuntimeException("Error starting bundle " + b.getSymbolicName() + "/" + b.getVersion(),
                    e);
        }
    }
    logger.info("All initial bundles installed and set to start");
    FileUtils.deleteQuietly(marker);
}

From source file:eu.asterics.ape.main.APE.java

/**
 * Determins property file location (APE.properties), reads property values and overrides property values given as system property (-Dkey=value).
 * @throws IOException //from ww w.  j ava  2 s .  c o  m
 */
private void initProperties() throws IOException {
    Properties defaultProperties = new Properties();
    //Init with empty properties
    apeProperties = new APEProperties();

    try {
        //APE.properties is expected to be in the project directory
        URI apePropFileURI = ResourceRegistry.resolveRelativeFilePath(projectDir, "APE.properties").toURI();

        defaultProperties.load(new BufferedReader(new InputStreamReader(apePropFileURI.toURL().openStream())));
        Notifier.debug("defaultProperties: " + defaultProperties.toString(), null);
        apeProperties = new APEProperties(defaultProperties);
        for (Entry<Object, Object> entry : System.getProperties().entrySet()) {
            if (entry.getKey().toString().startsWith(APEProperties.APE_PROP_PREFIX)
                    || entry.getKey().toString().startsWith(APEProperties.ARE_PROP_PREFIX)) {
                //sanity check
                if (entry.getValue() == null) {
                    continue;
                }

                String propValue = entry.getValue().toString();
                if (entry.getKey().equals(P_APE_MODELS) || entry.getKey().equals(P_APE_BUILD_DIR)
                        || entry.getKey().equals(P_ARE_BASE_URI)) {
                    //if the user provided model paths via the system property and not via the properties file, we have to resolve relative paths to the current directory
                    //and not relative to the APE.projectDir location to make it more intuitive.
                    propValue = resolveURIsToCWD(entry.getValue().toString());
                }
                Notifier.debug("Overriding ApeProp[" + entry.getKey() + "]=" + propValue, null);

                apeProperties.setProperty(entry.getKey().toString(), propValue);
            }
        }
        //Also add the projectDir to the properties to be sure that the values are in sync.
        apeProperties.setProperty(P_APE_PROJECT_DIR, projectDir.getPath());

        //Now adding default models search path to APE.models property
        Notifier.debug("Adding APE.projectDir/" + Packager.CUSTOM_BIN_ARE_FOLDER
                + " as search path for model files to " + APEProperties.P_APE_MODELS, null);
        String projectDirSearchPath = ResourceRegistry
                .resolveRelativeFilePath(projectDir, Packager.CUSTOM_BIN_ARE_MODELS_FOLDER).getPath();
        apeProperties.setProperty(APEProperties.P_APE_MODELS,
                apeProperties.getProperty(APEProperties.P_APE_MODELS, "") + ";" + projectDirSearchPath);
        Notifier.info("ApeProp[" + APEProperties.P_APE_MODELS + "]="
                + apeProperties.getProperty(APEProperties.P_APE_MODELS), null);
        Notifier.debug("Final apeProperties: " + apeProperties.toString(), null);
    } catch (IOException e) {
        Notifier.error("STOPPING: Initialization of APE properties failed", e);
        throw e;
    }
}

From source file:groovyx.net.http.thirdparty.GAEClientConnection.java

public void sendRequestHeader(HttpRequest request) throws HttpException, IOException {
    try {/*  w  ww . j ava  2  s . co  m*/
        HttpHost host = route.getTargetHost();

        URI uri = new URI(host.getSchemeName() + "://" + host.getHostName()
                + ((host.getPort() == -1) ? "" : (":" + host.getPort())) + request.getRequestLine().getUri());

        this.request = new HTTPRequest(uri.toURL(), HTTPMethod.valueOf(request.getRequestLine().getMethod()),
                FetchOptions.Builder.disallowTruncate().doNotFollowRedirects());
    } catch (URISyntaxException ex) {
        throw new IOException("Malformed request URI: " + ex.getMessage(), ex);
    } catch (IllegalArgumentException ex) {
        throw new IOException("Unsupported HTTP method: " + ex.getMessage(), ex);
    }

    //     System.err.println("SEND: " + this.request.getMethod() + " " + this.request.getURL());

    for (Header h : request.getAllHeaders()) {
        //       System.err.println("SEND: " + h.getName() + ": " + h.getValue());
        this.request.addHeader(new HTTPHeader(h.getName(), h.getValue()));
    }
}

From source file:com.anrisoftware.globalpom.checkfilehash.CheckFileHash.java

private String readExpectedHash(URI hashResource) throws Exception {
    if (StringUtils.equals(hashResource.getScheme(), "md5")) {
        return hashResource.getSchemeSpecificPart();
    } else if (StringUtils.equals(hashResource.getScheme(), "sha1")) {
        return hashResource.getSchemeSpecificPart();
    } else {//from  w  ww.  ja v  a 2  s  .  com
        String line = readLines(hashResource.toURL().openStream()).get(0);
        String hash = StringUtils.split(line, SEP)[0];
        return hash;
    }
}

From source file:com.anrisoftware.globalpom.initfileparser.InitFileParserImpl.java

private InputStream openURIStream(URI uri) throws InitFileParserException {
    try {//from w ww .ja  v a  2  s.c  o  m
        return openURLStream(uri.toURL());
    } catch (MalformedURLException e) {
        throw log.openStreamError(this, e);
    }
}

From source file:mSearch.filmlisten.FilmlisteLesen.java

private InputStream getInputStreamForLocation(String source) throws IOException, URISyntaxException {
    InputStream in;/*from ww w . ja v  a2s. co  m*/
    long size = 0;
    final URI uri;
    if (source.startsWith("http")) {
        uri = new URI(source);
        //remote address for internet download
        HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        conn.setRequestProperty("User-Agent", Config.getUserAgent());
        if (conn.getResponseCode() < 400) {
            size = conn.getContentLengthLong();
        }
        in = new ProgressMonitorInputStream(conn.getInputStream(), size, new InputStreamProgressMonitor() {
            private int oldProgress = 0;

            @Override
            public void progress(long bytesRead, long size) {
                final int iProgress = (int) (bytesRead * 100 / size);
                if (iProgress != oldProgress) {
                    oldProgress = iProgress;
                    notifyProgress(uri.toASCIIString(), "Download", iProgress);
                }
            }
        });
    } else {
        //local file
        notifyProgress(source, "Download", PROGRESS_MAX);
        in = new FileInputStream(source);
    }

    return in;
}