Example usage for java.net URLConnection setConnectTimeout

List of usage examples for java.net URLConnection setConnectTimeout

Introduction

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

Prototype

public void setConnectTimeout(int timeout) 

Source Link

Document

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.

Usage

From source file:org.wattdepot.client.http.api.collector.EGaugeCollector.java

@Override
public void run() {
    Measurement meas = null;//www .j ava 2s.  c  om
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    try {
        DocumentBuilder builder = domFactory.newDocumentBuilder();

        // Have to make HTTP connection manually so we can set proper timeouts
        URL url = new URL(eGaugeUri);
        URLConnection httpConnection;
        httpConnection = url.openConnection();
        // Set both connect and read timeouts to 15 seconds. No point in long
        // timeouts since the
        // sensor will retry before too long anyway.
        httpConnection.setConnectTimeout(15 * 1000);
        httpConnection.setReadTimeout(15 * 1000);
        httpConnection.connect();

        // Record current time as close approximation to time for reading we are
        // about to make
        Date timestamp = new Date();

        Document doc = builder.parse(httpConnection.getInputStream());

        XPathFactory factory = XPathFactory.newInstance();
        XPath powerXpath = factory.newXPath();
        XPath energyXpath = factory.newXPath();
        // Path to get the current power consumed measured by the meter in watts
        String exprPowerString = "//r[@rt='total' and @t='P' and @n='" + this.registerName + "']/i/text()";
        XPathExpression exprPower = powerXpath.compile(exprPowerString);
        // Path to get the energy consumed month to date in watt seconds
        String exprEnergyString = "//r[@rt='total' and @t='P' and @n='" + this.registerName + "']/v/text()";
        XPathExpression exprEnergy = energyXpath.compile(exprEnergyString);
        Object powerResult = exprPower.evaluate(doc, XPathConstants.NUMBER);
        Object energyResult = exprEnergy.evaluate(doc, XPathConstants.NUMBER);

        Double value = null;
        // power is given in W
        Amount<?> power = Amount.valueOf((Double) powerResult, SI.WATT);
        // energy given in Ws
        Amount<?> energy = Amount.valueOf((Double) energyResult, SI.WATT.times(SI.SECOND));
        if (isPower()) {
            value = power.to(measUnit).getEstimatedValue();
        } else {
            value = energy.to(measUnit).getEstimatedValue();
        }
        meas = new Measurement(definition.getSensorId(), timestamp, value, measUnit);
    } catch (MalformedURLException e) {
        System.err.format("URI %s was invalid leading to malformed URL%n", eGaugeUri);
    } catch (XPathExpressionException e) {
        System.err.println("Bad XPath expression, this should never happen.");
    } catch (ParserConfigurationException e) {
        System.err.println("Unable to configure XML parser, this is weird.");
    } catch (SAXException e) {
        System.err.format("%s: Got bad XML from eGauge sensor %s (%s), hopefully this is temporary.%n",
                Tstamp.makeTimestamp(), sensor.getName(), e);
    } catch (IOException e) {
        System.err.format(
                "%s: Unable to retrieve data from eGauge sensor %s (%s), hopefully this is temporary.%n",
                Tstamp.makeTimestamp(), sensor.getName(), e);
    }

    if (meas != null) {
        try {
            this.client.putMeasurement(depository, meas);
        } catch (MeasurementTypeException e) {
            System.err.format("%s does not store %s measurements%n", depository.getName(),
                    meas.getMeasurementType());
        }
        if (debug) {
            System.out.println(meas);
        }
    }
}

From source file:com.varaneckas.hawkscope.plugin.PluginManager.java

/**
 * Tells to check for plugin updates//www .  j a va2s  .  c om
 * 
 * @param pluginVersionCheckUrl
 * @param proxy can be null
 */
