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.apache.tez.engine.common.shuffle.impl.Fetcher.java

/** 
 * The connection establishment is attempted multiple times and is given up 
 * only on the last failure. Instead of connecting with a timeout of 
 * X, we try connecting with a timeout of x < X but multiple times. 
 *///ww w  .j a v a 2  s . co  m
private void connect(URLConnection connection, int connectionTimeout) throws IOException {
    int unit = 0;
    if (connectionTimeout < 0) {
        throw new IOException("Invalid timeout " + "[timeout = " + connectionTimeout + " ms]");
    } else if (connectionTimeout > 0) {
        unit = Math.min(UNIT_CONNECT_TIMEOUT, connectionTimeout);
    }
    // set the connect timeout to the unit-connect-timeout
    connection.setConnectTimeout(unit);
    while (true) {
        try {
            connection.connect();
            break;
        } catch (IOException ioe) {
            // update the total remaining connect-timeout
            connectionTimeout -= unit;

            // throw an exception if we have waited for timeout amount of time
            // note that the updated value if timeout is used here
            if (connectionTimeout == 0) {
                throw ioe;
            }

            // reset the connect timeout for the last try
            if (connectionTimeout < unit) {
                unit = connectionTimeout;
                // reset the connect time out for the final connect
                connection.setConnectTimeout(unit);
            }
        }
    }
}

From source file:org.hw.parlance.ParlanceActivity.java

/**
 * Method to parse XML response from Yahoo URL and add markers of restaurants on the map
 *//*from w w w . ja  va2  s .com*/
private synchronized void xmlParsing(String XMLResponse) {
    try {
        URLConnection conn = new URL(XMLResponse).openConnection();
        conn.setConnectTimeout(50000);
        conn.setReadTimeout(50000);
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        ItemHandler itemHandler = new ItemHandler();
        xr.setContentHandler(itemHandler);
        xr.parse(new InputSource(conn.getInputStream()));

        _itemAdapter.arr = itemHandler.getList();

        for (int index = 0; index < _itemAdapter.arr.size(); index++) {

            Marker temp_marker = mMap.addMarker(new MarkerOptions()
                    .position(new LatLng(Double.parseDouble(_itemAdapter.arr.get(index).getLat()),
                            Double.parseDouble(_itemAdapter.arr.get(index).getLon())))
                    .title(_itemAdapter.arr.get(index).getName())
                    .icon(BitmapDescriptorFactory.fromResource(numMarkerIcon[index])));

            this._markList.add(temp_marker);
        }

        _itemAdapter.notifyDataSetChanged();

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:ch.cyberduck.core.gdocs.GDSession.java

protected HttpURLConnection getConnection(URL url) throws IOException {
    URLConnection c = null;
    if (Preferences.instance().getBoolean("connection.proxy.enable")) {
        final Proxy proxy = ProxyFactory.instance();
        if (proxy.isHTTPSProxyEnabled(new Host(Protocol.GDOCS_SSL, url.getHost(), url.getPort()))) {
            c = url.openConnection(new java.net.Proxy(java.net.Proxy.Type.HTTP,
                    new InetSocketAddress(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host))));
        }//w  ww . j a  v a 2 s.  com
    }
    if (null == c) {
        log.debug("Direct connection");
        c = url.openConnection();
    }
    c.setConnectTimeout(timeout());
    c.setReadTimeout(timeout());
    if (c instanceof HttpsURLConnection) {
        ((HttpsURLConnection) c).setSSLSocketFactory(
                new CustomTrustSSLProtocolSocketFactory(this.getTrustManager(url.getHost())));
        ((HttpsURLConnection) c).setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String s, javax.net.ssl.SSLSession sslSession) {
                return true;
            }
        });
    }
    if (c instanceof HttpURLConnection) {
        return (HttpURLConnection) c;
    }
    throw new ConnectionCanceledException("Invalid URL connection:" + c);
}

From source file:org.apache.hadoop.mapred.JobClient.java

