Example usage for java.net URLConnection getInputStream

List of usage examples for java.net URLConnection getInputStream

Introduction

In this page you can find the example usage for java.net URLConnection getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:it.openutils.mgnlaws.magnolia.AmazonMgnlServletContextListener.java

protected void initEc2(String accessKey, String secretKey, String endpoint)
        throws IOException, AmazonEc2InstanceNotFound {
    String ec2InstanceId;//from ww  w  .ja  v a2 s  .  c o m
    BufferedReader in = null;
    try {
        URL url = new URL("http://169.254.169.254/latest/meta-data/instance-id");
        URLConnection connection = url.openConnection();
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        ec2InstanceId = in.readLine();
        in.close();
    } finally {
        IOUtils.closeQuietly(in);
    }

    AmazonEC2Client client = new AmazonEC2Client(new BasicAWSCredentials(accessKey, secretKey));
    client.setEndpoint(endpoint);
    DescribeInstancesResult result = client
            .describeInstances(new DescribeInstancesRequest().withInstanceIds(ec2InstanceId));
    if (result.getReservations().size() > 0 && result.getReservations().get(0).getInstances().size() > 0) {
        ec2Instance = result.getReservations().get(0).getInstances().get(0);
        if (ec2Instance == null) {
            // should never happen
            throw new AmazonEc2InstanceNotFound(ec2InstanceId);
        }
    } else {
        throw new AmazonEc2InstanceNotFound(ec2InstanceId);
    }

    for (Tag tag : ec2Instance.getTags()) {
        if (StringUtils.startsWith(tag.getKey(), "__")) {
            System.setProperty(StringUtils.substring(tag.getKey(), 2), tag.getValue());
        } else {
            System.setProperty("aws.instance." + tag.getKey(), tag.getValue());
        }
    }

    String clusterId = System.getProperty(EC2_TAG_CLUSTERID);
    if (StringUtils.isNotEmpty(clusterId)) {
        System.setProperty(JR_CLUSTERID, clusterId);
    }
}

From source file:com.omniburst.winetv.android.browser.VideoProvider.java