public void checkPluginUpdates(final String pluginVersionCheckUrl, final Proxy proxy) {
    try {
        final URL pluginCheckUrl = new URL(Version.PLUGIN_VERSION_CHECK_URL);
        final URLConnection conn;
        if (proxy == null) {
            conn = pluginCheckUrl.openConnection();
        } else {
            conn = pluginCheckUrl.openConnection(proxy);
        }
        conn.setConnectTimeout(Constants.CONNECTION_TIMOUT);
        conn.setReadTimeout(Constants.CONNECTION_TIMOUT);
        final InputStream io = conn.getInputStream();
        int c = 0;
        final StringBuilder version = new StringBuilder();
        while ((c = io.read()) != -1) {
            version.append((char) c);
        }
        final String[] plugs = version.toString().split("\n");
        final Map<String, String> currentVersions = new HashMap<String, String>();
        for (final Plugin p : getActivePlugins()) {
            currentVersions.put(p.getName(), p.getVersion());
        }
        for (final String plug : plugs) {
            final String[] plugData = plug.split(":");
            if (currentVersions.containsKey(plugData[0])) {
                if (currentVersions.get(plugData[0]).compareTo(plugData[1]) < 0) {
                    availableUpdates.put(plugData[0], plugData[1]);
                }
            }
        }
        if (availableUpdates.size() > 0) {
            log.info("Plugin updates available: " + availableUpdates);
        }
    } catch (final Exception e) {
        log.error("Failed getting plugin updates");
    }
}

From source file:org.wso2.iot.system.service.api.OTADownload.java