private static void getTaskLogs(TaskAttemptID taskId, URL taskLogUrl, OutputStream out) {
    try {/*from  ww w . j a va2 s  . c  o m*/
        URLConnection connection = taskLogUrl.openConnection();
        connection.setReadTimeout(tasklogtimeout);
        connection.setConnectTimeout(tasklogtimeout);
        BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        BufferedWriter output = new BufferedWriter(new OutputStreamWriter(out));
        try {
            String logData = null;
            while ((logData = input.readLine()) != null) {
                if (logData.length() > 0) {
                    output.write(taskId + ": " + logData + "\n");
                    output.flush();
                }
            }
        } finally {
            input.close();
        }
    } catch (IOException ioe) {
        LOG.warn("Error reading task output" + ioe.getMessage());
    }
}

From source file:com.miz.apis.thetvdb.TheTVDbService.java

@Override
public TvShow get(String id, String language) {
    TvShow show = new TvShow();
    show.setId(id);/*from   www  . ja v a2s  .  com*/

    // Show details
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        URL url = new URL(
                "http://thetvdb.com/api/" + mTvdbApiKey + "/series/" + show.getId() + "/" + language + ".xml");

        URLConnection con = url.openConnection();
        con.setReadTimeout(60000);
        con.setConnectTimeout(60000);

        Document doc = db.parse(con.getInputStream());
        doc.getDocumentElement().normalize();

        NodeList nodeList = doc.getElementsByTagName("Series");
        if (nodeList.getLength() > 0) {
            Node firstNode = nodeList.item(0);
            if (firstNode.getNodeType() == Node.ELEMENT_NODE) {
                Element firstElement = (Element) firstNode;
                NodeList list;
                Element element;
                NodeList tag;

                try {
                    list = firstElement.getElementsByTagName("SeriesName");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    show.setTitle((tag.item(0)).getNodeValue());
                } catch (Exception e) {
                }

                try {
                    list = firstElement.getElementsByTagName("Overview");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    show.setDescription((tag.item(0)).getNodeValue());
                } catch (Exception e) {
                }

                try {
                    list = firstElement.getElementsByTagName("Actors");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    show.setActors((tag.item(0)).getNodeValue());
                } catch (Exception e) {
                }

                try {
                    list = firstElement.getElementsByTagName("Genre");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    show.setGenres((tag.item(0)).getNodeValue());
                } catch (Exception e) {
                }

                try {
                    list = firstElement.getElementsByTagName("Rating");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    show.setRating((tag.item(0)).getNodeValue());
                } catch (Exception e) {
                    show.setRating("0");
                }

                try {
                    list = firstElement.getElementsByTagName("poster");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    show.setCoverUrl("http://thetvdb.com/banners/" + tag.item(0).getNodeValue());
                } catch (Exception e) {
                }

                try {
                    list = firstElement.getElementsByTagName("fanart");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    show.setBackdropUrl("http://thetvdb.com/banners/" + tag.item(0).getNodeValue());
                } catch (Exception e) {
                }

                try {
                    list = firstElement.getElementsByTagName("ContentRating");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    show.setCertification(tag.item(0).getNodeValue());
                } catch (Exception e) {
                }

                try {
                    list = firstElement.getElementsByTagName("Runtime");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    show.setRuntime(tag.item(0).getNodeValue());
                } catch (Exception e) {
                }

                try {
                    list = firstElement.getElementsByTagName("FirstAired");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    show.setFirstAired(tag.item(0).getNodeValue());
                } catch (Exception e) {
                }

                try {
                    list = firstElement.getElementsByTagName("IMDB_ID");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    show.setIMDbId(tag.item(0).getNodeValue());
                } catch (Exception e) {
                }
            }
        }

        // Trakt.tv
        if (getRatingsProvider().equals(mContext.getString(R.string.ratings_option_2))) {
            try {
                Show showSummary = Trakt.getShowSummary(mContext, id);
                double rating = Double.valueOf(showSummary.getRating() / 10);

                if (rating > 0 || show.getRating().equals("0.0"))
                    show.setRating(String.valueOf(rating));
            } catch (Exception e) {
            }
        }

        // OMDb API / IMDb
        if (getRatingsProvider().equals(mContext.getString(R.string.ratings_option_3))) {
            try {
                JSONObject jObject = MizLib.getJSONObject(mContext,
                        "http://www.omdbapi.com/?i=" + show.getImdbId());
                double rating = Double.valueOf(MizLib.getStringFromJSONObject(jObject, "imdbRating", "0"));

                if (rating > 0 || show.getRating().equals("0.0"))
                    show.setRating(String.valueOf(rating));
            } catch (Exception e) {
            }
        }
    } catch (Exception e) {
    }

    // Episode details
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        URL url = new URL("http://thetvdb.com/api/" + mTvdbApiKey + "/series/" + show.getId() + "/all/"
                + language + ".xml");

        URLConnection con = url.openConnection();
        con.setReadTimeout(60000);
        con.setConnectTimeout(60000);

        Document doc = db.parse(con.getInputStream());
        doc.getDocumentElement().normalize();

        NodeList nodeList = doc.getElementsByTagName("Episode");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node firstNode = nodeList.item(i);
            if (firstNode.getNodeType() == Node.ELEMENT_NODE) {
                Element firstElement = (Element) firstNode;
                NodeList list;
                Element element;
                NodeList tag;

                Episode episode = new Episode();

                if (useDvdOrder()) {
                    try {
                        list = firstElement.getElementsByTagName("DVD_episodenumber");
                        element = (Element) list.item(0);
                        tag = element.getChildNodes();
                        episode.setEpisode(MizLib.getInteger(Double.valueOf(tag.item(0).getNodeValue())));
                    } catch (Exception e) {
                    }
                }

                if (episode.getEpisode() == -1) {
                    try {
                        list = firstElement.getElementsByTagName("EpisodeNumber");
                        element = (Element) list.item(0);
                        tag = element.getChildNodes();
                        episode.setEpisode(MizLib.getInteger(tag.item(0).getNodeValue()));
                    } catch (Exception e) {
                        episode.setEpisode(0);
                    }
                }

                if (useDvdOrder()) {
                    try {
                        list = firstElement.getElementsByTagName("DVD_season");
                        element = (Element) list.item(0);
                        tag = element.getChildNodes();
                        episode.setSeason(MizLib.getInteger(tag.item(0).getNodeValue()));
                    } catch (Exception e) {
                    }
                }

                if (episode.getSeason() == -1) {
                    try {
                        list = firstElement.getElementsByTagName("SeasonNumber");
                        element = (Element) list.item(0);
                        tag = element.getChildNodes();
                        episode.setSeason(MizLib.getInteger(tag.item(0).getNodeValue()));
                    } catch (Exception e) {
                        episode.setSeason(0);
                    }
                }

                try {
                    list = firstElement.getElementsByTagName("EpisodeName");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    episode.setTitle(tag.item(0).getNodeValue());
                } catch (Exception e) {
                }

                try {
                    list = firstElement.getElementsByTagName("FirstAired");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    episode.setAirdate(tag.item(0).getNodeValue());
                } catch (Exception e) {
                }

                try {
                    list = firstElement.getElementsByTagName("Overview");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    episode.setDescription(tag.item(0).getNodeValue());
                } catch (Exception e) {
                }

                try {
                    list = firstElement.getElementsByTagName("filename");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    episode.setScreenshotUrl("http://thetvdb.com/banners/" + tag.item(0).getNodeValue());
                } catch (Exception e) {
                }

                try {
                    list = firstElement.getElementsByTagName("Rating");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    episode.setRating(tag.item(0).getNodeValue());
                } catch (Exception e) {
                    episode.setRating("0");
                }

                try {
                    list = firstElement.getElementsByTagName("Director");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    episode.setDirector(tag.item(0).getNodeValue());
                } catch (Exception e) {
                }

                try {
                    list = firstElement.getElementsByTagName("Writer");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    episode.setWriter(tag.item(0).getNodeValue());
                } catch (Exception e) {
                }

                try {
                    list = firstElement.getElementsByTagName("GuestStars");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    episode.setGueststars(tag.item(0).getNodeValue());
                } catch (Exception e) {
                }

                show.addEpisode(episode);
            }
        }
    } catch (Exception e) {
    }

    // Season covers
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        URL url = new URL("http://thetvdb.com/api/" + mTvdbApiKey + "/series/" + show.getId() + "/banners.xml");

        URLConnection con = url.openConnection();
        con.setReadTimeout(60000);
        con.setConnectTimeout(60000);

        Document doc = db.parse(con.getInputStream());
        doc.getDocumentElement().normalize();

        NodeList nodeList = doc.getElementsByTagName("Banner");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node firstNode = nodeList.item(i);
            if (firstNode.getNodeType() == Node.ELEMENT_NODE) {
                Element firstElement = (Element) firstNode;
                NodeList list;
                Element element;
                NodeList tag;

                Season season = new Season();

                String bannerType = "";
                int seasonNumber = -1;

                try {
                    list = firstElement.getElementsByTagName("BannerType");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    bannerType = tag.item(0).getNodeValue();
                } catch (Exception e) {
                }

                if (!bannerType.equals("season"))
                    continue;

                try {
                    list = firstElement.getElementsByTagName("Season");
                    element = (Element) list.item(0);
                    tag = element.getChildNodes();
                    seasonNumber = Integer.valueOf(tag.item(0).getNodeValue());
                } catch (Exception e) {
                }

                if (seasonNumber >= 0 && !show.hasSeason(seasonNumber)) {
                    season.setSeason(seasonNumber);

                    try {
                        list = firstElement.getElementsByTagName("BannerPath");
                        element = (Element) list.item(0);
                        tag = element.getChildNodes();
                        season.setCoverPath("http://thetvdb.com/banners/" + tag.item(0).getNodeValue());
                    } catch (Exception e) {
                        season.setCoverPath("");
                    }

                    show.addSeason(season);
                }
            }
        }
    } catch (Exception e) {
    }

    return show;
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

