Example usage for java.net URLConnection getContent

List of usage examples for java.net URLConnection getContent

Introduction

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

Prototype

public Object getContent() throws IOException 

Source Link

Document

Retrieves the contents of this URL connection.

Usage

From source file:org.sakaiproject.kernel.messaging.email.EmailMessageListener.java

/**
 * Sets the content of the mime part using the content of the email message.
 *
 * @param mimePart//from  w w  w. ja va  2  s . c o m
 *          To where the content should be set.
 * @param email
 *          From where the content should be retrieved.
 * @throws IOException
 *           If the content is a URL and there is a problem opening a stream
 *           to it.
 * @throws MessagingException
 *           If there is a problem setting the content to the mime part.
 */
private void setContent(MimePart mimePart, Message email) throws IOException, MessagingException {
    Object content = null;
    if (email.isBodyText()) {
        content = email.getText();
    } else {
        URL url = email.getBody();
        URLConnection conn = url.openConnection();
        content = conn.getContent();
    }

    mimePart.setContent(content, email.getMimeType());
}

From source file:org.openintents.updatechecker.UpdateChecker.java

public void checkForUpdate(String link) {

    mLatestVersion = -1;/*from  w  ww . j av  a 2  s  . c  o m*/
    mComment = null;
    mNewApplicationId = null;
    mLatestVersionName = null;

    try {
        Log.d(TAG, "Looking for version at " + link);

        if (mLatestVersion > 0 || mLatestVersionName != null) {
            return;
        } else {
            URL u = new URL(link);
            URLConnection connection = u.openConnection();
            connection.setReadTimeout(CONNECTION_TIMEOUT);
            Object content = connection.getContent();
            if (content instanceof InputStream) {
                InputStream is = (InputStream) content;

                BufferedReader reader = new BufferedReader(new InputStreamReader(is));

                String firstLine = reader.readLine();
                if (firstLine != null && firstLine.indexOf("<") >= 0) {

                    parseVeeCheck(link);
                } else {
                    parseTxt(firstLine, reader);
                }

            } else {
                Log.d(TAG, "Unknown server format: " + ((String) content).substring(0, 100));
            }
        }
    } catch (MalformedURLException e) {
        Log.v(TAG, "MalformedURLException", e);
    } catch (IOException e) {
        Log.v(TAG, "IOException", e);
    } catch (Exception e) {
        Log.v(TAG, "Exception", e);
    }

}

From source file:org.apache.beehive.controls.system.ejb.EJBControlImpl.java

@EventHandler(field = "resourceContext", eventSet = ResourceEvents.class, eventName = "onAcquire")
public void onAcquire() {

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Enter: onAquire()");
    }//from  w w w  .ja va2 s. c o  m

    // Compute the home instance cache lookup key.  The Service URI must
    // be taken into account because different services use different
    // class loaders.  The JNDI home must be taken into account because
    // it is possible to be a remote client of the same bean type on two
    // different providers.
    //
    if (_homeInstance == null) {
        // If JNDI name is an URL using a JNDI protocol
        if (_jndiName.toLowerCase().startsWith(JNDI_GLOBAL_PREFIX)) {

            try {
                URL url = new URL(_jndiName);
                URLConnection jndiConn = url.openConnection();
                _homeInstance = jndiConn.getContent();
            } catch (MalformedURLException mue) {
                throw new ControlException(_jndiName + " is not a valid JNDI URL", mue);
            } catch (IOException ioe) {
                throw new ControlException("Error during JNDI lookup from " + _jndiName, ioe);
            }
        } else {

            try {
                _homeInstance = lookupHomeInstance();
            } catch (NamingException ne) {
                throw new ControlException("Error during JNDI lookup from " + _jndiName, ne);
            }
        }

        if (!_homeInterface.isAssignableFrom(_homeInstance.getClass())) {
            throw new ControlException(
                    "JNDI lookup of " + _jndiName + " failed to return an instance of " + _homeInterface);
        }
    }
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPAuthenticatorIT.java