public void onStateChecked(int error, final BuildPropParser parser) {
    final String operation = Preference.getBoolean(context,
            context.getResources().getString(R.string.firmware_status_check_in_progress))
                    ? Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS
                    : Constants.Operation.UPGRADE_FIRMWARE;
    if (error == 0) {
        if (!otaServerManager.compareLocalVersionToServer(parser)) {
            JSONObject result = new JSONObject();
            try {
                result.put(UPGRADE_AVAILABLE, false);
                if (parser != null) {
                    result.put(UPGRADE_DESCRIPTION, parser.getProp("Software is up to date"));
                }/*from  ww w.j a  v a  2 s.  co m*/
                CommonUtils.sendBroadcast(context, operation, Constants.Code.SUCCESS,
                        Constants.Status.NO_UPGRADE_FOUND, result.toString());
            } catch (JSONException e) {
                String message = "Result payload build failed.";
                CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE,
                        Constants.Status.UPDATE_INFO_NOT_READABLE, message);
                Log.e(TAG, message + e);
            }
            String message = "Software is up to date:" + Build.VERSION.RELEASE + ", " + Build.ID;
            Log.i(TAG, message);
            CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_COMPLETE,
                    Preference.getInt(context, context.getResources().getString(R.string.operation_id)),
                    "No upgrades available. " + message);
        } else if (checkNetworkOnline()) {
            new AsyncTask<Void, Void, Long>() {
                protected Long doInBackground(Void... param) {
                    URL url = otaServerManager.getServerConfig().getPackageURL();
                    URLConnection con;
                    try {
                        con = url.openConnection();
                        con.setConnectTimeout(Constants.FIRMWARE_UPGRADE_CONNECTIVITY_TIMEOUT);
                        con.setReadTimeout(Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                        return (long) con.getContentLength();
                    } catch (SocketTimeoutException e) {
                        String message = "Connection failure (Socket timeout) when retrieving update package size.";
                        Log.e(TAG, message + e);
                        CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE,
                                Constants.Status.CONNECTION_FAILED, message);
                        CommonUtils
                                .callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION,
                                        Preference.getInt(context,
                                                context.getResources().getString(R.string.operation_id)),
                                        message);
                        return (long) -1;
                    } catch (IOException e) {
                        String message = "Connection failure when retrieving update package size.";
                        Log.e(TAG, message + e);
                        CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE,
                                Constants.Status.CONNECTION_FAILED, message);
                        CommonUtils
                                .callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION,
                                        Preference.getInt(context,
                                                context.getResources().getString(R.string.operation_id)),
                                        message);
                        return (long) -1;
                    }
                }

                protected void onPostExecute(Long bytes) {
                    Log.i(TAG, "New release found " + Build.VERSION.RELEASE + ", " + Build.ID);
                    String length = "Unknown";
                    if (bytes > 0) {
                        length = byteCountToDisplaySize(bytes, false);
                    }

                    Log.i(TAG, "version :" + parser.getProp("ro.build.id") + "\n" + "full_version :"
                            + parser.getProp("ro.build.description") + "\n" + "size : " + length);
                    //Downloading the new update package if a new version is available.
                    if (Preference.getBoolean(context,
                            context.getResources().getString(R.string.firmware_status_check_in_progress))) {
                        JSONObject result = new JSONObject();
                        try {
                            result.put(UPGRADE_AVAILABLE, true);
                            result.put(UPGRADE_SIZE, length);
                            result.put(UPGRADE_RELEASE, parser.getNumRelease());
                            result.put(UPGRADE_VERSION, parser.getProp("ro.build.id"));
                            result.put(UPGRADE_DESCRIPTION, parser.getProp("ro.build.description"));
                            CommonUtils.sendBroadcast(context,
                                    Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS,
                                    Constants.Code.SUCCESS, Constants.Status.SUCCESSFUL, result.toString());
                        } catch (JSONException e) {
                            String message = "Result payload build failed.";
                            CommonUtils.sendBroadcast(context,
                                    Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS,
                                    Constants.Code.FAILURE, Constants.Status.OTA_IMAGE_VERIFICATION_FAILED,
                                    message);
                            Log.e(TAG, message + e);
                        }

                    } else {
                        Boolean isAutomaticRetry = !Preference.hasPreferenceKey(context,
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry))
                                || Preference.getBoolean(context, context.getResources()
                                        .getString(R.string.firmware_upgrade_automatic_retry));

                        if (checkNetworkOnline()) {
                            if (getBatteryLevel(
                                    context) >= Constants.REQUIRED_BATTERY_LEVEL_TO_FIRMWARE_UPGRADE) {
                                otaServerManager.startDownloadUpgradePackage(otaServerManager);
                            } else if (isAutomaticRetry) {
                                String message = "Upgrade download has been differed due to insufficient battery level.";
                                Log.w(TAG, message);
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_download_status),
                                        Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD);
                                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                                        Constants.Code.PENDING,
                                        Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD, message);
                            } else {
                                String message = "Upgrade download has been failed due to insufficient battery level.";
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_download_status),
                                        Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD);
                                Log.e(TAG, message);
                                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                                        Constants.Code.FAILURE,
                                        Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD, message);
                                CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_FAILURE,
                                        Preference.getInt(context,
                                                context.getResources().getString(R.string.operation_id)),
                                        message);
                            }
                        } else {
                            String message = "Connection failure when starting upgrade download.";
                            Log.e(TAG, message);
                            if (isAutomaticRetry) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_download_status),
                                        Constants.Status.NETWORK_UNREACHABLE);
                                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                                        Constants.Code.PENDING, Constants.Status.NETWORK_UNREACHABLE, message);
                                CommonUtils.callAgentApp(context,
                                        Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION,
                                        Preference.getInt(context,
                                                context.getResources().getString(R.string.operation_id)),
                                        message);
                            } else {
                                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                                        Constants.Code.FAILURE, Constants.Status.NETWORK_UNREACHABLE, message);
                                CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_FAILURE,
                                        Preference.getInt(context,
                                                context.getResources().getString(R.string.operation_id)),
                                        message);
                            }
                        }
                    }
                }
            }.execute();

        } else {
            String message = "Connection failure when starting build prop download.";
            Log.e(TAG, message);
            CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE,
                    Constants.Status.CONNECTION_FAILED, message);
            CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION,
                    Preference.getInt(context, context.getResources().getString(R.string.operation_id)), null);
        }
    } else if (error == ERROR_WIFI_NOT_AVAILABLE) {
        Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status),
                Constants.Status.WIFI_OFF);
        Log.e(TAG, "OTA failed due to WIFI connection failure.");
    } else if (error == ERROR_CANNOT_FIND_SERVER) {
        String message = "OTA failed due to OTA server not accessible.";
        Log.e(TAG, message);
    } else if (error == ERROR_WRITE_FILE_ERROR) {
        String message = "OTA failed due to file write error.";
        Log.e(TAG, message);
    }
}

