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.zhonghui.tool.controller.HttpClient.java

/**
 * HTTP Post???// ww w .j a v a2  s  .  c o m
 *
 * @param connection 
 * @param message ???
 * @throws IOException
 */
private void requestServer(final URLConnection connection, String message, String encoder) throws Exception {
    PrintStream out = null;
    try {
        connection.connect();
        out = new PrintStream(connection.getOutputStream(), false, encoder);
        out.print(message);
        out.flush();
    } catch (Exception e) {
        throw e;
    } finally {
        if (null != out) {
            out.close();
        }
    }
}

From source file:org.xenmaster.monitoring.engine.Slot.java

public URLConnection getConnection() {
    try {/*from   ww w.j  a  v a 2s  .  c  om*/
        if (connection == null || connectToUpdates) {
            Host host = new Host(reference);
            URL url;
            if (connectToUpdates) {
                url = new URL("http://" + host.getAddress().getCanonicalHostName() + "/rrd_updates?start="
                        + ((lastPolled - 5000) / 1000) + "&host=true");
            } else {
                url = new URL("http://" + host.getAddress().getCanonicalHostName() + "/host_rrd");
                connectToUpdates = true;
            }

            URLConnection uc = url.openConnection();
            byte[] auth = (Settings.getInstance().getString("Xen.User") + ':'
                    + Settings.getInstance().getString("Xen.Password")).getBytes("UTF-8");
            uc.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(auth)));
            uc.connect();

            lastPolled = System.currentTimeMillis();
            connection = uc;
        }
    } catch (Exception ex) {
        busy = false;
        Logger.getLogger(getClass()).error("Failed to retrieve statistics", ex);
    }

    return connection;
}

From source file:com.alfaariss.oa.authentication.remote.aselect.idp.storage.config.IDPConfigStorage.java

/**
 * @see com.alfaariss.oa.engine.idp.storage.configuration.AbstractConfigurationStorage#createIDP(com.alfaariss.oa.api.configuration.IConfigurationManager, org.w3c.dom.Element)
 *//*from w  w w .j  a  v  a 2 s .com*/