/**
 * Tries to download the contents of the provided url using commercially validated CA certificate from chosen provider.
 *
 * @param string_url//w  ww  .  j  a  v a  2 s. c  o m
 * @return
 */
private String downloadWithCommercialCA(String string_url) {

    String json_file_content = "";

    URL provider_url = null;
    int seconds_of_timeout = 1;
    try {
        provider_url = new URL(string_url);
        URLConnection url_connection = provider_url.openConnection();
        url_connection.setConnectTimeout(seconds_of_timeout * 1000);
        if (!LeapSRPSession.getToken().isEmpty())
            url_connection.addRequestProperty(LeapSRPSession.AUTHORIZATION_HEADER,
                    "Token token = " + LeapSRPSession.getToken());
        json_file_content = new Scanner(url_connection.getInputStream()).useDelimiter("\\A").next();
    } catch (MalformedURLException e) {
        json_file_content = formatErrorMessage(R.string.malformed_url);
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
        json_file_content = formatErrorMessage(R.string.server_unreachable_message);
    } catch (SSLHandshakeException e) {
        if (provider_url != null) {
            json_file_content = downloadWithProviderCA(string_url);
        } else {
            json_file_content = formatErrorMessage(R.string.certificate_error);
        }
    } catch (ConnectException e) {
        json_file_content = formatErrorMessage(R.string.service_is_down_error);
    } catch (FileNotFoundException e) {
        json_file_content = formatErrorMessage(R.string.malformed_url);
    } catch (Exception e) {
        e.printStackTrace();
        if (provider_url != null) {
            json_file_content = downloadWithProviderCA(string_url);
        }
    }

    return json_file_content;
}