From source file:xyz.lebalex.lockscreen.MainActivity.java

private static Bitmap getBitMapFromUrl(String urls, int timeout) {
    try {/*from w ww .j  a  v a2 s  . c o  m*/
        originalUrlTemp = urls;
        /*URL url = new URL(urls);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(10000);
        urlConnection.setReadTimeout(10000);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();
        InputStream imageStream = urlConnection.getInputStream();*/

        URL url = new URL(urls);
        URLConnection dc = url.openConnection();
        dc.setConnectTimeout(timeout * 1000);
        dc.setReadTimeout(timeout * 1000);
        InputStream imageStream = dc.getInputStream();
        return BitmapFactory.decodeStream(imageStream);
    } catch (Exception e) {
        return null;
    }
}

From source file:io.fabric8.apiman.rest.Kubernetes2ApimanFilter.java

/**
 * Checks of the descriptionDocument can be obtained from the service. If the
 * service is still deploying we will hold off and return false.
 *
 * @param bean/*from   w  w w. j  a  v a2 s . c  o  m*/
 * @return true of the desciptionDocument is ready to be read.
 */
private boolean isServiceReady(AvailableApiBean bean) {
    log.debug("DefinitionType: " + bean.getDefinitionType());
    URL defUrl = null;
    if (bean.getDefinitionType() != null && !"None".equals(bean.getDefinitionType().name())) {
        try {
            defUrl = new URL(bean.getDefinitionUrl());
            URLConnection urlConnection = defUrl.openConnection();
            log.info("Trying to obtain descriptionDoc for service " + bean.getName());
            urlConnection.setConnectTimeout(250);
            if (urlConnection.getContentLength() > 0) {
                log.debug("DefinitionDoc at 'Ready to be read " + urlConnection.getContent());
                return true;
            } else {
                //try the route
                defUrl = new URL(bean.getRouteDefinitionUrl());
                urlConnection = defUrl.openConnection();
                log.info("Trying to obtain descriptionDoc for service " + bean.getName());
                urlConnection.setConnectTimeout(250);
                if (urlConnection.getContentLength() > 0) {
                    bean.setDefinitionUrl(defUrl.toExternalForm());
                    return true;
                } else {
                    log.info("DefinitionDoc for '" + bean.getName() + "' not ready to be read from "
                            + defUrl.toExternalForm());
                }
                return false;
            }
        } catch (Exception e) {
            log.info("DefinitionDoc for '" + bean.getName() + "' can't be read. " + e.getMessage());
            return false;
        }
    }
    return true;
}

From source file:net.sf.eclipsecs.core.config.configtypes.RemoteConfigurationType.java

@Override
protected byte[] getBytesFromURLConnection(URLConnection connection) throws IOException {

    byte[] configurationFileData = null;
    InputStream in = null;//from  www .j  a  va 2s . c  om
    try {

        // set timeouts - bug 2941010
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);

        if (connection instanceof HttpURLConnection) {

            if (!sFailedWith401URLs.contains(connection.getURL().toString())) {

                HttpURLConnection httpConn = (HttpURLConnection) connection;
                httpConn.setInstanceFollowRedirects(true);
                httpConn.connect();
                if (httpConn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    try {
                        RemoteConfigAuthenticator.removeCachedAuthInfo(connection.getURL());
                    } catch (CheckstylePluginException e) {
                        CheckstyleLog.log(e);
                    }

                    // add to 401ed URLs
                    sFailedWith401URLs.add(connection.getURL().toString());
                    throw new IOException(Messages.RemoteConfigurationType_msgUnAuthorized);
                }
            } else {
                // don't retry since we just get another 401
                throw new IOException(Messages.RemoteConfigurationType_msgUnAuthorized);
            }
        }

        in = connection.getInputStream();
        configurationFileData = IOUtils.toByteArray(in);
    } finally {
        IOUtils.closeQuietly(in);

    }
    return configurationFileData;
}