@Test()
public void wrongPasswordDontSave() throws Exception {
    assertEquals("Unexpected calls to password provider", 0,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
    assertEquals("Unexpected calls to authenticator", 0, authenticator.calls);
    Authenticator.setDefault(authenticator);

    // Make the server expect different password so our cache is no longer
    // valid//from   w  w w.j  a v  a 2 s .  c om
    userRealm.put(USERNAME, PASSWORD2);
    // But we'll try with the old one, which we'll this time ask to save in
    // DB
    UsernamePassword usernamePassword = new UsernamePassword(USERNAME, PASSWORD);
    assertFalse("Should not be set to save by default", usernamePassword.isShouldSave());
    //FixedPasswordProvider.setUsernamePassword(usernamePassword);

    URL url = new URL("http://localhost:" + PORT + "/test.html");
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), usernamePassword);
    URLConnection c = url.openConnection();
    try {
        c.getContent();
    } catch (Exception ex) {
    }

    assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage());
    assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString());

    assertEquals("HTTP/1.1 401 Unauthorized", c.getHeaderField(0));

    assertTrue("Did not invoke authenticator enough times", authenticator.calls > 1);
    assertEquals("Should have asked provider as much as authenticator", authenticator.calls,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());

    // Update provider to now provide the right one
    //      HTTPAuthenticatorServiceUsernameAndPasswordProvider.setUsernamePassword(new UsernamePassword(
    //            USERNAME, PASSWORD2));
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), new UsernamePassword(USERNAME, PASSWORD2));
    HTTPAuthenticatorServiceUsernameAndPasswordProvider.resetCalls();
    authenticator.calls = 0;

    URLConnection c2 = url.openConnection();
    try {
        c2.getContent();
    } catch (Exception ex) {
    }
    assertEquals("Did not call authenticator again with cache pw invalid", 1, authenticator.calls);
    assertEquals("id not called our password provider once", 1,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPAuthenticatorIT.java

@Test()
public void saveToDatabase() throws Exception {
    assertEquals("Unexpected calls to password provider", 0,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
    assertEquals("Unexpected calls to authenticator", 0, authenticator.calls);
    Authenticator.setDefault(authenticator);

    // Make the server expect different password so our cache is no longer
    // valid (In case CredManager.resetAuthCache() did not succeed on non-Sun VMs)
    userRealm.put(USERNAME, PASSWORD3);/* ww  w  .  ja v  a 2  s .c o  m*/
    // But we'll try with the old one, which we'll this time ask to save in
    // DB
    UsernamePassword usernamePassword = new UsernamePassword(USERNAME, PASSWORD2);
    usernamePassword.setShouldSave(true);
    //HTTPAuthenticatorServiceUsernameAndPasswordProvider.setUsernamePassword(usernamePassword);

    URL url = new URL("http://localhost:" + PORT + "/test.html");
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), usernamePassword);
    URLConnection c = url.openConnection();
    try {
        c.getContent();
    } catch (Exception ex) {
    }

    assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage());
    assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString());

    assertEquals("HTTP/1.1 401 Unauthorized", c.getHeaderField(0));

    assertTrue("Did not invoke authenticator enough times", authenticator.calls > 1);
    assertEquals("Asked our provider more than once, not saved in credMan?", 1,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());

    // Expect the old one again
    userRealm.put(USERNAME, PASSWORD2);
    // We'll now set our provider to give an invalid password, but we should
    // not be asked
    // as the old one (now correct agian) is stored in DB
    //      HTTPAuthenticatorServiceUsernameAndPasswordProvider.setUsernamePassword(new UsernamePassword(
    //            USERNAME, WRONG_PASSWORD));
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), new UsernamePassword(USERNAME, WRONG_PASSWORD));

    HTTPAuthenticatorServiceUsernameAndPasswordProvider.resetCalls();
    authenticator.calls = 0;

    URLConnection c2 = url.openConnection();
    try {
        c2.getContent();
    } catch (Exception ex) {
    }
    assertEquals("Did not call authenticator again with cache pw invalid", 1, authenticator.calls);
    assertEquals("Called our password provider instead of using credMan saved one", 0,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPAuthenticatorIT.java

@Test()
public void withAuthenticator() throws Exception {
    assertEquals("Unexpected calls to password provider", 0,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    // Set the authenticator to our Credential Manager-backed one that also
    // counts calls to itself
    CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
    assertEquals("Unexpected calls to authenticator", 0, authenticator.calls);
    Authenticator.setDefault(authenticator);
    //      FixedPasswordProvider.setUsernamePassword(new UsernamePassword(
    //            USERNAME, PASSWORD));

    URL url = new URL("http://localhost:" + PORT + "/test.html");
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), new UsernamePassword(USERNAME, PASSWORD));
    URLConnection c = url.openConnection();

    c.connect();//from ww  w.  j ava  2  s .  co m
    try {
        c.getContent();
    } catch (Exception ex) {
    }
    System.out.println(c.getHeaderField(0));
    assertEquals("Did not invoke authenticator", 1, authenticator.calls);
    assertEquals("Did not invoke our password provider", 1,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    assertEquals("HTTP/1.1 200 OK", c.getHeaderField(0));

    assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage());
    assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString());

    // And test Java's cache:
    URLConnection c2 = url.openConnection();
    c2.connect();
    assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));
    assertEquals("JVM invoked our authenticator again instead of caching", 1, authenticator.calls);
    assertEquals("Invoked our password provider again instead of caching", 1,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());

}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPAuthenticatorIT.java