From source file:org.eclipse.kapua.app.console.server.GwtDeviceManagementServiceImpl.java

/**
 * Checks the source of the icon./*w  ww .  jav a  2s  . co  m*/
 * The component config icon can be one of the well known icon (i.e. MqttDataTransport icon)
 * as well as an icon loaded from external source with an HTTP link.
 *
 * We need to filter HTTP link to protect the console page and also to have content always served from
 * EC console. Otherwise browsers can alert the user that content is served from domain different from
 * *.everyware-cloud.com and over insicure connection.
 *
 * To avoid this we will download the image locally on the server temporary directory and give back the page
 * a token URL to get the file.
 *
 * @param icon
 *            The icon from the OCD of the component configuration.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws ImageReadException
 */
private void checkIconResource(KapuaTicon icon) {
    ConsoleSetting config = ConsoleSetting.getInstance();

    String iconResource = icon.getResource();

    //
    // Check if the resource is an HTTP URL or not
    if (iconResource != null && (iconResource.toLowerCase().startsWith("http://")
            || iconResource.toLowerCase().startsWith("https://"))) {
        File tmpFile = null;

        try {
            logger.info("Got configuration component icon from URL: {}", iconResource);

            //
            // Tmp file name creation
            String systemTmpDir = System.getProperty("java.io.tmpdir");
            String iconResourcesTmpDir = config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER);
            String tmpFileName = Base64.encodeBase64String(
                    MessageDigest.getInstance("MD5").digest(iconResource.getBytes("UTF-8")));

            // Conversions needed got security reasons!
            // On the file servlet we use the regex [0-9A-Za-z]{1,} to validate the given file id.
            // This validation prevents the caller of the file servlet to try to move out of the directory where the icons are stored.
            tmpFileName = tmpFileName.replaceAll("/", "a");
            tmpFileName = tmpFileName.replaceAll("\\+", "m");
            tmpFileName = tmpFileName.replaceAll("=", "z");

            //
            // Tmp dir check and creation
            StringBuilder tmpDirPathSb = new StringBuilder().append(systemTmpDir);
            if (!systemTmpDir.endsWith("/")) {
                tmpDirPathSb.append("/");
            }
            tmpDirPathSb.append(iconResourcesTmpDir);

            File tmpDir = new File(tmpDirPathSb.toString());
            if (!tmpDir.exists()) {
                logger.info("Creating tmp dir on path: {}", tmpDir.toString());
                tmpDir.mkdir();
            }

            //
            // Tmp file check and creation
            tmpDirPathSb.append("/").append(tmpFileName);
            tmpFile = new File(tmpDirPathSb.toString());

            // Check date of modification to avoid caching forever
            if (tmpFile.exists()) {
                long lastModifiedDate = tmpFile.lastModified();

                long maxCacheTime = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_CACHE_TIME);

                if (System.currentTimeMillis() - lastModifiedDate > maxCacheTime) {
                    logger.info("Deleting old cached file: {}", tmpFile.toString());
                    tmpFile.delete();
                }
            }

            // If file is not cached, download it.
            if (!tmpFile.exists()) {
                // Url connection
                URL iconUrl = new URL(iconResource);
                URLConnection urlConnection = iconUrl.openConnection();
                urlConnection.setConnectTimeout(2000);
                urlConnection.setReadTimeout(2000);

                // Length check
                String contentLengthString = urlConnection.getHeaderField("Content-Length");

                long maxLength = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_SIZE_MAX);

                try {
                    Long contentLength = Long.parseLong(contentLengthString);
                    if (contentLength > maxLength) {
                        logger.warn("Content lenght exceeded ({}/{}) for URL: {}",
                                new Object[] { contentLength, maxLength, iconResource });
                        throw new IOException("Content-Length reported a length of " + contentLength
                                + " which exceeds the maximum allowed size of " + maxLength);
                    }
                } catch (NumberFormatException nfe) {
                    logger.warn("Cannot get Content-Length header!");
                }

                logger.info("Creating file: {}", tmpFile.toString());
                tmpFile.createNewFile();

                // Icon download
                InputStream is = urlConnection.getInputStream();
                OutputStream os = new FileOutputStream(tmpFile);
                byte[] buffer = new byte[4096];
                try {
                    int len;
                    while ((len = is.read(buffer)) > 0) {
                        os.write(buffer, 0, len);

                        maxLength -= len;

                        if (maxLength < 0) {
                            logger.warn("Maximum content lenght exceeded ({}) for URL: {}",
                                    new Object[] { maxLength, iconResource });
                            throw new IOException("Maximum content lenght exceeded (" + maxLength
                                    + ") for URL: " + iconResource);
                        }
                    }
                } finally {
                    os.close();
                }

                logger.info("Downloaded file: {}", tmpFile.toString());

                // Image metadata content checks
                ImageFormat imgFormat = Sanselan.guessFormat(tmpFile);

                if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_BMP)
                        || imgFormat.equals(ImageFormat.IMAGE_FORMAT_GIF)
                        || imgFormat.equals(ImageFormat.IMAGE_FORMAT_JPEG)
                        || imgFormat.equals(ImageFormat.IMAGE_FORMAT_PNG)) {
                    logger.info("Detected image format: {}", imgFormat.name);
                } else if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_UNKNOWN)) {
                    logger.error("Unknown file format for URL: {}", iconResource);
                    throw new IOException("Unknown file format for URL: " + iconResource);
                } else {
                    logger.error("Usupported file format ({}) for URL: {}", imgFormat, iconResource);
                    throw new IOException("Unknown file format for URL: {}" + iconResource);
                }

                logger.info("Image validation passed for URL: {}", iconResource);
            } else {
                logger.info("Using cached file: {}", tmpFile.toString());
            }

            //
            // Injecting new URL for the icon resource
            String newResourceURL = new StringBuilder().append("img://console/file/icons?id=")
                    .append(tmpFileName).toString();

            logger.info("Injecting configuration component icon: {}", newResourceURL);
            icon.setResource(newResourceURL);
        } catch (Exception e) {
            if (tmpFile != null && tmpFile.exists()) {
                tmpFile.delete();
            }

            icon.setResource("Default");

            logger.error("Error while checking component configuration icon. Using the default plugin icon.",
                    e);
        }
    }
    //
    // If not, all is fine.
}