From source file:com.alfaariss.oa.authentication.remote.saml2.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)
 */// w  ww.  j ava 2  s  . com
@Override
protected IIDP createIDP(IConfigurationManager configManager, Element config) throws OAException {
    SAML2IDP saml2IDP = null;

    try {
        String sID = configManager.getParam(config, "id");
        if (sID == null) {
            _oLogger.error("No 'id' item found in 'organization' section in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }
        byte[] baSourceID = generateSHA1(sID);

        String sFriendlyName = configManager.getParam(config, "friendlyname");
        if (sFriendlyName == null) {
            _oLogger.error("No 'friendlyname' item found in 'organization' section in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sDateLastModified = configManager.getParam(config, "lastmodified");
        Date dLastModified = null;

        if (sDateLastModified != null) {
            // Convert to java.util.Date
            try {
                DateTime dt = ISODateTimeFormat.dateTimeNoMillis().parseDateTime(sDateLastModified);
                dLastModified = dt.toDate();
            } catch (IllegalArgumentException iae) {
                _oLogger.info(
                        "Invalid 'lastmodified' timestamp provided: " + sDateLastModified + "; ignoring.");
                dLastModified = null;
            }
        }

        String sMetadataURL = null;
        int iMetadataURLTimeout = -1;
        String sMetadataFile = null;

        Element eMetadata = configManager.getSection(config, "metadata");
        if (eMetadata == null) {
            _oLogger.warn(
                    "No optional 'metadata' section found in configuration for organization with id: " + sID);
        } else {
            Element eHttp = configManager.getSection(eMetadata, "http");
            if (eHttp == null) {
                _oLogger.warn(
                        "No optional 'http' section in 'metadata' section found in configuration for organization with id: "
                                + sID);
            } else {
                sMetadataURL = configManager.getParam(eHttp, "url");
                if (sMetadataURL == null) {
                    _oLogger.error(
                            "No 'url' item in 'http' section found in configuration for organization with id: "
                                    + sID);
                    throw new OAException(SystemErrors.ERROR_CONFIG_READ);
                }

                URL urlTarget = null;
                try {
                    urlTarget = new URL(sMetadataURL);
                } catch (MalformedURLException e) {
                    _oLogger.error(
                            "Invalid 'url' item in 'http' section found in configuration: " + sMetadataURL, e);
                    throw new OAException(SystemErrors.ERROR_INIT);
                }

                StringBuffer sbInfo = new StringBuffer("Organization '");
                sbInfo.append(sID);
                sbInfo.append("' uses metadata from url: ");
                sbInfo.append(sMetadataURL);
                _oLogger.info(sbInfo.toString());

                try {
                    URLConnection urlConnection = urlTarget.openConnection();
                    urlConnection.setConnectTimeout(3000);
                    urlConnection.setReadTimeout(3000);
                    urlConnection.connect();
                } catch (IOException e) {
                    _oLogger.warn("Could not connect to 'url' item in 'http' section found in configuration: "
                            + sMetadataURL, e);
                }

                String sTimeout = configManager.getParam(eHttp, "timeout");
                if (sTimeout != null) {
                    try {
                        iMetadataURLTimeout = Integer.parseInt(sTimeout);
                    } catch (NumberFormatException e) {
                        _oLogger.error(
                                "Invalid 'timeout' item in 'http' section found in configuration (must be a number): "
                                        + sTimeout,
                                e);
                        throw new OAException(SystemErrors.ERROR_INIT);
                    }

                    if (iMetadataURLTimeout < 0) {
                        _oLogger.error(
                                "Invalid 'timeout' item in 'http' section found in configuration: " + sTimeout);
                        throw new OAException(SystemErrors.ERROR_INIT);
                    }
                }
            }

            sMetadataFile = configManager.getParam(eMetadata, "file");
            if (sMetadataFile == null) {
                _oLogger.warn(
                        "No optional 'file' item in 'metadata' section found in configuration for organization with id: "
                                + sID);
            } else {
                // Translate the path
                sMetadataFile = PathTranslator.getInstance().map(sMetadataFile);

                File fMetadata = new File(sMetadataFile);
                if (!fMetadata.exists()) {
                    _oLogger.error("Configured metadata 'file' doesn't exist: " + sMetadataFile);
                    throw new OAException(SystemErrors.ERROR_INIT);
                }

                StringBuffer sbInfo = new StringBuffer("Organization '");
                sbInfo.append(sID);
                sbInfo.append("' uses metadata in file: ");
                sbInfo.append(sMetadataFile);
                _oLogger.info(sbInfo.toString());
            }
        }

        Boolean boolACSIndex = new Boolean(true);
        String sACSIndex = configManager.getParam(config, "acs_index");
        if (sACSIndex != null) {
            if (sACSIndex.equalsIgnoreCase("FALSE"))
                boolACSIndex = new Boolean(false);
            else if (!sACSIndex.equalsIgnoreCase("TRUE")) {
                _oLogger.error("Invalid 'acs_index' item value found in configuration: " + sACSIndex);
                throw new OAException(SystemErrors.ERROR_INIT);
            }
        }

        Boolean boolScoping = new Boolean(true);
        String sScoping = configManager.getParam(config, "scoping");
        if (sScoping != null) {
            if (sScoping.equalsIgnoreCase("FALSE"))
                boolScoping = new Boolean(false);
            else if (!sScoping.equalsIgnoreCase("TRUE")) {
                _oLogger.error("Invalid 'scoping' item value found in configuration: " + sScoping);
                throw new OAException(SystemErrors.ERROR_INIT);
            }
        }

        Boolean boolNameIDPolicy = new Boolean(true);
        String sNameIDFormat = null;
        Boolean boolAllowCreate = null;

        Element eNameIDPolicy = configManager.getSection(config, "nameidpolicy");
        if (eNameIDPolicy != null) {
            String sNameIDPolicyEnabled = configManager.getParam(eNameIDPolicy, "enabled");
            if (sNameIDPolicyEnabled != null) {
                if (sNameIDPolicyEnabled.equalsIgnoreCase("FALSE"))
                    boolNameIDPolicy = new Boolean(false);
                else if (!sNameIDPolicyEnabled.equalsIgnoreCase("TRUE")) {
                    _oLogger.error(
                            "Invalid 'enabled' item value in 'nameidpolicy' section found in configuration: "
                                    + sNameIDPolicyEnabled);
                    throw new OAException(SystemErrors.ERROR_INIT);
                }
            }

            if (boolNameIDPolicy) {
                String sAllowCreate = configManager.getParam(eNameIDPolicy, "allow_create");
                if (sAllowCreate != null) {
                    if (sAllowCreate.equalsIgnoreCase("TRUE"))
                        boolAllowCreate = new Boolean(true);
                    else if (sAllowCreate.equalsIgnoreCase("FALSE"))
                        boolAllowCreate = new Boolean(false);
                    else {
                        _oLogger.error(
                                "Invalid 'allow_create' item value found in configuration: " + sAllowCreate);
                        throw new OAException(SystemErrors.ERROR_INIT);
                    }
                }

                sNameIDFormat = configManager.getParam(eNameIDPolicy, "nameidformat");
            }
        }

        Boolean boolAvoidSubjectConfirmation = new Boolean(false); // default: don't avoid
        String sAvoidSC = configManager.getParam(config, "avoid_subjectconfirmation");
        if (sAvoidSC != null) {
            if (sAvoidSC.equalsIgnoreCase("TRUE"))
                boolAvoidSubjectConfirmation = new Boolean(true);
            else if (!sAvoidSC.equalsIgnoreCase("FALSE")) {
                _oLogger.error(
                        "Invalid 'avoid_subjectconfirmation' item value found in configuration: " + sAvoidSC);
                throw new OAException(SystemErrors.ERROR_INIT);
            }
        }

        Boolean boolDisableSSOForIDP = new Boolean(false); // default: don't disable
        String sDisableSSO = configManager.getParam(config, "disable_sso");
        if (sDisableSSO != null) {
            if (sDisableSSO.equalsIgnoreCase("TRUE"))
                boolDisableSSOForIDP = new Boolean(true);
            else if (!sDisableSSO.equalsIgnoreCase("FALSE")) {
                _oLogger.error("Invalid 'disable_sso' item value found in configuration: " + sDisableSSO);
                throw new OAException(SystemErrors.ERROR_INIT);
            }
        }

        saml2IDP = new SAML2IDP(sID, baSourceID, sFriendlyName, sMetadataFile, sMetadataURL,
                iMetadataURLTimeout, boolACSIndex, boolAllowCreate, boolScoping, boolNameIDPolicy,
                sNameIDFormat, boolAvoidSubjectConfirmation, boolDisableSSOForIDP, dLastModified, _sMPMId);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _oLogger.fatal("Internal error while reading organization configuration", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }

    return saml2IDP;
}

From source file:org.syncany.operations.plugin.PluginOperation.java

/**
 * Downloads the plugin JAR from the given URL to a temporary
 * local location.//from  w  w w  . j a v  a 2 s.co  m
 */
private File downloadPluginJar(String pluginJarUrl) throws Exception {
    URL pluginJarFile = new URL(pluginJarUrl);
    logger.log(Level.INFO, "Querying " + pluginJarFile + " ...");

    URLConnection urlConnection = pluginJarFile.openConnection();
    urlConnection.setConnectTimeout(2000);
    urlConnection.setReadTimeout(2000);

    File tempPluginFile = File.createTempFile("syncany-plugin", "tmp");
    tempPluginFile.deleteOnExit();

    logger.log(Level.INFO, "Downloading to " + tempPluginFile + " ...");
    FileOutputStream tempPluginFileOutputStream = new FileOutputStream(tempPluginFile);
    InputStream remoteJarFileInputStream = urlConnection.getInputStream();

    IOUtils.copy(remoteJarFileInputStream, tempPluginFileOutputStream);

    remoteJarFileInputStream.close();
    tempPluginFileOutputStream.close();

    if (!tempPluginFile.exists() || tempPluginFile.length() == 0) {
        throw new Exception("Downloading plugin file failed, URL was " + pluginJarUrl);
    }

    return tempPluginFile;
}

From source file:org.syncany.operations.plugin.PluginOperation.java

private String getRemoteListStr(String pluginId) throws Exception {
    String appVersion = Client.getApplicationVersion();
    String snapshotsEnabled = (options.isSnapshots()) ? "true" : "false";
    String pluginIdQueryStr = (pluginId != null) ? pluginId : "";
    String osStr = EnvironmentUtil.getOperatingSystemDescription();
    String archStr = EnvironmentUtil.getArchDescription();

    String apiEndpointUrl = (options.getApiEndpoint() != null) ? options.getApiEndpoint()
            : API_DEFAULT_ENDPOINT_URL;
    URL pluginListUrl = new URL(String.format(API_PLUGIN_LIST_REQUEST_FORMAT, apiEndpointUrl, appVersion,
            snapshotsEnabled, pluginIdQueryStr, osStr, archStr));

    logger.log(Level.INFO, "Querying " + pluginListUrl + " ...");
    eventBus.post(new ConnectToHostExternalEvent(pluginListUrl.getHost()));

    URLConnection urlConnection = pluginListUrl.openConnection();
    urlConnection.setConnectTimeout(2000);
    urlConnection.setReadTimeout(2000);//  w  ww  .  j  a va2s. com

    BufferedReader urlStreamReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    StringBuilder responseStringBuilder = new StringBuilder();

    String line;
    while ((line = urlStreamReader.readLine()) != null) {
        responseStringBuilder.append(line);
    }

    String responseStr = responseStringBuilder.toString();
    logger.log(Level.INFO, "Response from api.syncany.org: " + responseStr);

    return responseStr;
}

From source file:org.adaway.service.ApplyService.java

/**
 * Downloads files from hosts sources/* w  ww  . j  a v  a 2s. c o m*/
 *
 * @return return code
 */
private int download() {
    Cursor enabledHostsSourcesCursor;

    byte data[];
    int count;
    long currentLastModifiedOnline;

    int returnCode = StatusCodes.SUCCESS; // default return code

    if (Utils.isAndroidOnline(mService)) {

        showApplyNotification(mService, mService.getString(R.string.download_dialog),
                mService.getString(R.string.download_dialog), mService.getString(R.string.download_dialog));

        // output to write into
        FileOutputStream out = null;

        try {
            out = mService.openFileOutput(Constants.DOWNLOADED_HOSTS_FILENAME, Context.MODE_PRIVATE);

            mNumberOfFailedDownloads = 0;
            mNumberOfDownloads = 0;

            // get cursor over all enabled hosts source
            enabledHostsSourcesCursor = ProviderHelper.getEnabledHostsSourcesCursor(mService);

            // iterate over all hosts sources in db with cursor
            if (enabledHostsSourcesCursor.moveToFirst()) {
                do {

                    mNumberOfDownloads++;

                    InputStream is = null;
                    BufferedInputStream bis = null;
                    String currentUrl = enabledHostsSourcesCursor
                            .getString(enabledHostsSourcesCursor.getColumnIndex("url"));

                    try {
                        Log.v(Constants.TAG, "Downloading hosts file: " + currentUrl);

                        /* change URL in download dialog */
                        updateApplyNotification(mService, mService.getString(R.string.download_dialog),
                                currentUrl);

                        /* build connection */
                        URL mURL = new URL(currentUrl);
                        URLConnection connection = mURL.openConnection();
                        connection.setConnectTimeout(15000);
                        connection.setReadTimeout(30000);

                        /* connect */
                        connection.connect();
                        is = connection.getInputStream();

                        bis = new BufferedInputStream(is);
                        if (is == null) {
                            Log.e(Constants.TAG, "Stream is null");
                        }

                        /* download with progress */
                        data = new byte[1024];
                        count = 0;

                        // run while only when thread is not cancelled
                        while ((count = bis.read(data)) != -1) {
                            out.write(data, 0, count);
                        }

                        // add line seperator to add files together in one file
                        out.write(Constants.LINE_SEPERATOR.getBytes());

                        // save last modified online for later use
                        currentLastModifiedOnline = connection.getLastModified();

                        ProviderHelper.updateHostsSourceLastModifiedOnline(mService,
                                enabledHostsSourcesCursor
                                        .getInt(enabledHostsSourcesCursor.getColumnIndex(HostsSources._ID)),
                                currentLastModifiedOnline);

                    } catch (IOException e) {
                        Log.e(Constants.TAG, "Exception while downloading from " + currentUrl, e);

                        mNumberOfFailedDownloads++;

                        // set last_modified_online of failed download to 0 (not available)
                        ProviderHelper.updateHostsSourceLastModifiedOnline(mService, enabledHostsSourcesCursor
                                .getInt(enabledHostsSourcesCursor.getColumnIndex(HostsSources._ID)), 0);
                    } finally {
                        // flush and close streams
                        try {
                            if (out != null) {
                                out.flush();
                            }
                            if (bis != null) {
                                bis.close();
                            }
                            if (is != null) {
                                is.close();
                            }
                        } catch (Exception e) {
                            Log.e(Constants.TAG, "Exception on flush and closing streams.", e);
                        }
                    }

                } while (enabledHostsSourcesCursor.moveToNext());
            }

            // close cursor in the end
            if (enabledHostsSourcesCursor != null && !enabledHostsSourcesCursor.isClosed()) {
                enabledHostsSourcesCursor.close();
            }

            // if all downloads failed return download_fail error
            if (mNumberOfDownloads == mNumberOfFailedDownloads && mNumberOfDownloads != 0) {
                returnCode = StatusCodes.DOWNLOAD_FAIL;
            }
        } catch (Exception e) {
            Log.e(Constants.TAG, "Private File can not be created, Exception: " + e);
            returnCode = StatusCodes.PRIVATE_FILE_FAIL;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                Log.e(Constants.TAG, "Exception on close of out.", e);
            }
        }
    } else {
        returnCode = StatusCodes.NO_CONNECTION;
    }

    return returnCode;
}