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.tonbeller.wcf.format.FormatterFactory.java

private static void fillFormatter(Formatter formatter, Locale locale, URL configXml) {

    if (locale == null)
        locale = Locale.getDefault();

    URL rulesXml = Formatter.class.getResource("rules.xml");
    Digester digester = DigesterLoader.createDigester(rulesXml);
    digester.setValidating(false);//from w w  w  . jav a2 s .  c o  m
    digester.push(formatter);
    try {
        digester.parse(new InputSource(configXml.toExternalForm()));
    } catch (IOException e) {
        logger.error("exception caught", e);
        throw new SoftException(e);
    } catch (SAXException e) {
        logger.error("exception caught", e);
        throw new SoftException(e);
    }
    formatter.setLocale(locale);
}

From source file:com.github.robozonky.installer.RoboZonkyInstallerListener.java

static CommandLinePart prepareEmailConfiguration() {
    if (!Boolean.valueOf(Variables.IS_EMAIL_ENABLED.getValue(DATA))) {
        return new CommandLinePart();
    }//from  w  w  w .  j  av  a 2  s .c om
    try {
        final URL url = getEmailConfiguration();
        return new CommandLinePart().setOption("-i", url.toExternalForm());
    } catch (final Exception ex) {
        throw new IllegalStateException("Failed writing e-mail configuration.", ex);
    }
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.file.RemoteFileReader.java

public static InputStream getInputStream(URL url, String user, String password)
        throws HttpException, IOException {
    InputStream inputStream;//ww  w . j a v  a 2 s. c o  m
    if (StringUtils.isEmpty(user) && StringUtils.isEmpty(password)) {
        inputStream = url.openConnection().getInputStream();
    } else {
        HttpMethod getMethod = httpGet(url.toExternalForm(), user, password);
        inputStream = getMethod.getResponseBodyAsStream();
    }
    return inputStream;
}

From source file:net.line2soft.preambul.utils.Network.java

/**
 * Downloads a file from the Internet//from  w w  w  .  j av a 2s. co  m
 * @param address The URL of the file
 * @param dest The destination directory
 * @return The queried file
 * @throws IOException HTTP connection error, or writing error
 */
public static File download(URL address, File dest) throws IOException {
    File result = null;
    InputStream in = null;
    BufferedOutputStream out = null;
    //Open streams
    try {
        HttpGet httpGet = new HttpGet(address.toExternalForm());
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 4000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        httpClient.setParams(httpParameters);
        HttpResponse response = httpClient.execute(httpGet);

        //Launch streams for download
        in = new BufferedInputStream(response.getEntity().getContent());
        String filename = address.getFile().substring(address.getFile().lastIndexOf("/") + 1);
        File tmp = new File(dest.getPath() + File.separator + filename);
        out = new BufferedOutputStream(new FileOutputStream(tmp));

        //Test if connection is OK
        if (response.getStatusLine().getStatusCode() / 100 == 2) {
            //Download and write
            try {
                int byteRead = in.read();
                while (byteRead >= 0) {
                    out.write(byteRead);
                    byteRead = in.read();
                }
                result = tmp;
            } catch (IOException e) {
                throw new IOException("Error while writing file: " + e.getMessage());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("Error while downloading: " + e.getMessage());
    } finally {
        //Close streams
        if (out != null) {
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }
    return result;
}

From source file:com.tc.util.ProductInfo.java

static InputStream getData(String name) {
    CodeSource codeSource = ProductInfo.class.getProtectionDomain().getCodeSource();
    if (codeSource != null && codeSource.getLocation() != null) {
        URL source = codeSource.getLocation();

        if (source.getProtocol().equals("file") && source.toExternalForm().endsWith(".jar")) {
            URL res;/*from w ww.  ja  v  a 2  s .co m*/
            try {
                res = new URL("jar:" + source.toExternalForm() + "!" + name);
                InputStream in = res.openStream();
                if (in != null) {
                    return in;
                }
            } catch (MalformedURLException e) {
                throw new AssertionError(e);
            } catch (IOException e) {
                // must not be embedded in this jar -- resolve via loader path
            }
        } else if (source.getProtocol().equals("file") && (new File(source.getPath()).isDirectory())) {
            File local = new File(source.getPath(), name);

            if (local.isFile()) {
                try {
                    return new FileInputStream(local);
                } catch (FileNotFoundException e) {
                    throw new AssertionError(e);
                }
            }
        }
    }

    return ProductInfo.class.getResourceAsStream(name);
}

From source file:de.nava.informa.parsers.FeedParser.java

/**
 * Parse feed presented by file and build channel.
 *
 * @param cBuilder specific channel builder to use.
 * @param aFile    file to read data from.
 * @return parsed channel.//from   www .j a  v a  2s .  c o  m
 * @throws IOException    if IO errors occur.
 * @throws ParseException if parsing is not possible.
 */
public static ChannelIF parse(ChannelBuilderIF cBuilder, File aFile) throws IOException, ParseException {
    URL aURL;
    try {
        aURL = aFile.toURI().toURL();
    } catch (java.net.MalformedURLException e) {
        throw new IOException("File " + aFile + " had invalid URL representation.");
    }
    return parse(cBuilder, new InputSource(aURL.toExternalForm()), aURL);
}

From source file:net.lightbody.bmp.proxy.jetty.util.Resource.java

/** Construct a resource from a url.
 * @param url A URL.//from   w  w  w .  j ava 2  s.c o  m
 * @return A Resource object.
 */
public static Resource newResource(URL url) throws IOException {
    if (url == null)
        return null;

    String urls = url.toExternalForm();
    if (urls.startsWith("file:")) {
        try {
            FileResource fileResource = new FileResource(url);
            return fileResource;
        } catch (Exception e) {
            log.debug(LogSupport.EXCEPTION, e);
            return new BadResource(url, e.toString());
        }
    } else if (urls.startsWith("jar:file:")) {
        return new JarFileResource(url);
    } else if (urls.startsWith("jar:")) {
        return new JarResource(url);
    }

    return new URLResource(url, null);
}

From source file:com.offbynull.voip.ui.UiWebRegion.java

public static UiWebRegion create(Bus busFromGateway, Bus busToGateway) {
    UiWebRegion ret = new UiWebRegion(busFromGateway, busToGateway);

    URL resource = ret.getClass().getResource("/index.html");
    Validate.validState(resource != null); // should never happen, sanity check

    String mainPageLink = resource.toExternalForm();

    ret.webEngine.getLoadWorker().stateProperty().addListener((ov, oldState, newState) -> {
        if (newState == State.SUCCEEDED) {
            JSObject win = (JSObject) ret.webEngine.executeScript("window");
            win.setMember("messageSender", ret.new JavascriptToGatewayBridge());

            busToGateway.add(new UiAction(new ReadyAction(false)));
        } else if (newState == State.CANCELLED || newState == State.FAILED) {
            busToGateway.add(new UiAction(new ReadyAction(true)));
        }/*from  w w w .  ja v  a 2  s  .com*/
    });
    ret.webEngine.load(mainPageLink);

    // This block makes sure to kill the incoming message pump if this webregion is removed from its parent, and (re)starts it if its
    // added
    //
    // NOTE: CANNOT USE PARENTPROPERTY -- PARENTPROPERTY ALWAYS RETURNS NULL FOR WHATEVER REASON
    ret.sceneProperty().addListener((observable, oldValue, newValue) -> {
        ret.lock.lock();
        try {
            if (oldValue != null) {
                ret.incomingMessagePumpThread.interrupt();
                ret.incomingMessagePumpThread.join();
                ret.incomingMessagePumpThread = null;
            }

            if (newValue != null) {
                Thread thread = new Thread(ret.new GatewayToJavascriptPump());
                thread.setDaemon(true);
                thread.setName(UiWebRegion.class.getSimpleName() + "-GatewayToJavascriptPump");
                thread.start();
                ret.incomingMessagePumpThread = thread;
            }
        } catch (InterruptedException ex) {
            throw new IllegalStateException(ex);
        } finally {
            ret.lock.unlock();
        }
    });

    return ret;
}

From source file:net.sourceforge.fenixedu.util.report.ReportsUtils.java

static private void addFont(final Map<FontKey, PdfFont> result, final String fontName, final String pdfFontName,
        final String baseFont) {
    final URL url = ReportsUtils.class.getClassLoader().getResource("fonts/" + pdfFontName);
    result.put(new FontKey(fontName, false, false), new PdfFont(url.toExternalForm(), baseFont, true));
}

From source file:com.microsoft.tfs.core.clients.workitem.internal.files.AttachmentUpDownHelper.java

public static void download(final URL attachmentUrl, final File localTarget,
        final TFSTeamProjectCollection connection) throws DownloadException {
    final TaskMonitor taskMonitor = TaskMonitorService.getTaskMonitor();
    final HttpClient httpClient = connection.getHTTPClient();
    final GetMethod method = new GetMethod(attachmentUrl.toExternalForm());
    boolean cancelled = false;
    OutputStream outputStream = null;

    try {/*www.  j  a va2s. co  m*/
        final int statusCode = httpClient.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            throw new DownloadException(MessageFormat.format(
                    Messages.getString("AttachmentUpDownHelper.ServerReturnedHTTPStatusFormat"), //$NON-NLS-1$
                    Integer.toString(statusCode)));
        }

        taskMonitor.begin(Messages.getString("AttachmentUpDownHelper.Downloading"), //$NON-NLS-1$
                computeTaskSize(method.getResponseContentLength()));

        final InputStream input = method.getResponseBodyAsStream();
        outputStream = new FileOutputStream(localTarget);
        outputStream = new BufferedOutputStream(outputStream);

        final byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE];
        int len;
        long totalBytesDownloaded = 0;

        while ((len = input.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
            totalBytesDownloaded += len;
            taskMonitor.worked(1);
            taskMonitor.setCurrentWorkDescription(MessageFormat.format(
                    Messages.getString("AttachmentUpDownHelper.DownloadedCountBytesFormat"), //$NON-NLS-1$
                    totalBytesDownloaded));
            if (taskMonitor.isCanceled()) {
                cancelled = true;
                break;
            }
            Thread.sleep(10);
        }

    } catch (final Exception ex) {
        throw new DownloadException(ex);
    } finally {
        method.releaseConnection();
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (final IOException e) {
            }
        }
    }

    if (cancelled) {
        localTarget.delete();
    }
}