From source file:com.blackducksoftware.integration.hub.builder.HubServerConfigBuilder.java

public void validateHubUrl(final ValidationResults<GlobalFieldKey, HubServerConfig> result) {
    assertProxyValid();/*ww  w  .  ja  va  2  s  . c  o  m*/
    if (hubUrl == null) {
        result.addResult(HubServerConfigFieldEnum.HUBURL,
                new ValidationResult(ValidationResultEnum.ERROR, ERROR_MSG_URL_NOT_FOUND));
        return;
    }

    URL hubURL = null;
    try {
        hubURL = new URL(hubUrl);
        hubURL.toURI();
    } catch (final MalformedURLException e) {
        result.addResult(HubServerConfigFieldEnum.HUBURL,
                new ValidationResult(ValidationResultEnum.ERROR, ERROR_MSG_URL_NOT_VALID));
    } catch (final URISyntaxException e) {
        result.addResult(HubServerConfigFieldEnum.HUBURL,
                new ValidationResult(ValidationResultEnum.ERROR, ERROR_MSG_URL_NOT_VALID));
    }

    if (hubURL == null) {
        return;
    }

    try {
        URLConnection connection = null;
        if (proxyInfo != null) {
            if (!hubURL.getProtocol().equals("https") && proxyInfo.getUsername() != null
                    && proxyInfo.getEncryptedPassword() != null) {
                result.addResult(HubProxyInfoFieldEnum.PROXYUSERNAME, new ValidationResult(
                        ValidationResultEnum.ERROR, ERROR_MSG_AUTHENTICATED_PROXY_WITH_HTTPS));
                return;
            }
            connection = proxyInfo.openConnection(hubURL);
        } else {
            connection = hubURL.openConnection();
        }
        final int timeoutIntMillisec = 1000 * stringToNonNegativeInteger(timeoutSeconds);
        connection.setConnectTimeout(timeoutIntMillisec);
        connection.setReadTimeout(timeoutIntMillisec);
        connection.getContent();
    } catch (final IOException ioe) {
        result.addResult(HubServerConfigFieldEnum.HUBURL,
                new ValidationResult(ValidationResultEnum.ERROR, ERROR_MSG_UNREACHABLE_PREFIX + hubUrl, ioe));
        return;
    } catch (final RuntimeException e) {
        result.addResult(HubServerConfigFieldEnum.HUBURL,
                new ValidationResult(ValidationResultEnum.ERROR, ERROR_MSG_URL_NOT_VALID_PREFIX + hubUrl, e));
        return;
    }

    result.addResult(HubServerConfigFieldEnum.HUBURL, new ValidationResult(ValidationResultEnum.OK, ""));
}