protected JSONObject parseUrl(String urlString) {
    InputStream is = null;//from   w  ww  . j ava 2s.co m
    try {
        java.net.URL url = new java.net.URL(urlString);
        URLConnection urlConnection = url.openConnection();
        is = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(urlConnection.getInputStream(), "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String xml = sb.toString();
        JSONObject obj = XML.toJSONObject(xml);
        return obj;
    } catch (Exception e) {
        Log.d(TAG, "Failed to parse the json for media list", e);
        return null;
    } finally {
        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:com.puppycrawl.tools.checkstyle.PackageNamesLoaderTest.java

@Test
@SuppressWarnings("unchecked")
public void testPackagesWithIoException() throws Exception {

    final URLConnection mockConnection = Mockito.mock(URLConnection.class);
    when(mockConnection.getInputStream()).thenReturn(null);

    URL url = getMockUrl(mockConnection);

    Enumeration<URL> enumer = (Enumeration<URL>) mock(Enumeration.class);
    when(enumer.hasMoreElements()).thenReturn(true);
    when(enumer.nextElement()).thenReturn(url);

    ClassLoader classLoader = mock(ClassLoader.class);
    when(classLoader.getResources("checkstyle_packages.xml")).thenReturn(enumer);

    try {/*from   w w  w.  j  a v  a2  s . c  o  m*/
        PackageNamesLoader.getPackageNames(classLoader);
        fail();
    } catch (CheckstyleException ex) {
        assertTrue(ex.getCause() instanceof IOException);
        assertNotEquals("unable to get package file resources", ex.getMessage());
    }
}

From source file:com.sammyun.controller.console.StatisticsController.java

/**
 * //  w  w w .  ja va2s.  c  o m
 */
@RequestMapping(value = "/setting", method = RequestMethod.POST)
public String setting(@RequestParam(defaultValue = "false") Boolean isEnabled,
        RedirectAttributes redirectAttributes) {
    Setting setting = SettingUtils.get();
    if (isEnabled) {
        //if (StringUtils.isEmpty(setting.getCnzzSiteId()) || StringUtils.isEmpty(setting.getCnzzPassword()))
        {
            String domain = setting.getSiteUrl()
                    .replaceAll("(^[\\s\\S]*?[^a-zA-Z0-9-.]+)|([^a-zA-Z0-9-.][\\s\\S]*$)", "");
            try {
                String createAccountUrl = "http://intf.cnzz.com/user/companion/shopxx.php?domain=" + domain
                        + "&key=" + DigestUtils.md5Hex(domain + "Lfg4uP0H");
                URLConnection urlConnection = new URL(createAccountUrl).openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String line = null;
                while ((line = in.readLine()) != null) {
                    if (line.contains("@")) {
                        break;
                    }
                }
                if (line != null) {
                    //setting.setCnzzSiteId(StringUtils.substringBefore(line, "@"));
                    //setting.setCnzzPassword(StringUtils.substringAfter(line, "@"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //setting.setIsCnzzEnabled(isEnabled);
    SettingUtils.set(setting);
    cacheService.clear();
    addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
    return "redirect:setting.ct";
}

From source file:XMLResourceBundleControl.java

public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader,
        boolean reload) throws IllegalAccessException, InstantiationException, IOException {

    if ((baseName == null) || (locale == null) || (format == null) || (loader == null)) {
        throw new NullPointerException();
    }/*from   www . j a  va 2s . co m*/
    ResourceBundle bundle = null;
    if (!format.equals(XML)) {
        return null;
    }

    String bundleName = toBundleName(baseName, locale);
    String resourceName = toResourceName(bundleName, format);
    URL url = loader.getResource(resourceName);
    if (url == null) {
        return null;
    }
    URLConnection connection = url.openConnection();
    if (connection == null) {
        return null;
    }
    if (reload) {
        connection.setUseCaches(false);
    }
    InputStream stream = connection.getInputStream();
    if (stream == null) {
        return null;
    }
    BufferedInputStream bis = new BufferedInputStream(stream);
    bundle = new XMLResourceBundle(bis);
    bis.close();

    return bundle;
}

From source file:com.github.beat.signer.pdf_signer.TSAClient.java

private byte[] getResponse(URLConnection connection) throws IOException {
    InputStream input = null;/*  w  ww.  j  a va  2  s  . c om*/
    try {
        input = connection.getInputStream();
        return IOUtils.toByteArray(input);
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:com.dawsonloudon.videoplayer.VideoPlayer.java

private void playVideo(String url) throws IOException {
    if (url.contains("bit.ly/") || url.contains("goo.gl/") || url.contains("tinyurl.com/")
            || url.contains("youtu.be/")) {
        //support for google / bitly / tinyurl / youtube shortens
        URLConnection con = new URL(url).openConnection();
        con.connect();/*from   www . jav  a  2s  .co m*/
        InputStream is = con.getInputStream();
        //new redirected url
        url = con.getURL().toString();
        is.close();
    }

    // Create URI
    Uri uri = Uri.parse(url);

    Intent intent = null;
    // Check to see if someone is trying to play a YouTube page.
    if (url.contains(YOU_TUBE)) {
        // If we don't do it this way you don't have the option for youtube
        uri = Uri.parse("vnd.youtube:" + uri.getQueryParameter("v"));
        if (isYouTubeInstalled()) {
            intent = new Intent(Intent.ACTION_VIEW, uri);
        } else {
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=com.google.android.youtube"));
        }
    } else if (url.contains(ASSETS)) {
        // get file path in assets folder
        String filepath = url.replace(ASSETS, "");
        // get actual filename from path as command to write to internal storage doesn't like folders
        String filename = filepath.substring(filepath.lastIndexOf("/") + 1, filepath.length());

        // Don't copy the file if it already exists
        File fp = new File(this.cordova.getActivity().getFilesDir() + "/" + filename);
        if (!fp.exists()) {
            this.copy(filepath, filename);
        }

        // change uri to be to the new file in internal storage
        uri = Uri.parse("file://" + this.cordova.getActivity().getFilesDir() + "/" + filename);

        // Display video player
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "video/*");
    } else {
        // Display video player
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "video/*");
    }

    this.cordova.getActivity().startActivity(intent);
}

From source file:fi.kinetik.android.currencies.spi.openexchange.OpenExchangeRatesSpi.java

public void loadData(ArrayList<ContentProviderOperation> operations) throws IOException, RatesSpiException {

    final URLConnection connection = OpenExchangeRatesSpiFactory.sFeedURL.openConnection();

    InputStream in = null;//from   w  w w .j  a v a  2  s.  c  o  m

    try {

        in = connection.getInputStream();

        // not efficient to read the entire feed into memory but since its
        // not that big...

        JSONObject json = new JSONObject(IOUtils.toString(in, OpenExchangeRatesSpiFactory.CHARSET));

        parseRates(operations, json);

    } catch (JSONException e) {
        throw new RatesSpiException("parsing json failed", e);
    } finally {
        IOUtils.close(in);
    }
}

From source file:com.kaylerrenslow.armaDialogCreator.updater.tasks.AdcVersionCheckTask.java

@NotNull
private ReleaseInfo getLatestRelease() throws Exception {
    setStatusText("Updater.checking_for_updates");

    JSONParser parser = new JSONParser();
    URLConnection connection = new URL(versionCheckUrl).openConnection();
    InputStreamReader reader = new InputStreamReader(connection.getInputStream());

    JSONObject object = (JSONObject) parser.parse(reader);

    reader.close();/*from   w  w  w .j a v a  2 s  . co  m*/
    connection.getInputStream().close();

    return new ReleaseInfo(object);
}

From source file:eu.project.ttc.resources.DictionaryResource.java

@Override
public void load(URI resourceIdentifier) throws Exception {
    URLConnection connection = resourceIdentifier.toURL().openConnection();
    this.load(resourceIdentifier.getPath(), connection.getInputStream());
}