Example usage for java.net URLConnection connect

List of usage examples for java.net URLConnection connect

Introduction

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

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:com.pentaho.ctools.cdf.require.XactionComponent.java

/**
 * ############################### Test Case 3 ###############################
 *
 * Test Case Name://from w w  w  .j  av a 2  s  .  c om
 *    Xacion
 * Description:
 *    We pretend validate the generated graphic (in an image) and if the image
 *    has a valid url.
 * Steps:
 *    1. Check if a graphic was generated
 *    2. Check the http request for the image generated
 */
@Test
public void tc3_GenerateChart_ChartIsDisplayed() {
    this.log.info("tc3_GenerateChart_ChartIsDisplayed");

    /*
     * ## Step 1
     */
    WebElement xactionElement = this.elemHelper.FindElement(driver, By.cssSelector("img"));
    assertNotNull(xactionElement);

    String attrSrc = this.elemHelper.FindElement(driver, By.cssSelector("img")).getAttribute("src");
    String attrWidth = this.elemHelper.FindElement(driver, By.cssSelector("img")).getAttribute("width");
    String attrHeight = this.elemHelper.FindElement(driver, By.cssSelector("img")).getAttribute("height");

    assertTrue(attrSrc.startsWith(baseUrl + "getImage?image=tmp_chart_admin-"));
    assertEquals(attrWidth, "500");
    assertEquals(attrHeight, "600");

    // ## Step 2
    try {
        URL url = new URL(attrSrc);
        URLConnection connection = url.openConnection();
        connection.connect();

        assertEquals(HttpStatus.SC_OK, ((HttpURLConnection) connection).getResponseCode());

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.afreire.plugins.video.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();
        InputStream is = con.getInputStream();
        //new redirected url
        url = con.getURL().toString();/*from w w  w. ja va2s . c om*/
        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, "");
        //Remove the path to the file from any location
        if (filepath.contains("www/file:")) {
            filepath = filepath.replace("www/file://", "");
        }
        // 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);

        //It uses a fixed name to optimize memory space
        File fp = new File(this.cordova.getActivity().getFilesDir() + "/" + VIDEO_FILE_NAME);
        //Always copy the file
        //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:cc.arduino.net.CustomProxySelector.java

private Proxy pacProxy(String pac, URI uri) throws IOException, ScriptException, NoSuchMethodException {
    setAuthenticator(preferences.get(Constants.PREF_PROXY_AUTO_USERNAME),
            preferences.get(Constants.PREF_PROXY_AUTO_PASSWORD));

    URLConnection urlConnection = new URL(pac).openConnection();
    urlConnection.connect();
    if (urlConnection instanceof HttpURLConnection) {
        int responseCode = ((HttpURLConnection) urlConnection).getResponseCode();
        if (responseCode != 200) {
            throw new IOException("Unable to fetch PAC file at " + pac + ". Response code is " + responseCode);
        }/*from ww  w. j ava  2s.  c o  m*/
    }
    String pacScript = new String(IOUtils.toByteArray(urlConnection.getInputStream()),
            Charset.forName("ASCII"));

    ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn");
    nashorn.getBindings(ScriptContext.ENGINE_SCOPE).put("pac", new PACSupportMethods());
    Stream.of("isPlainHostName(host)", "dnsDomainIs(host, domain)", "localHostOrDomainIs(host, hostdom)",
            "isResolvable(host)", "isInNet(host, pattern, mask)", "dnsResolve(host)", "myIpAddress()",
            "dnsDomainLevels(host)", "shExpMatch(str, shexp)").forEach((fn) -> {
                try {
                    nashorn.eval("function " + fn + " { return pac." + fn + "; }");
                } catch (ScriptException e) {
                    throw new RuntimeException(e);
                }
            });
    nashorn.eval(pacScript);
    String proxyConfigs = callFindProxyForURL(uri, nashorn);
    return makeProxyFrom(proxyConfigs);
}

From source file:org.artifactory.cli.test.TestCli.java

private void importFromTemp(File importFrom) throws Exception {
    cleanOptions();//from  w  ww  .j  av a2  s  .c  o  m
    ArtAdmin.main(new String[] { "import", importFrom.getAbsolutePath(), "--server", "localhost:8080",
            "--syncImport", "--username", "admin", "--password", "password" });
    for (MdToFind mdPath : mdExported) {
        String url = "http://localhost:8080/artifactory" + mdPath.uri;
        URLConnection urlConnection = new URL(url).openConnection();
        urlConnection.connect();
        //Assert.assertEquals(urlConnection.getContentLength(), mdPath.imported.length(), "md "+mdPath.uri+" not the same than "+mdPath.imported.getAbsolutePath());
        assertTrue(urlConnection.getContentType().contains("xml"), "URL " + url + " is not xml");
    }
}

From source file:se.blinfo.session.client.SessionClient.java

private String call(String path) {
    URL sessionServiceUrl;//  w w w . j a va2  s.  c om
    try {
        sessionServiceUrl = new URL(baseUrl + path);
        URLConnection yc;
        try {
            yc = sessionServiceUrl.openConnection();
            yc.setConnectTimeout(5 * 1000); //5 sekunder
            yc.setReadTimeout(5 * 1000);
            yc.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
            String response = in.readLine();
            in.close();
            return response;
        } catch (IOException ex) {
            Logger.getLogger(SessionClient.class.getName()).log(Level.SEVERE, "Kunde inte hmta data", ex);
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(SessionClient.class.getName()).log(Level.SEVERE, "Ogiltig url", ex);
    }
    return "";
}

From source file:com.moust.cordova.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();
        InputStream is = con.getInputStream();
        //new redirected url
        url = con.getURL().toString();// w  w w.j  av a2  s.c o m
        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, "");
        //Remove the path to the file from any location
        if (filepath.contains("www/file:")) {
            filepath = filepath.replace("www/file://", "");
        }
        // 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);

        //It uses a fixed name to optimize memory space
        File fp = new File(this.cordova.getActivity().getFilesDir() + "/" + VIDEO_FILE_NAME);

        //Always copy the file
        //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:com.almunt.jgcaap.systemupdater.DownloadService.java

@Override
protected void onHandleIntent(Intent intent) {
    String urlToDownload = "http://download.jgcaap.xyz/files/oneplusone/cm-13.0/"
            + intent.getStringExtra("url");
    filename = intent.getStringExtra("url");
    String newfilename = filename.replace("zip", "temp");
    ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
    try {/*from   w  w w .  j  a v  a  2s  .  co m*/
        URL url = new URL(urlToDownload);
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        int fileLength = connection.getContentLength();
        // download the file
        InputStream input = new BufferedInputStream(connection.getInputStream());
        File tempDir = new File(Environment.getExternalStorageDirectory() + "/JgcaapUpdates/temp/");
        tempDir.mkdir();
        //make a folder for downloading files
        OutputStream output = new FileOutputStream(
                Environment.getExternalStorageDirectory() + "/JgcaapUpdates/temp/" + newfilename);
        byte data[] = new byte[1024];
        long total = 0;
        int count;
        File temp = new File(Environment.getExternalStorageDirectory() + "/JgcaapUpdates/temp/nd");
        //temp file is created in case of an error
        while ((count = input.read(data)) != -1 && continuedownload) {
            total += count;
            // publishing the progress....
            Bundle resultData = new Bundle();
            resultData.putInt("progress", (int) total);
            resultData.putInt("total", fileLength);
            resultData.putString("filename", filename);
            resultData.putBoolean("error", false);
            receiver.send(UPDATE_PROGRESS, resultData);
            output.write(data, 0, count);
            if (temp.exists()) {
                continuedownload = false;
                temp.delete();
            }
        }
        output.flush();
        output.close();
        input.close();
    } catch (IOException e) {
        System.out.println(e.getMessage());
        Bundle resultData = new Bundle();
        resultData.putInt("progress", 0);
        resultData.putInt("total", 1);
        resultData.putString("filename", filename);
        resultData.putBoolean("error", true);
        resultData.putString("errordetails", e.getMessage());
        receiver.send(UPDATE_PROGRESS, resultData);
    }
    String dir = Environment.getExternalStorageDirectory() + File.separator + "JgcaapUpdates";
    // copy downloaded file if download is successful
    if (continuedownload) {
        try {
            if (new File(Environment.getExternalStorageDirectory() + "/JgcaapUpdates/temp/" + newfilename)
                    .length() > 1000)
                copy(new File(Environment.getExternalStorageDirectory() + "/JgcaapUpdates/temp/" + newfilename),
                        new File(Environment.getExternalStorageDirectory() + "/JgcaapUpdates/" + filename));

        } catch (IOException e) {
            e.printStackTrace();
        }
        Bundle resultData = new Bundle();
        resultData.putInt("progress", 100);
        receiver.send(UPDATE_PROGRESS, resultData);
    }
    //clear the temporary folder
    File deletefolder = new File(dir + "/temp");
    if (deletefolder.exists()) {
        File[] contents = deletefolder.listFiles();
        if (contents != null) {
            for (File f : contents) {
                f.delete();
            }
        }
    }
    deletefolder.delete();
}

From source file:com.pentaho.ctools.cdf.ExecuteXactionComponent.java

/**
 * ############################### Test Case 3 ###############################
 *
 * Test Case Name://from  ww w . jav a  2 s .  com
 *    Execute Xacion
 * Description:
 *    We pretend validate the generated chart (in an image) and if the image
 *    has a valid url.
 * Steps:
 *    1. Click to generate chart
 *    2. Check if a chart was generated
 *    3. Check the http request for the image generated
 */
@Test
public void tc3_PressToGenerateChart_ChartIsDisplayed() {
    // ## Step 1
    final String buttonName = this.elemHelper.WaitForElementPresentGetText(driver, By.xpath("//button/span"));
    assertEquals("Execute XAction", buttonName);
    //Click in button
    this.elemHelper.FindElement(driver, By.xpath("//button")).click();

    // ## Step 1
    wait.until(ExpectedConditions.presenceOfElementLocated(By.id("fancybox-content")));
    driver.switchTo().frame("fancybox-frame");
    //Check the title
    final String chartTitle = this.elemHelper.WaitForElementPresentGetText(driver,
            By.xpath("//table/tbody/tr/td"));
    assertEquals("Action Successful", chartTitle);
    //Check for the displayed image
    final WebElement xactionElement = this.elemHelper.FindElement(driver, By.cssSelector("img"));
    assertNotNull(xactionElement);

    final String attrSrc = xactionElement.getAttribute("src");
    final String attrWidth = xactionElement.getAttribute("width");
    final String attrHeight = xactionElement.getAttribute("height");

    assertTrue(attrSrc.startsWith(baseUrl + "getImage?image=tmp_chart_admin-"));
    assertEquals(attrWidth, "500");
    assertEquals(attrHeight, "600");

    // ## Step 3
    try {
        final URL url = new URL(attrSrc);
        final URLConnection connection = url.openConnection();
        connection.connect();

        assertEquals(HttpStatus.SC_OK, ((HttpURLConnection) connection).getResponseCode());
    } catch (final Exception ex) {
        this.log.error(ex.getMessage());
    }

    //Close pop-up window
    driver.switchTo().defaultContent();
    this.elemHelper.FindElement(driver, By.id("fancybox-close")).click();
    this.elemHelper.WaitForElementInvisibility(driver, By.id("fancybox-content"));
    assertNotNull(this.elemHelper.FindElement(driver, By.xpath("//button")));
}

From source file:com.android.calculator2.BitmapTask.java

private Bitmap getImageBitmap(String url) {
    Bitmap bitmap = null;/*from w  w  w  .java2s.  c o  m*/

    if (url != null && !"".equals(url)) {
        try {
            URL aURL = new URL(url);
            URLConnection conn = aURL.openConnection();
            conn.connect();

            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bitmap = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();

            cacheBitmap(mImageView.getContext(), bitmap, url);
        } catch (IOException e) {
            Log.e(TAG, "Error getting bitmap from url " + url, e);
        }
    }

    return bitmap;
}

From source file:de.damdi.fitness.activity.settings.sync.WgerImageDownloader.java

/**
 * /*from  w w  w.  ja v  a2 s  .c o  m*/
 * @param urlToDownload
 *            the url
 * @return the name of the downloaded image. This name can be different from
 *         the original name if there's already a file with the same name.
 */
private String downloadImageToSyncedImagesFolder(String urlToDownload) {
    try {
        URL url = new URL(urlToDownload);
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100%
        // progress bar
        int fileLength = connection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(url.openStream());

        // create output folder
        String outputFolder = mContext.getFilesDir().toString() + "/" + IDataProvider.SYNCED_IMAGES_FOLDER;
        (new File(outputFolder)).mkdir();
        String imageName = new File(urlToDownload).getName();
        String outputPath = outputFolder + "/" + imageName;

        // skip files that already exist
        if ((new File(outputPath)).exists()) {
            Log.e(TAG, "already such a file: " + outputPath);
            Log.e(TAG, "Will SKIP this file.");
            return imageName;
        }
        OutputStream output = new FileOutputStream(outputPath);

        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            Bundle resultData = new Bundle();
            resultData.putInt("progress", (int) (total * 100 / fileLength));
            // receiver.send(UPDATE_PROGRESS, resultData);
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();

        return imageName;
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}