Example usage for java.net URLConnection setReadTimeout

List of usage examples for java.net URLConnection setReadTimeout

Introduction

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

Prototype

public void setReadTimeout(int timeout) 

Source Link

Document

Sets the read timeout to a specified timeout, in milliseconds.

Usage

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);

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

    String line;/*  w  w  w .ja va2s  . c om*/
    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: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)
 *//*  ww w. j a  v  a 2  s  .  co m*/
@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.adaway.service.ApplyService.java

/**
 * Downloads files from hosts sources//from   w w  w .j a va 2 s .c  om
 *
 * @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;
}

From source file:edu.hackathon.perseus.core.httpSpeedTest.java

private double doUpload(String phpFile, InputStream uploadFileIs, String fileName) {
    URLConnection conn = null;
    OutputStream os = null;//from   ww w. j a  v  a2 s .c  om
    InputStream is = null;
    double bw = 0.0;

    try {
        String response = "";
        Date oldTime = new Date();
        URL url = new URL(amazonDomain + "/" + phpFile);
        String boundary = "---------------------------4664151417711";
        conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);

        byte[] fileData = new byte[uploadFileIs.available()];
        uploadFileIs.read(fileData);
        uploadFileIs.close();

        String message1 = "--" + boundary + CrLf;
        message1 += "Content-Disposition: form-data;";
        message1 += "name=\"uploadedfile\"; filename=\"" + fileName + "\"" + CrLf;
        message1 += "Content-Type: text/plain; charset=UTF-8" + CrLf + CrLf;

        // the file is sent between the messages in the multipart message.
        String message2 = CrLf + "--" + boundary + "--" + CrLf;

        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        int contentLenght = message1.length() + message2.length() + fileData.length;

        // might not need to specify the content-length when sending chunked data.
        conn.setRequestProperty("Content-Length", String.valueOf(contentLenght));

        os = conn.getOutputStream();

        os.write(message1.getBytes());

        // SEND THE IMAGE
        int index = 0;
        int size = 1024;
        do {
            if ((index + size) > fileData.length) {
                size = fileData.length - index;
            }
            os.write(fileData, index, size);
            index += size;
        } while (index < fileData.length);

        os.write(message2.getBytes());
        os.flush();

        is = conn.getInputStream();

        char buff = 512;
        int len;
        byte[] data = new byte[buff];
        do {
            len = is.read(data);

            if (len > 0) {
                response += new String(data, 0, len);
            }
        } while (len > 0);

        if (response.equals("200")) {
            Date newTime = new Date();
            double milliseconds = newTime.getTime() - oldTime.getTime();
            bw = ((double) contentLenght * 8) / (milliseconds * (double) 1000);
        }
    } catch (Exception e) {
        System.out.println("Exception is fired in upload test. error:" + e.getMessage());
    } finally {
        try {
            os.close();
        } catch (Exception e) {
            //System.out.println("Exception is fired in os.close. error:" + e.getMessage());
        }
        try {
            is.close();
        } catch (Exception e) {
            //System.out.println("Exception is fired in is.close. error:" + e.getMessage());
        }
    }
    return bw;
}

From source file:us.derfers.tribex.rapids.Loader.java

/**
 * Loads scripts and styles from link tags.
 * @param linkElement The element from which to load the content from.
 * @param engine The ScriptEngine to run links to scripts in.
 * @return/*from   w ww .  j a va 2s  .c  o  m*/
 */