From source file:com.spinn3r.api.BaseClient.java

protected URLConnection getConnection(String resource) throws IOException {

    URLConnection conn = null;

    try {//w ww .j av a 2  s  .c  o m

        // create the HTTP connection.
        URL request = new URL(resource);
        conn = request.openConnection();

        // set the UserAgent so Spinn3r know which client lib is calling.
        conn.setRequestProperty(USER_AGENT_HEADER, USER_AGENT + "; " + getConfig().getCommandLine());
        conn.setRequestProperty(ACCEPT_ENCODING_HEADER, GZIP_ENCODING);
        conn.setConnectTimeout(20000);
        conn.connect();

    }

    catch (IOException ioe) {

        //create a custom exception message with the right error.
        String message = conn.getHeaderField(null);
        IOException ce = new IOException(message);
        ce.setStackTrace(ioe.getStackTrace());

        throw ce;
    }

    return conn;
}

From source file:net.sf.taverna.t2.workbench.ui.impl.UserRegistrationForm.java

/**
 * Post registration data to our server.
 *///from  ww  w. j  a  v  a2  s.  c  om
private boolean postUserRegistrationDataToServer(UserRegistrationData regData) {
    StringBuilder parameters = new StringBuilder();

    /*
     * The 'submit' parameter - to let the server-side script know we are
     * submitting the user's registration form - all other requests will be
     * silently ignored
     */
    try {
        // value does not matter
        enc(parameters, TAVERNA_REGISTRATION_POST_PARAMETER_NAME, "submit");

        enc(parameters, TAVERNA_VERSION_POST_PARAMETER_NAME, regData.getTavernaVersion());
        enc(parameters, FIRST_NAME_POST_PARAMETER_NAME, regData.getFirstName());
        enc(parameters, LAST_NAME_POST_PARAMETER_NAME, regData.getLastName());
        enc(parameters, EMAIL_ADDRESS_POST_PARAMETER_NAME, regData.getEmailAddress());
        enc(parameters, KEEP_ME_INFORMED_POST_PARAMETER_PROPERTY_NAME, regData.getKeepMeInformed());
        enc(parameters, INSTITUTION_OR_COMPANY_POST_PARAMETER_NAME, regData.getInstitutionOrCompanyName());
        enc(parameters, INDUSTRY_TYPE_POST_PARAMETER_NAME, regData.getIndustry());
        enc(parameters, FIELD_POST_PARAMETER_NAME, regData.getField());
        enc(parameters, PURPOSE_POST_PARAMETER_NAME, regData.getPurposeOfUsingTaverna());
    } catch (UnsupportedEncodingException ueex) {
        logger.error(FAILED + "Could not url encode post parameters", ueex);
        showMessageDialog(null, REGISTRATION_FAILED_MSG, "Error encoding registration data", ERROR_MESSAGE);
        return false;
    }
    String server = REGISTRATION_URL;
    logger.info("Posting user registartion to " + server + " with parameters: " + parameters);
    String response = "";
    String failure;
    try {
        URL url = new URL(server);
        URLConnection conn = url.openConnection();
        /*
         * Set timeout to e.g. 7 seconds, otherwise we might hang too long
         * if server is not responding and it will block Taverna
         */
        conn.setConnectTimeout(7000);
        // Set connection parameters
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        // Make server believe we are HTML form data...
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // Write out the bytes of the content string to the stream.
        try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
            out.writeBytes(parameters.toString());
            out.flush();
        }
        // Read response from the input stream.
        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String temp;
            while ((temp = in.readLine()) != null)
                response += temp + "\n";
            // Remove the last \n character
            if (!response.isEmpty())
                response = response.substring(0, response.length() - 1);
        }
        if (response.equals("Registration successful!"))
            return true;
        logger.error(FAILED + "Response form server was: " + response);
        failure = "Error saving registration data on the server";
    } catch (ConnectException ceex) {
        /*
         * the connection was refused remotely (e.g. no process is listening
         * on the remote address/port).
         */
        logger.error(FAILED + "Registration server is not listening of the specified url.", ceex);
        failure = "Registration server is not listening at the specified url";
    } catch (SocketTimeoutException stex) {
        // timeout has occurred on a socket read or accept.
        logger.error(FAILED + "Socket timeout occurred.", stex);
        failure = "Registration server timeout";
    } catch (MalformedURLException muex) {
        logger.error(FAILED + "Registartion server's url is malformed.", muex);
        failure = "Error with registration server's url";
    } catch (IOException ioex) {
        logger.error(
                FAILED + "Failed to open url connection to registration server or writing/reading to/from it.",
                ioex);
        failure = "Error opening connection to the registration server";
    }
    showMessageDialog(null, REGISTRATION_FAILED_MSG, failure, ERROR_MESSAGE);
    return false;
}