Example usage for java.net URL openStream

List of usage examples for java.net URL openStream

Introduction

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

Prototype

public final InputStream openStream() throws java.io.IOException 

Source Link

Document

Opens a connection to this URL and returns an InputStream for reading from that connection.

Usage

From source file:net.sf.janos.util.ui.ImageUtilities.java

/**
 * Loads an image from the provided resource
 * @param resource the image to load//from   w w  w  .j a v  a 2  s .  co m
 * @return the loaded image, or null if an error occurred
 */
public static ImageData loadImageData(URL resource) {
    if (resource == null) {
        return null;
    }
    ImageData data = null;
    synchronized (IMAGE_DATA_CACHE) {
        try {
            data = IMAGE_DATA_CACHE.get(resource);
            return data;
        } catch (NoSuchKeyException e) {
            // fall through
        }
    }
    InputStream is = null;
    try {
        is = resource.openStream();
        data = new ImageData(is);
        synchronized (IMAGE_DATA_CACHE) {
            IMAGE_DATA_CACHE.put(resource, data);
        }
    } catch (FileNotFoundException e) {
        Log log = LogFactory.getLog(ImageUtilities.class);
        log.debug("Image file " + resource + " does not exist");
        synchronized (IMAGE_DATA_CACHE) {
            IMAGE_DATA_CACHE.put(resource, null);
        }
    } catch (IOException e) {
        Log log = LogFactory.getLog(ImageUtilities.class);
        log.error("Couldn't load image from " + resource, e);
    } finally {
        try {
            is.close();
        } catch (Exception e) {
        }
    }
    return data;
}

From source file:marytts.tools.install.LicenseRegistry.java

private static void downloadLicense(URL licenseURL) {

    assert remote2local != null;
    File downloadDir = new File(System.getProperty("mary.downloadDir", "."));
    String filename = licenseURL.toString().replace('/', '_').replace(':', '_');
    File licenseFile = new File(downloadDir, filename);
    System.out.println("Downloading license from " + licenseURL.toString());
    try (FileOutputStream out = new FileOutputStream(licenseFile); InputStream in = licenseURL.openStream()) {
        IOUtils.copy(in, out);/*w w w  .j  a  v  a2  s  . c om*/
    } catch (IOException e) {
        System.err.println("Cannot download license from " + licenseURL.toString());
        e.printStackTrace();
    }

    // Now we need to update remote2local and write an updated license-index.txt:
    remote2local.put(licenseURL, filename);
    saveIndex();

}

From source file:com.aurel.track.admin.customize.lists.BlobBL.java

/**
 * This method returns the iconKey content in byte array.In case of not founds returns the default image content. 
 * @param iconKey//from   ww  w .  java  2  s. c  om
 * @param iconName
 * @param inline
 * @param defaultIconPath
 * @return
 */
public static byte[] getAvatarInByteArray(Integer iconKey, String iconName, boolean inline,
        String defaultIconPath) {
    byte[] imageContent = null;
    if (iconKey != null) {
        TBLOBBean blobBean = loadByPrimaryKey(iconKey);
        if (blobBean != null) {
            imageContent = blobBean.getBLOBValue();
        }
    }
    if (defaultIconPath != null) {
        if (imageContent == null || imageContent.length == 0) {
            try {
                URL defaultIconURL = ApplicationBean.getInstance().getServletContext()
                        .getResource(defaultIconPath);
                imageContent = IOUtils.toByteArray(defaultIconURL.openStream());
            } catch (IOException e) {
                LOGGER.info("Getting the icon content for " + defaultIconPath + " from URL failed with "
                        + e.getMessage());
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                }
            }
        }
        if (imageContent == null || imageContent.length == 0) {
            InputStream is = ApplicationBean.getInstance().getServletContext()
                    .getResourceAsStream(defaultIconPath);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                byte[] buf = new byte[1024];
                int numBytesRead;
                while ((numBytesRead = is.read(buf)) != -1) {
                    output.write(buf, 0, numBytesRead);
                }
                imageContent = output.toByteArray();
                output.close();
                is.close();
            } catch (IOException e) {
                LOGGER.info("Getting the icon content for " + defaultIconPath
                        + " as resource stream failed with " + e.getMessage());
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                }
            }
        }
    }
    return imageContent;
}

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

/**
 * Gets the PropertiesConfiguration for a property file from servlet context
 * @param servletContext/*  w ww  .  j ava2s  . c  om*/
 * @param pathWithinContext
 * @param propFile
 * @return
 * @throws ServletException
 */
public static PropertiesConfiguration loadServletContextPropFile(ServletContext servletContext,
        String pathWithinContext, String propFile) throws ServletException {
    PropertiesConfiguration propertiesConfiguration = null;
    InputStream in = null;
    URL propFileURL = null;
    try {
        if (servletContext != null && pathWithinContext != null) {
            if (!pathWithinContext.startsWith("/")) {
                pathWithinContext = "/" + pathWithinContext;
            }
            if (!pathWithinContext.endsWith("/")) {
                pathWithinContext = pathWithinContext + "/";
            }
            propFileURL = servletContext.getResource(pathWithinContext + propFile);
            in = propFileURL.openStream();
            propertiesConfiguration = new PropertiesConfiguration();
            propertiesConfiguration.load(in);
            in.close();
        }
    } catch (Exception e) {
        LOGGER.error("Could not read " + propFile + " from servlet context " + propFileURL == null ? ""
                : propFileURL.toExternalForm() + ". Exiting. " + e.getMessage());
        throw new ServletException(e);
    }
    return propertiesConfiguration;
}