@Override
protected IIDP createIDP(IConfigurationManager configManager, Element config) throws OAException {
    ASelectIDP oASelectIDP = null;
    try {
        String sServerID = configManager.getParam(config, "server_id");
        if (sServerID == null) {
            _logger.error("No 'server_id' parameter found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sOrganizationID = configManager.getParam(config, "id");
        if (sOrganizationID == null) {
            _logger.error("No 'id' parameter found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sFriendlyname = configManager.getParam(config, "friendlyname");
        if (sFriendlyname == null) {
            _logger.error("No 'friendlyname' parameter found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sURL = configManager.getParam(config, "url");
        if (sURL == null) {
            _logger.error("No 'url' parameter found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }
        URL urlTarget = null;
        try {
            urlTarget = new URL(sURL);
        } catch (MalformedURLException e) {
            _logger.error("Invalid 'url' parameter found in configuration: " + sURL);
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        try {
            URLConnection urlConnection = urlTarget.openConnection();
            urlConnection.setConnectTimeout(3000);
            urlConnection.setReadTimeout(3000);
            urlConnection.connect();
        } catch (IOException e) {
            _logger.warn("Could not connect to 'url' parameter found in configuration: " + sURL);
        }

        String sLevel = configManager.getParam(config, "level");
        if (sLevel == null) {
            _logger.error("No 'level' parameter found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        int iLevel;
        try {
            iLevel = Integer.parseInt(sLevel);
        } catch (NumberFormatException e) {
            _logger.error("Invalid 'level' parameter found in configuration, not a number: " + sLevel);
            throw new OAException(SystemErrors.ERROR_INIT);
        }

        String sCountry = configManager.getParam(config, "country");
        if (sCountry == null)
            _logger.info("No optional 'country' parameter found in configuration");

        String sLanguage = configManager.getParam(config, "language");
        if (sLanguage == null)
            _logger.info("No optional 'language' parameter found in configuration");

        boolean bDoSigning = false;
        String sSigning = configManager.getParam(config, "signing");
        if (sSigning != null) {
            if (sSigning.equalsIgnoreCase("TRUE"))
                bDoSigning = true;
            else if (!sSigning.equalsIgnoreCase("FALSE")) {
                _logger.error("Invalid 'signing' parameter found in configuration, must be 'true' or 'false': "
                        + sSigning);
                throw new OAException(SystemErrors.ERROR_INIT);
            }
        }

        boolean bASynchronousLogout = false;
        String sASynchronousLogout = configManager.getParam(config, "asynchronouslogout");
        if (sASynchronousLogout != null) {
            if (sASynchronousLogout.equalsIgnoreCase("TRUE"))
                bASynchronousLogout = true;
            else if (!sASynchronousLogout.equalsIgnoreCase("FALSE")) {
                _logger.error(
                        "Invalid 'asynchronouslogout' parameter found in configuration, must be 'true' or 'false': "
                                + sASynchronousLogout);
                throw new OAException(SystemErrors.ERROR_INIT);
            }
        }

        boolean bSynchronousLogout = false;
        String sSynchronousLogout = configManager.getParam(config, "synchronouslogout");
        if (sSynchronousLogout != null) {
            if (sSynchronousLogout.equalsIgnoreCase("TRUE"))
                bSynchronousLogout = true;
            else if (!sSynchronousLogout.equalsIgnoreCase("FALSE")) {
                _logger.error(
                        "Invalid 'synchronouslogout' parameter found in configuration, must be 'true' or 'false': "
                                + sSynchronousLogout);
                throw new OAException(SystemErrors.ERROR_INIT);
            }
        }

        boolean bSendArpTarget = false;
        String sSendArpTarget = configManager.getParam(config, "send_arp_target");
        if (sSendArpTarget != null) {
            if (sSendArpTarget.equalsIgnoreCase("TRUE"))
                bSendArpTarget = true;
            else if (!sSendArpTarget.equalsIgnoreCase("FALSE")) {
                _logger.error(
                        "Invalid 'send_arp_target' parameter found in configuration, must be 'true' or 'false': "
                                + sSigning);
                throw new OAException(SystemErrors.ERROR_INIT);
            }
        }

        oASelectIDP = new ASelectIDP(sOrganizationID, sFriendlyname, sServerID, sURL, iLevel, bDoSigning,
                sCountry, sLanguage, bASynchronousLogout, bSynchronousLogout, bSendArpTarget);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Internal error during create", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL, e);
    }
    return oASelectIDP;
}

From source file:piuk.blockchain.android.ui.WalletActivity.java

private void checkVersionAndTimeskewAlert() {
    new Thread() {
        @Override//from   w ww.  j a v  a 2  s .  c  om
        public void run() {
            try {
                final int versionCode = getWalletApplication().applicationVersionCode();
                final URLConnection connection = new URL(Constants.VERSION_URL + "?current=" + versionCode)
                        .openConnection();
                connection.connect();
                final long serverTime = connection.getHeaderFieldDate("Date", 0);
                final InputStream is = connection.getInputStream();
                final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                // final String version = reader.readLine();
                reader.close();

                if (serverTime > 0) {
                    final long diffMinutes = Math.abs((System.currentTimeMillis() - serverTime) / 1000 / 60);

                    if (diffMinutes >= 60) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                if (!isFinishing())
                                    timeskewAlert(diffMinutes);
                            }
                        });
                    }
                }
            } catch (final Exception x) {
                x.printStackTrace();
            }
        }
    }.start();
}

From source file:org.pentaho.reporting.libraries.resourceloader.loader.URLResourceData.java

private void readMetaData() throws IOException {
    if (metaDataOK) {
        if ((System.currentTimeMillis() - lastDateMetaDataRead) < URLResourceData.getFixedCacheDelay()) {
            return;
        }//from   w  w w.  j av a 2 s  .c  om
        if (isFixBrokenWebServiceDateHeader()) {
            return;
        }

    }

    final URLConnection c = url.openConnection();
    c.setDoOutput(false);
    c.setAllowUserInteraction(false);
    if (c instanceof HttpURLConnection) {
        final HttpURLConnection httpURLConnection = (HttpURLConnection) c;
        httpURLConnection.setRequestMethod("HEAD");
    }
    c.connect();
    readMetaData(c);
    c.getInputStream().close();
}

From source file:org.bireme.interop.fromJson.Json2Couch.java

private void sendDocuments(final String docs) {
    try {//from  w w w .  j a va2s .co m
        assert docs != null;

        final URLConnection connection = url.openConnection();
        connection.setRequestProperty("CONTENT-TYPE", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream())
        //final String udocs = URLEncoder.encode(docs, "UTF-8");
        ) {
            out.write(docs);
        }

        try (InputStreamReader reader = new InputStreamReader(connection.getInputStream())) {
            final List<String> msgs = getBadDocuments(reader);

            for (String msg : msgs) {
                System.err.println("write error: " + msg);
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(Json2Couch.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.atricore.idbus.bundles.apache.tiles.OsgiDefinitionsFactory.java

/**
 * Creates and returns a {@link Definitions} set by reading
 * configuration data from the applied sources.
 *
 * @return The definitions holder object, filled with base definitions.
 * @throws DefinitionsFactoryException if an error occurs reading the
 * sources.//from   www.  j  a  v a  2 s .  co m
 */
public Definitions readDefinitions() throws DefinitionsFactoryException {
    Definitions definitions = createDefinitions();
    try {
        for (Object source1 : sources) {
            URL source = (URL) source1;
            URLConnection connection = source.openConnection();
            connection.connect();
            lastModifiedDates.put(source.toExternalForm(), connection.getLastModified());
            Map<String, Definition> defsMap = reader.read(connection.getInputStream());
            definitions.addDefinitions(defsMap);
        }
    } catch (IOException e) {
        throw new DefinitionsFactoryException("I/O error accessing source.", e);
    }
    return definitions;
}

From source file:org.atricore.idbus.bundles.apache.tiles.OsgiDefinitionsFactory.java

/**
 * Indicates whether the DefinitionsFactory is out of date and needs to be
 * reloaded.//  ww  w .  j a  v a 2  s . com
 *
 * @return If the factory needs refresh.
 */
public boolean refreshRequired() {
    boolean status = false;

    Set<String> urls = lastModifiedDates.keySet();

    try {
        for (String urlPath : urls) {
            Long lastModifiedDate = lastModifiedDates.get(urlPath);
            URL url = new URL(urlPath);
            URLConnection connection = url.openConnection();
            connection.connect();
            long newModDate = connection.getLastModified();
            if (newModDate != lastModifiedDate) {
                status = true;
                break;
            }
        }
    } catch (Exception e) {
        logger.warn("Exception while monitoring update times.", e);
        return true;
    }
    return status;
}

From source file:org.wso2.es.integration.common.utils.AssetsRESTClient.java

/**
 * This method is used to retrieve assets via publisher assets list endpoint
 *
 * @param sessionId String of valid session ID
 * @return JSON ARRAY of gadgets/*  w  ww .  j a  va  2s  .c  o m*/
 */
private JsonArray getAssets(String sessionId) throws IOException {
    BufferedReader input = null;
    String listAssetsEndpoint = getBaseUrl() + PUBLISHER_APIS_LIST_GADGETS_ENDPOINT;
    //construct endpoint which retrieves list of gadgets
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Get Assets via REST endpoint using sessionID: " + sessionId);
        }
        URL endpointUrl = new URL(listAssetsEndpoint);
        URLConnection urlConn = endpointUrl.openConnection();
        urlConn.setRequestProperty("Accept", "application/json");
        urlConn.setRequestProperty(COOKIE, JSESSIONID + "=" + sessionId + ";");
        // SessionId Cookie
        urlConn.connect();
        //GET response data
        input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        JsonElement elem = parser.parse(input);

        // parse response to a JasonArray
        return elem.getAsJsonObject().getAsJsonArray(ASSET_LIST_KEY);
    } catch (MalformedURLException e) {
        LOG.error(getAssetRetrievingErrorMassage(listAssetsEndpoint), e);
        throw e;
    } catch (IOException e) {
        LOG.error(getAssetRetrievingErrorMassage(listAssetsEndpoint), e);
        throw e;
    } finally {
        if (input != null) {
            try {
                input.close();// will close the URL connection as well
            } catch (IOException e) {
                LOG.error("Failed to close the connection", e);
            }
        }
    }
}

From source file:count.ly.messaging.ConnectionProcessor.java

@Override
public void run() {
    while (true) {
        final String[] storedEvents = store_.connections();
        if (storedEvents == null || storedEvents.length == 0) {
            // currently no data to send, we are done for now
            break;
        }/*from   www .j  a v  a  2s. c o  m*/

        // get first event from collection
        if (deviceId_.getId() == null) {
            // When device ID is supplied by OpenUDID or by Google Advertising ID.
            // In some cases it might take time for them to initialize. So, just wait for it.
            if (Countly.sharedInstance().isLoggingEnabled()) {
                Log.i(Countly.TAG, "No Device ID available yet, skipping request " + storedEvents[0]);
            }
            break;
        }
        final String eventData = storedEvents[0] + "&device_id=" + deviceId_.getId();

        URLConnection conn = null;
        BufferedInputStream responseStream = null;
        try {
            // initialize and open connection
            conn = urlConnectionForEventData(eventData);
            conn.connect();

            // consume response stream
            responseStream = new BufferedInputStream(conn.getInputStream());
            final ByteArrayOutputStream responseData = new ByteArrayOutputStream(256); // big enough to handle success response without reallocating
            int c;
            while ((c = responseStream.read()) != -1) {
                responseData.write(c);
            }

            // response code has to be 2xx to be considered a success
            boolean success = true;
            if (conn instanceof HttpURLConnection) {
                final HttpURLConnection httpConn = (HttpURLConnection) conn;
                final int responseCode = httpConn.getResponseCode();
                success = responseCode >= 200 && responseCode < 300;
                if (!success && Countly.sharedInstance().isLoggingEnabled()) {
                    Log.w(Countly.TAG, "HTTP error response code was " + responseCode
                            + " from submitting event data: " + eventData);
                }
            }

            // HTTP response code was good, check response JSON contains {"result":"Success"}
            if (success) {
                final JSONObject responseDict = new JSONObject(responseData.toString("UTF-8"));
                success = responseDict.optString("result").equalsIgnoreCase("success");
                if (!success && Countly.sharedInstance().isLoggingEnabled()) {
                    Log.w(Countly.TAG, "Response from Countly server did not report success, it was: "
                            + responseData.toString("UTF-8"));
                }
            }

            if (success) {
                if (Countly.sharedInstance().isLoggingEnabled()) {
                    Log.d(Countly.TAG, "ok ->" + eventData);
                }

                // successfully submitted event data to Count.ly server, so remove
                // this one from the stored events collection
                store_.removeConnection(storedEvents[0]);
            } else {
                // warning was logged above, stop processing, let next tick take care of retrying
                break;
            }
        } catch (Exception e) {
            if (Countly.sharedInstance().isLoggingEnabled()) {
                Log.w(Countly.TAG, "Got exception while trying to submit event data: " + eventData, e);
            }
            // if exception occurred, stop processing, let next tick take care of retrying
            break;
        } finally {
            // free connection resources
            if (responseStream != null) {
                try {
                    responseStream.close();
                } catch (IOException ignored) {
                }
            }
            if (conn != null && conn instanceof HttpURLConnection) {
                ((HttpURLConnection) conn).disconnect();
            }
        }
    }
}