private boolean parseLinks(Element linkElement, ScriptEngine engine) {

    //Check and see if the <link> tag contains a rel and href attribute
    if (linkElement.getAttribute("href") != null) {
        //If it links to a stylesheet
        if ((linkElement.getAttributeNode("rel") != null
                && linkElement.getAttributeNode("rel").getTextContent().equals("stylesheet"))
                || linkElement.getAttributeNode("href").getTextContent().endsWith(".css")) {

            //Check and see if the href and URL exist.
            if (linkElement.getAttributeNode("href").getNodeValue().contains("://")) {
                try {
                    if (this.loadStyles(
                            IOUtils.toString(new URL(linkElement.getAttributeNode("href").getNodeValue())),
                            null) == false) {
                        Utilities.showError("Error: invalid file in link tag pointing to "
                                + linkElement.getAttributeNode("href").getTextContent());
                        return false;
                    }

                    if (linkElement.getAttributeNode("cache") != null) {
                        try {
                            FileUtils.writeStringToFile(
                                    new File(Globals
                                            .getCWD(linkElement.getAttributeNode("cache").getTextContent())),
                                    IOUtils.toString(
                                            new URL(linkElement.getAttributeNode("href").getNodeValue())));
                        } catch (Exception e2) {
                            Utilities.showError("Error: unable to cache to file "
                                    + linkElement.getAttributeNode("cache").getTextContent());
                        }
                    }

                } catch (Exception e) {
                    Utilities.showError(
                            "Unable to locate " + linkElement.getAttributeNode("href").getNodeValue());
                    //Attempt to load from the fallback file. (If tag and file exist)
                    if (linkElement.getAttributeNode("fallback") != null) {
                        if (this.loadStyles(null, Globals
                                .getCWD(linkElement.getAttributeNode("fallback").getTextContent())) == false) {
                            Utilities.showError("Error: invalid file in fallback tag pointing to "
                                    + linkElement.getAttributeNode("fallback").getTextContent());
                            return false;
                        }
                        ;
                    }
                }
                //Load from file
            } else {
                if (this.loadStyles(null,
                        Globals.getCWD(linkElement.getAttributeNode("href").getTextContent())) == false) {
                    Utilities.showError("Error: invalid file in link tag pointing to "
                            + linkElement.getAttributeNode("href").getTextContent());
                    return false;
                }
                ;
            }

            //If it links to a script
        } else if ((linkElement.getAttributeNode("rel") != null
                && linkElement.getAttributeNode("rel").getTextContent().equals("script"))
                || linkElement.getAttributeNode("href").getTextContent().endsWith(".js")) {

            //Check and see if the file exists
            if (linkElement.getAttributeNode("href").getNodeValue().contains("://")) {
                //Run script in file
                URL url;
                try {
                    url = new URL(linkElement.getAttributeNode("href").getTextContent());

                    URLConnection connection = url.openConnection();
                    connection.setConnectTimeout(10000);
                    connection.setReadTimeout(10000);
                    engine.eval(new InputStreamReader(connection.getInputStream()),
                            "Remote file: " + linkElement.getAttributeNode("href").getTextContent());

                    if (linkElement.getAttributeNode("cache") != null) {
                        try {
                            FileUtils.writeStringToFile(
                                    new File(Globals
                                            .getCWD(linkElement.getAttributeNode("cache").getTextContent())),
                                    IOUtils.toString(
                                            new URL(linkElement.getAttributeNode("href").getNodeValue())));
                        } catch (Exception e2) {
                            Utilities.showError("Error: unable to cache to file "
                                    + linkElement.getAttributeNode("cache").getTextContent());
                        }
                    }

                    return true;
                } catch (Exception e) {
                    //Attempt to load from the fallback file. (If tag and file exist)
                    if (linkElement.getAttributeNode("fallback") != null) {
                        try {
                            engine.eval(
                                    new java.io.FileReader(Globals
                                            .getCWD(linkElement.getAttributeNode("fallback").getTextContent())),
                                    linkElement.getAttributeNode("fallback").getTextContent());
                        } catch (Exception e2) {
                            Utilities.showError("Error: invalid file in fallback tag pointing to "
                                    + linkElement.getAttributeNode("fallback").getTextContent());
                        }
                    } else {
                        Utilities.showError(
                                "Unable to load " + linkElement.getAttributeNode("href").getTextContent()
                                        + ". No fallback found.");
                    }

                }

            } else {
                try {
                    //Run script in file
                    engine.eval(
                            new java.io.FileReader(
                                    Globals.getCWD(linkElement.getAttributeNode("href").getTextContent())),
                            linkElement.getAttributeNode("href").getTextContent());
                    return true;

                } catch (FileNotFoundException e) {
                    Utilities.showError("Error: invalid file in link tag pointing to "
                            + linkElement.getAttributeNode("href").getTextContent());
                    e.printStackTrace();
                    return false;
                } catch (DOMException e) {
                    Utilities.showError("Error: Improperly formatted XML");
                    e.printStackTrace();
                    return false;
                } catch (Exception e) {
                    Utilities.showError("Error: invalid script in file "
                            + linkElement.getAttributeNode("href").getTextContent());
                    e.printStackTrace();
                    return false;
                }
            }
        } else {
            //Attempt to load as a .rsm file

            //If the file is a URL on the internet:
            if (linkElement.getAttributeNode("href").getNodeValue().contains("://")) {
                try {
                    //Load the file from the internet.
                    Main.loader.loadAll(Utilities.EscapeScriptTags(
                            IOUtils.toString(new URL(linkElement.getAttributeNode("href").getNodeValue()))));

                    if (linkElement.getAttributeNode("cache") != null) {
                        try {
                            FileUtils.writeStringToFile(
                                    new File(Globals
                                            .getCWD(linkElement.getAttributeNode("cache").getTextContent())),
                                    IOUtils.toString(
                                            new URL(linkElement.getAttributeNode("href").getNodeValue())));
                        } catch (Exception e2) {
                            Utilities.showError("Error: unable to cache to file "
                                    + linkElement.getAttributeNode("cache").getTextContent());
                        }
                    }
                } catch (Exception e) {
                    if (linkElement.getAttributeNode("fallback") != null) {
                        try {
                            Main.loader.loadAll(Utilities.EscapeScriptTags(FileUtils.readFileToString(new File(
                                    Globals.getCWD(linkElement.getAttributeNode("fallback").getNodeValue())))));
                        } catch (Exception e2) {
                            Utilities.showError("Error: invalid file in fallback tag pointing to "
                                    + linkElement.getAttributeNode("fallback").getTextContent());
                        }
                    }
                }

                //Load the file from the Hard Drive
            } else {
                try {
                    Main.loader.loadAll(Utilities.EscapeScriptTags(FileUtils.readFileToString(
                            new File(Globals.getCWD(linkElement.getAttributeNode("href").getNodeValue())))));
                } catch (DOMException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    } else {
        System.out.println(linkElement.toString());
        Utilities.showError(
                "Warning: <link> tags must contain a href attribute and a rel attribute. Skipping tag.");
    }
    return false;
}

From source file:io.hummer.util.ws.WebServiceClient.java

private InvocationResult doInvokeGET(String parameters, Map<String, String> httpHeaders, int retries,
        long connectTimeoutMS, long readTimeoutMS, boolean doUseCache) throws Exception {
    if (retries < 0)
        throw new Exception("Invocation to " + endpointURL + " failed: " + xmlUtil.toString(parameters));

    String host = new URL(endpointURL).getHost();
    if (!lastRequestedHosts.containsKey(host)) {
        lastRequestedHosts.put(host, new AtomicLong());
    }/*from ww w  .  j  ava2  s.c  om*/
    Object lockForTargetHost = lastRequestedHosts.get(host);

    parameters = parameters.trim();
    String urlString = endpointURL;
    if (!strUtil.isEmpty(parameters)) {
        String separator = endpointURL.contains("?") ? "&" : "?";
        urlString = endpointURL + separator + parameters;
    }

    if (doUseCache) {
        /** retrieve result from document cache */
        CacheEntry existing = cache.get(urlString);
        if (existing != null && !strUtil.isEmpty(existing.value)) {
            String valueShort = (String) existing.value;
            if (valueShort.length() > 200)
                valueShort = valueShort.substring(0, 200) + "...";
            AtomicReference<Element> eRef = new AtomicReference<Element>();
            Parallelization.warnIfNoResultAfter(eRef, "! Client could not convert element ("
                    + existing.value.length() + " bytes) within 15 seconds: " + valueShort, 15 * 1000);
            Parallelization.warnIfNoResultAfter(eRef, "! Client could not convert element ("
                    + existing.value.length() + " bytes) within 40 seconds: " + valueShort, 40 * 1000);
            Element e = xmlUtil.toElement((String) existing.value);
            eRef.set(e);
            logger.info("Result exists in cache for URL " + urlString + " - " + e + " - "
                    + this.xmlUtil.toString().length());
            return new InvocationResult(e);
        }
    }

    pauseToAvoidSpamming();

    URL url = new URL(urlString);
    URLConnection c = url.openConnection();
    c.setConnectTimeout((int) connectTimeoutMS);
    c.setReadTimeout((int) readTimeoutMS);
    logger.info("Retrieving data from service using GET: " + url);

    String tmpID = PerformanceInterceptor.event(EventType.START_HTTP_GET);
    for (String key : httpHeaders.keySet()) {
        c.setRequestProperty(key, httpHeaders.get(key));
    }
    StringBuilder b = new StringBuilder();
    synchronized (lockForTargetHost) {
        try {
            BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream()));
            String temp;
            while ((temp = r.readLine()) != null) {
                b.append(temp);
                b.append("\n");
            }
        } catch (Exception e) {
            logger.info("Could not GET page with regular URLConnection, trying HtmlUnit..: " + e);
            b = getPageUsingHtmlUnit(urlString, httpHeaders, readTimeoutMS, null);
        }
    }

    PerformanceInterceptor.event(EventType.FINISH_HTTP_GET, tmpID);

    String tmpID1 = PerformanceInterceptor.event(EventType.START_RESPONSE_TO_XML);
    String result = b.toString().trim();
    if (!result.startsWith("<") || !result.endsWith(">")) { // wrap non-xml results (e.g., CSV files)
        StringBuilder sb = new StringBuilder("<doc><![CDATA[");
        sb.append(result);
        sb.append("]]></doc>");
        result = sb.toString();
    }

    String tmpID2 = PerformanceInterceptor.event(EventType.START_STRING_TO_XML);
    Element resultElement = xmlUtil.toElement(result);
    PerformanceInterceptor.event(EventType.FINISH_STRING_TO_XML, tmpID2);

    if (doUseCache) {
        /** put result element to document cache */
        cache.putWithoutWaiting(urlString, xmlUtil.toString(resultElement, true));
    }

    InvocationResult invResult = new InvocationResult(resultElement);
    PerformanceInterceptor.event(EventType.FINISH_RESPONSE_TO_XML, tmpID1);

    return invResult;
}

From source file:org.xbmc.jsonrpc.Connection.java

/**
 * Executes a query./*from   w w  w.  ja  v  a2  s .  c  o  m*/
 * @param command    Name of the command to execute
 * @param parameters Parameters
 * @param manager    Reference back to business layer
 * @return Parsed JSON object, empty object on error.
 */
public JsonNode query(String command, JsonNode parameters, INotifiableManager manager) {
    URLConnection uc = null;
    try {
        final ObjectMapper mapper = Client.MAPPER;

        if (mUrlSuffix == null) {
            throw new NoSettingsException();
        }

        final URL url = new URL(mUrlSuffix + XBMC_JSONRPC_BOOTSTRAP);
        uc = url.openConnection();
        uc.setConnectTimeout(SOCKET_CONNECTION_TIMEOUT);
        uc.setReadTimeout(mSocketReadTimeout);
        if (authEncoded != null) {
            uc.setRequestProperty("Authorization", "Basic " + authEncoded);
        }
        uc.setRequestProperty("Content-Type", "application/json");
        uc.setDoOutput(true);

        final ObjectNode data = Client.obj().p("jsonrpc", "2.0").p("method", command).p("id", "1");
        if (parameters != null) {
            data.put("params", parameters);
        }

        final JsonFactory jsonFactory = new JsonFactory();
        final JsonGenerator jg = jsonFactory.createJsonGenerator(uc.getOutputStream(), JsonEncoding.UTF8);
        jg.setCodec(mapper);

        // POST data
        jg.writeTree(data);
        jg.flush();

        final JsonParser jp = jsonFactory.createJsonParser(uc.getInputStream());
        jp.setCodec(mapper);
        final JsonNode ret = jp.readValueAs(JsonNode.class);
        return ret;

    } catch (MalformedURLException e) {
        manager.onError(e);
    } catch (IOException e) {
        int responseCode = -1;
        try {
            responseCode = ((HttpURLConnection) uc).getResponseCode();
        } catch (IOException e1) {
        } // do nothing, getResponse code failed so treat as default i/o exception.
        if (uc != null && responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            manager.onError(new HttpException(Integer.toString(HttpURLConnection.HTTP_UNAUTHORIZED)));
        } else {
            manager.onError(e);
        }
    } catch (NoSettingsException e) {
        manager.onError(e);
    }
    return new ObjectNode(null);
}

From source file:com.dotosoft.dotoquiz.tools.thirdparty.PicasawebClient.java

public boolean downloadPhoto(File saveLocation, PhotoEntry photo) throws IOException, ParseException {
    boolean downloadSuccess = false;
    final int BUFFER_SIZE = 8096;
    final int TIMEOUT_MS = 10 * 1000;

    File saveFolder = saveLocation.getParentFile();
    boolean createdFolder = false;

    if (!saveFolder.exists()) {
        log.info("Creating local folder: " + saveFolder.getName());
        if (!saveFolder.mkdirs())
            throw new IOException("Unable to create folder " + saveFolder.getName());
        createdFolder = true;//from   w ww. ja v a2 s  .c  o  m
    }

    log.debug("Beginning download for " + saveLocation + "...");

    File tempFile = new File(saveLocation + ".tmp");
    tempFile.deleteOnExit();

    FileOutputStream fos = new FileOutputStream(tempFile);

    List<MediaContent> media = photo.getMediaContents();
    URL fileUrl = new URL(photo.getMediaContents().get(0).getUrl());

    if (media.size() > 1) {
        if (media.size() > 2) {
            log.debug("Extracting h264 video stream...");
            fileUrl = new URL(photo.getMediaContents().get(2).getUrl());
        } else {
            log.debug("Extracting low-res video stream...");
            fileUrl = new URL(photo.getMediaContents().get(1).getUrl());
        }
    }

    try {
        URLConnection conn = fileUrl.openConnection();
        conn.setConnectTimeout(TIMEOUT_MS);
        conn.setReadTimeout(TIMEOUT_MS);
        InputStream dis = conn.getInputStream();

        int totalRead = 0;
        int readCount = 0;
        byte b[] = new byte[BUFFER_SIZE];
        while ((readCount = dis.read(b)) != 0 && readCount != -1) {
            totalRead += readCount;
            fos.write(b, 0, readCount);
        }
        dis.close();
        fos.close();

        if (!tempFile.renameTo(saveLocation))
            throw new IOException("Unable to rename temp file to " + saveLocation);

        // Fix up the timestamps from the photo metadata
        updateTimeFromTags(saveLocation, photo, createdFolder);

        log.info("Written " + FileUtils.byteCountToDisplaySize(totalRead) + " to " + saveLocation
                + " successfully.");
        downloadSuccess = true;
    } catch (ConnectException ex) {
        log.warn("Network connection downloading " + fileUrl, ex);
        saveLocation = null;
    } catch (Exception ex) {
        log.error("Unexpected exception downloading " + fileUrl, ex);
        saveLocation = null;

    }

    return downloadSuccess;
}

From source file:org.wso2.emm.system.service.api.OTAServerManager.java

public void startDownloadUpgradePackage(final OTAServerManager serverManager) {
    if (asyncTask != null) {
        asyncTask.cancel(true);/*  ww w  .  j  a  va2s .c om*/
    }
    asyncTask = new AsyncTask<Void, Void, Void>() {
        protected Void doInBackground(Void... unused) {
            Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status),
                    Constants.Status.OTA_UPGRADE_ONGOING);
            File targetFile = new File(FileUtils.getUpgradePackageFilePath());
            if (targetFile.exists()) {
                targetFile.delete();
            }
            try {
                boolean fileStatus = targetFile.createNewFile();
                if (!fileStatus) {
                    Log.e(TAG, "Update package file creation failed.");
                }
            } catch (IOException e) {
                String message = "Update package file retrieval error.";
                Log.e(TAG, message + e);
                reportDownloadError(OTAStateChangeListener.ERROR_WRITE_FILE_ERROR);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.INTERNAL_ERROR, message);
            }

            try {
                wakeLock.acquire();

                URL url = serverConfig.getPackageURL();
                Log.d(TAG, "Start downloading package:" + url.toString());
                URLConnection connection = url.openConnection();
                connection.setConnectTimeout(Constants.FIRMWARE_UPGRADE_CONNECTIVITY_TIMEOUT);
                connection.setReadTimeout(Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                lengthOfFile = connection.getContentLength();
                downloadedLength = 0;
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(targetFile);
                Timer timeoutTimer = new Timer();
                Log.d(TAG, "Update package file size:" + lengthOfFile);
                if (getFreeDiskSpace() < lengthOfFile) {
                    String message = "Device does not have enough memory to download the OTA" + " update";
                    CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                            Constants.Code.FAILURE, Constants.Status.LOW_DISK_SPACE, message);
                    CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_FAILURE,
                            Preference.getInt(context, context.getResources().getString(R.string.operation_id)),
                            message);
                    Log.e(TAG, message);
                    return null;
                }
                byte data[] = new byte[DEFAULT_BYTES];
                long count;
                isProgressUpdateTerminated = false;
                executor = new DownloadProgressUpdateExecutor();
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        while (lengthOfFile > downloadedLength && !isProgressUpdateTerminated) {
                            Preference.putString(context,
                                    context.getResources().getString(R.string.upgrade_download_status),
                                    Constants.Status.OTA_UPGRADE_ONGOING);
                            publishDownloadProgress(lengthOfFile, downloadedLength);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException ignored) {
                            }
                        }
                    }
                });
                while ((count = input.read(data)) >= 0) {
                    downloadedLength += count;
                    output.write(data, DEFAULT_OFFSET, (int) count);
                    timeoutTimer.cancel();
                    timeoutTimer = new Timer();
                    timeoutTimer.schedule(new Timeout(this), Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
                }
                publishDownloadProgress(lengthOfFile, downloadedLength);
                isProgressUpdateTerminated = true;
                timeoutTimer.cancel();
                output.flush();
                output.close();
                input.close();
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        context.getResources().getString(R.string.status_success));
                if (serverManager.stateChangeListener != null) {
                    serverManager.stateChangeListener.onStateOrProgress(
                            OTAStateChangeListener.STATE_IN_DOWNLOADING, DEFAULT_STATE_ERROR_CODE, null,
                            DEFAULT_STATE_INFO_CODE);
                }
            } catch (SocketTimeoutException e) {
                String message = "Connection failure (Socket timeout) when downloading update package.";
                Log.e(TAG, message + e);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.CONNECTION_FAILED, message);
                CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0,
                        null);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.CONNECTION_FAILED);
            } catch (IOException e) {
                String message = "Unable to find firmware upgrade package "
                        + serverConfig.getPackageURL().toString();
                Log.e(TAG, message + e);
                CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE,
                        Constants.Status.FILE_NOT_FOUND, message);
                CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0,
                        null);
                reportDownloadError(OTAStateChangeListener.ERROR_WRITE_FILE_ERROR);
                Preference.putString(context,
                        context.getResources().getString(R.string.upgrade_download_status),
                        Constants.Status.FILE_NOT_FOUND);
            } finally {
                wakeLock.release();
                wakeLock.acquire(2);
                if (targetFile.exists() && lengthOfFile != downloadedLength) {
                    targetFile.delete();
                    String status = Preference.getString(context,
                            context.getResources().getString(R.string.upgrade_download_status));
                    if (!Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) {
                        Preference.putString(context,
                                context.getResources().getString(R.string.upgrade_download_status),
                                Constants.Status.OTA_DOWNLOAD_FAILED);
                    }
                }
            }
            return null;
        }
    }.executeOnExecutor(threadPoolExecutor);
}