From source file:com.isa.utiles.Utiles.java

public static void downloadFile(String linkDescarga, String rutaDestino)
        throws MalformedURLException, IOException {

    URL urlFile = new URL(linkDescarga);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream in = new BufferedInputStream(urlFile.openStream());

    byte[] buf = new byte[1024];
    int n = 0;//w  w w  .jav  a 2 s. c  om
    while (-1 != (n = in.read(buf))) {
        out.write(buf, 0, n);
    }
    out.close();
    in.close();

    /*
    byte[] response = out.toByteArray();
    FileOutputStream fos = new FileOutputStream(rutaDestino);
    fos.write(response);
    fos.close();
    */

    File file = new File(rutaDestino);
    file.setWritable(true);
    file.setReadable(true);

    BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
    bw.write(out.toString());
    bw.close();
}

From source file:com.inamik.template.util.TemplateConfigUtil.java

/**
 * readTemplateLibConfig w/URL - Read a template library xml
 * configuration from a URL./*  w  ww  .  j a  v a 2  s.c  om*/
 * <p>
 * This is a convenience method and is equivelent to:
 * <p>
 * &nbsp;&nbsp; <code>readTeplateLibConfig(url.oipenStream())</code>
 *
 * @param url The URL to read.
 * @return A template library configuration suitable for adding to a
 *         template engine configuration.
 * @throws IOException
 * @throws TemplateException
 * @throws NullPointerException if <code>url == null</code>
 *
 * @see #readTemplateLibConfig(InputStream)
 * @see TemplateEngineConfig
 */
public static TemplateLibConfig readTemplateLibConfig(final URL url) throws IOException, TemplateException {
    return readTemplateLibConfig(url.openStream());
}

From source file:com.netflix.config.ConfigurationManager.java

/**
 * Load properties from resource file into the system wide configuration
 * @param path path of the resource/*from w  w  w.  j a v  a 2 s  . c o  m*/
 * @throws IOException
 */
public static void loadPropertiesFromResources(String path) throws IOException {
    if (instance == null) {
        instance = getConfigInstance();
    }
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL url = loader.getResource(path);
    if (url == null) {
        throw new IOException("Cannot locate " + path + " as a classpath resource.");
    }
    Properties props = new Properties();
    InputStream fin = url.openStream();
    props.load(fin);
    fin.close();
    if (instance instanceof AggregatedConfiguration) {
        String name = getConfigName(url);
        ConcurrentMapConfiguration config = new ConcurrentMapConfiguration();
        config.loadProperties(props);
        ((AggregatedConfiguration) instance).addConfiguration(config, name);
    } else {
        ConfigurationUtils.loadProperties(props, instance);
    }
}

From source file:net.ontopia.utils.TestFileUtils.java

public static void transferTestInputDirectory(ResourcesDirectoryReader directoryReader, String path)
        throws IOException {
    for (URL resource : directoryReader.getResources()) {
        String relative = resource.getFile();
        relative = relative.substring(relative.lastIndexOf(path));
        File file = new File(new File(getTestdataOutputDirectory()), relative);
        file.getParentFile().mkdirs();//from w  w w.  j av a 2s  .  c o m
        try (InputStream in = resource.openStream(); OutputStream out = new FileOutputStream(file)) {
            IOUtils.copy(in, out);
        }
    }
}

From source file:name.yumao.douyu.http.PlaylistDownloader.java

private static void downloadInternal(URL segmentUrl) {

    FileOutputStream out = null;/*from  w w  w.  j  av  a 2  s . com*/
    InputStream is = null;
    try {
        byte[] buffer = new byte[512 * 1024];

        is = segmentUrl.openStream();

        if (outFile.equals("")) {
            //                Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
            //                  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("^yyyy-MM-dd^HH-mm-ss");
            //         //   
            //                   outFile = "record"+File.separator+num+File.separator+simpleDateFormat.format(calendar.getTime());
            outFile = getPath();
        }

        File file = new File(outFile);

        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        Date now = new Date();
        System.out.println(now + " " + roomnum + "?: "
                + file.length() / (1024 * 1024L) + "m");

        // System.out.println("Downloading size:"+file.length() / (1024 *
        // 1024L) +"m\r");

        if (file.length() > 1024 * 1024L * Config.SIZE) {
            outFile = getPath();
            file = new File(outFile);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

        }
        out = new FileOutputStream(outFile, file.exists());

        // System.out.println(":"+segmentUrl+"\r");

        int read;

        while ((read = is.read(buffer)) >= 0) {
            out.write(buffer, 0, read);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.flush();
                out.close();
            }

            if (is != null)
                is.close();

        } catch (IOException e) {
            logger.info(":" + segmentUrl + e.getMessage());
            e.printStackTrace();
        }

    }
}

From source file:net.rptools.lib.FileUtil.java

public static byte[] getBytes(URL url) throws IOException {
    InputStream is = null;/*w w  w . j av a  2 s. co m*/
    try {
        is = url.openStream();
        return IOUtils.toByteArray(is);
    } finally {
        IOUtils.closeQuietly(is);
    }
}