@Test()
public void withAuthenticatorResetJava() throws Exception {
    assertTrue("Could not reset JVMs authCache, ignore on non-Sun JVM", credentialManager.resetAuthCache());

    assertEquals("Unexpected calls to password provider", 0,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
    assertEquals("Unexpected calls to authenticator", 0, authenticator.calls);
    Authenticator.setDefault(authenticator);
    //      FixedPasswordProvider.setUsernamePassword(new UsernamePassword(
    //            USERNAME, PASSWORD));

    URL url = new URL("http://localhost:" + PORT + "/test.html");
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), new UsernamePassword(USERNAME, PASSWORD));
    URLConnection c = url.openConnection();

    c.connect();/*from   w ww .  ja v a  2s  .  com*/
    try {
        c.getContent();
    } catch (Exception ex) {
    }

    assertEquals("HTTP/1.1 200 OK", c.getHeaderField(0));

    assertEquals("Did not invoke authenticator", 1, authenticator.calls);
    assertEquals("Did not invoke our password provider", 1,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());

    assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage());
    assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString());

    // And without Java's cache:
    assertTrue("Could not reset VMs authCache, ignore on non-Sun VM", credentialManager.resetAuthCache());

    URLConnection c2 = url.openConnection();
    c2.connect();
    assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));
    assertEquals("Did not invoke our authenticator again", 2, authenticator.calls);
    assertEquals("Did not invoke our password provider again", 2,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());

}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPAuthenticatorIT.java

@Test()
public void differentRealm() throws Exception {

    assertEquals("Unexpected calls to password provider", 0,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
    assertEquals("Unexpected calls to authenticator", 0, authenticator.calls);
    Authenticator.setDefault(authenticator);
    // Different password in case resetAuthCache() did not run
    UsernamePassword userPassword = new UsernamePassword(USERNAME, PASSWORD4);
    userRealm.put(USERNAME, PASSWORD4);/* ww w . j a  v a 2 s .  c o  m*/
    //      userPassword.setShouldSave(true);
    //FixedPasswordProvider.setUsernamePassword(userPassword);

    URL url = new URL("http://localhost:" + PORT + "/test.html");
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), userPassword);
    URLConnection c = url.openConnection();

    c.connect();
    try {
        c.getContent();
    } catch (Exception ex) {
    }

    assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage());
    assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString());

    assertEquals("HTTP/1.1 200 OK", c.getHeaderField(0));

    assertEquals("Did not invoke authenticator", 1, authenticator.calls);
    assertEquals("Did not invoke our password provider", 1,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());

    // different realm should be treated as a second connection, and not even use saved credentials

    credentialManager.resetAuthCache();
    userRealm.setName(REALM2);

    URLConnection c2 = url.openConnection();
    c2.connect();
    try {
        c.getContent();
    } catch (Exception ex) {
    }

    assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));

    assertEquals("Did not invoke authenticator again", 2, authenticator.calls);
    assertEquals("Did not invoke provider again", 2,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());

    assertEquals("Unexpected prompt/realm", REALM2, httpAuthProvider.getRequestMessage());
    assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM2,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString());
}

From source file:org.apache.pulsar.client.impl.auth.AuthenticationAthenz.java

private PrivateKey loadPrivateKey(String privateKeyURL) {
    PrivateKey privateKey = null;
    try {/*w  ww.j a  va  2  s. c om*/
        URLConnection urlConnection = new URL(privateKeyURL).openConnection();
        String protocol = urlConnection.getURL().getProtocol();
        if ("data".equals(protocol) && !APPLICATION_X_PEM_FILE.equals(urlConnection.getContentType())) {
            throw new IllegalArgumentException(
                    "Unsupported media type or encoding format: " + urlConnection.getContentType());
        }
        String keyData = CharStreams.toString(new InputStreamReader((InputStream) urlConnection.getContent()));
        privateKey = Crypto.loadPrivateKey(keyData);
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid privateKey format", e);
    } catch (CryptoException | InstantiationException | IllegalAccessException | IOException e) {
        privateKey = null;
    }
    return privateKey;
}

From source file:info.magnolia.cms.exchange.simple.SimpleSyndicator.java

/**
 * deactivate from a specified subscriber
 *
 * @param subscriber/*from  w ww. j av a 2  s.  c o  m*/
 * @throws ExchangeException
 */
private synchronized void doDeActivate(Subscriber subscriber) throws ExchangeException {
    if (!isSubscribed(subscriber)) {
        return;
    }
    String handle = getDeactivationURL(subscriber);
    try {
        URL url = new URL(handle);
        URLConnection urlConnection = url.openConnection();
        this.addDeactivationHeaders(urlConnection);
        urlConnection.getContent();
    } catch (MalformedURLException e) {
        throw new ExchangeException("Incorrect URL for subscriber " + subscriber + "[" + handle + "]");
    } catch (IOException e) {
        throw new ExchangeException(
                "Not able to send the deactivation request [" + handle + "]: " + e.getMessage());
    } catch (Exception e) {
        throw new ExchangeException(e);
    }
}