Example usage for java.net URLConnection getHeaderField

List of usage examples for java.net URLConnection getHeaderField

Introduction

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

Prototype

public String getHeaderField(int n) 

Source Link

Document

Returns the value for the n th header field.

Usage

From source file:com.sabre.hack.travelachievementgame.DSCommHandler.java

@SuppressWarnings("deprecation")
public String sendRequest(String payLoad, String authToken) {
    URLConnection conn = null;
    String strRet = null;/*  w  w  w .  j  av  a 2s .  com*/
    try {
        URL urlConn = new URL(payLoad);

        conn = null;
        conn = urlConn.openConnection();

        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Accept", "application/json");

        DataInputStream dataIn = new DataInputStream(conn.getInputStream());
        String strChunk = "";
        StringBuilder sb = new StringBuilder("");
        while (null != ((strChunk = dataIn.readLine())))
            sb.append(strChunk);

        strRet = sb.toString();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        System.out.println("MalformedURLException in DSCommHandler");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("IOException in DSCommHandler: " + conn.getHeaderField(0));
        //         e.printStackTrace();
    }
    return strRet;
}

From source file:twitter4j.internal.models4j.TwitterBaseImpl.java

private void setContentTypeAndTotalContentLength(TonUpload tonUpload) throws TwitterException {
    if (tonUpload.getTotalContentLength() != null && tonUpload.getTotalContentLength() > 0l
            && StringUtils.isNotBlank(tonUpload.getContentType())) {
        return;//  w  w w .jav  a2 s .co  m
    }
    if (StringUtils.isNotBlank(tonUpload.getMediaUrl())) {

        URLConnection urlConnection = null;
        try {
            URL localURL = new URL(tonUpload.getMediaUrl());
            urlConnection = localURL.openConnection();
            String contentLength = urlConnection.getHeaderField("Content-Length");
            String contentType = urlConnection.getHeaderField("Content-Type");
            if (StringUtils.isNotBlank(contentLength)) {
                tonUpload.setTotalContentLength(Long.valueOf(contentLength));
            }
            //check valid content type else add video/mp4 or image default or file default
            tonUpload.setContentType(contentType);
        } catch (IOException e) {
            throw new TwitterException("Failed to determine content type and length", e);
        } finally {

        }

    }
}

From source file:org.apache.xml.security.utils.resolver.implementations.ResolverDirectHTTP.java

/**
 * Method resolve//from   w  w w  .  j  a  va2  s . com
 *
 * @param uri
 * @param baseURI
 *
 * @throws ResourceResolverException
 * @return 
 * $todo$ calculate the correct URI from the attribute and the baseURI
 */
public XMLSignatureInput engineResolve(Attr uri, String baseURI) throws ResourceResolverException {
    try {
        boolean useProxy = false;
        String proxyHost = engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyHost]);
        String proxyPort = engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPort]);

        if ((proxyHost != null) && (proxyPort != null)) {
            useProxy = true;
        }

        String oldProxySet = null;
        String oldProxyHost = null;
        String oldProxyPort = null;
        // switch on proxy usage
        if (useProxy) {
            if (log.isDebugEnabled()) {
                log.debug("Use of HTTP proxy enabled: " + proxyHost + ":" + proxyPort);
            }
            oldProxySet = System.getProperty("http.proxySet");
            oldProxyHost = System.getProperty("http.proxyHost");
            oldProxyPort = System.getProperty("http.proxyPort");
            System.setProperty("http.proxySet", "true");
            System.setProperty("http.proxyHost", proxyHost);
            System.setProperty("http.proxyPort", proxyPort);
        }

        boolean switchBackProxy = ((oldProxySet != null) && (oldProxyHost != null) && (oldProxyPort != null));

        // calculate new URI
        URI uriNew = null;
        try {
            uriNew = getNewURI(uri.getNodeValue(), baseURI);
        } catch (URISyntaxException ex) {
            throw new ResourceResolverException("generic.EmptyMessage", ex, uri, baseURI);
        }

        URL url = uriNew.toURL();
        URLConnection urlConnection = url.openConnection();

        {
            // set proxy pass
            String proxyUser = engineGetProperty(
                    ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyUser]);
            String proxyPass = engineGetProperty(
                    ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPass]);

            if ((proxyUser != null) && (proxyPass != null)) {
                String password = proxyUser + ":" + proxyPass;
                String encodedPassword = Base64.encode(password.getBytes("ISO-8859-1"));

                // or was it Proxy-Authenticate ?
                urlConnection.setRequestProperty("Proxy-Authorization", encodedPassword);
            }
        }

        {
            // check if Basic authentication is required
            String auth = urlConnection.getHeaderField("WWW-Authenticate");

            if (auth != null && auth.startsWith("Basic")) {
                // do http basic authentication
                String user = engineGetProperty(
                        ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicUser]);
                String pass = engineGetProperty(
                        ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicPass]);

                if ((user != null) && (pass != null)) {
                    urlConnection = url.openConnection();

                    String password = user + ":" + pass;
                    String encodedPassword = Base64.encode(password.getBytes("ISO-8859-1"));

                    // set authentication property in the http header
                    urlConnection.setRequestProperty("Authorization", "Basic " + encodedPassword);
                }
            }
        }

        String mimeType = urlConnection.getHeaderField("Content-Type");
        InputStream inputStream = urlConnection.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte buf[] = new byte[4096];
        int read = 0;
        int summarized = 0;

        while ((read = inputStream.read(buf)) >= 0) {
            baos.write(buf, 0, read);
            summarized += read;
        }

        if (log.isDebugEnabled()) {
            log.debug("Fetched " + summarized + " bytes from URI " + uriNew.toString());
        }

        XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray());

        result.setSourceURI(uriNew.toString());
        result.setMIMEType(mimeType);

        // switch off proxy usage
        if (useProxy && switchBackProxy) {
            System.setProperty("http.proxySet", oldProxySet);
            System.setProperty("http.proxyHost", oldProxyHost);
            System.setProperty("http.proxyPort", oldProxyPort);
        }

        return result;
    } catch (MalformedURLException ex) {
        throw new ResourceResolverException("generic.EmptyMessage", ex, uri, baseURI);
    } catch (IOException ex) {
        throw new ResourceResolverException("generic.EmptyMessage", ex, uri, baseURI);
    }
}

From source file:tm.alashow.datmusic.ui.activity.MainActivity.java

private void search(String query, final boolean refresh, long captchaSid, String captchaKey,
        boolean performerOnly) {
    oldQuery = query;//from  w  w  w . ja v a2s  .com
    RequestParams params = new RequestParams();

    params.put("q", query);
    params.put("autocomplete", Config.VK_CONFIG_AUTOCOMPLETE);
    params.put("sort", CONFIG_SORT);
    params.put("count", CONFIG_COUNT);

    params.put("performer_only", (performerOnly) ? 1 : CONFIG_PERFORMER_ONLY);

    if (captchaSid > 1) {
        params.put("captcha_sid", captchaSid);
        params.put("captcha_key", captchaKey);
    }

    //change search method to getPopular, if query empty. get popular music.

    ApiClient.get(Config.SEARCH, params, new JsonHttpResponseHandler() {
        @Override
        public void onStart() {
            U.hideView(errorView);
            if (refresh) {
                swipeRefreshLayout.setRefreshing(true);
            } else {
                U.showView(progressBar);
                U.hideView(mListView);
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            try {
                clearList();//clear old data
                if (response.has("error")) { //if we have error
                    //Result errors
                    JSONObject errorObject = response.getJSONObject("error");
                    int errorCode = errorObject.getInt("error_code");
                    //showing error
                    switch (errorCode) {
                    case 5:
                        showError("token");
                        break;
                    case 6: // "Too many requests per second" error, retry
                        search(oldQuery);
                        break;
                    case 14:
                        showCaptcha(errorObject.getString("captcha_img"), errorObject.getLong("captcha_sid"));
                        showError("captcha");
                        break;
                    default:
                        showError(errorObject.getString("error_msg"));
                        break;
                    }
                    return;
                }
                JSONArray audios = response.getJSONArray("response");
                if (audios.length() >= 2) {
                    for (int i = 1; i < audios.length(); i++)
                        audioList.add(new Audio((JSONObject) audios.get(i)));
                    audioListAdapter = new AudioListAdapter(MainActivity.this, audioList);
                    mListView.setAdapter(audioListAdapter);
                    mListView.setFastScrollEnabled(audioList.size() > 10);

                    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            final Audio audio = audioList.get(position);
                            final BottomSheet bottomSheet = new BottomSheet.Builder(MainActivity.this)
                                    .title(audio.getArtist() + " - " + audio.getTitle())
                                    .sheet(R.menu.audio_actions)
                                    .listener(new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            switch (which) {
                                            case R.id.download:
                                                DownloadManager mgr = (DownloadManager) getSystemService(
                                                        DOWNLOAD_SERVICE);
                                                Uri downloadUri = Uri.parse(audio.getDownloadUrl());
                                                DownloadManager.Request request = new DownloadManager.Request(
                                                        downloadUri);

                                                if (U.isAboveOfVersion(11)) {
                                                    request.setNotificationVisibility(
                                                            DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                                }

                                                request.setAllowedNetworkTypes(
                                                        DownloadManager.Request.NETWORK_WIFI
                                                                | DownloadManager.Request.NETWORK_MOBILE);
                                                mgr.enqueue(request);
                                                break;
                                            case R.id.play:
                                                playAudio(audio);
                                                break;
                                            case R.id.copy:
                                                if (!U.isAboveOfVersion(11)) {
                                                    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                                                            CLIPBOARD_SERVICE);
                                                    clipboard.setText(audio.getSecureDownloadUrl());
                                                } else {
                                                    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(
                                                            CLIPBOARD_SERVICE);
                                                    android.content.ClipData clip = android.content.ClipData
                                                            .newPlainText("Link", audio.getSecureDownloadUrl());
                                                    clipboard.setPrimaryClip(clip);
                                                    U.showCenteredToast(MainActivity.this,
                                                            R.string.audio_copied);
                                                }
                                                break;
                                            case R.id.share:
                                                String shareText = getString(R.string.share_text)
                                                        + audio.getSecureDownloadUrl();
                                                Intent sendIntent = new Intent();
                                                sendIntent.setAction(Intent.ACTION_SEND);
                                                sendIntent.putExtra(Intent.EXTRA_TEXT, shareText);
                                                sendIntent.setType("text/plain");
                                                startActivity(sendIntent);
                                            }
                                        }
                                    }).show();

                            //If file size already set, show it
                            if (audio.getBytes() > 1) {
                                setSizeAndBitrate(bottomSheet, audio);
                            } else {
                                try {
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                URLConnection ucon;
                                                final URL uri = new URL(audio.getDownloadUrl());
                                                ucon = uri.openConnection();
                                                ucon.connect();
                                                final long bytes = Long
                                                        .parseLong(ucon.getHeaderField("content-length"));
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        audio.setBytes(bytes);
                                                        setSizeAndBitrate(bottomSheet, audio);
                                                    }
                                                });
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }).start();
                                } catch (final Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });

                    if (refresh) {
                        swipeRefreshLayout.setRefreshing(false);
                    } else {
                        U.hideView(progressBar);
                    }
                } else {
                    showError("notFound");
                }
            } catch (Exception e) {
                U.showCenteredToast(MainActivity.this, R.string.exception);
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            showError("network");
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            showError("network");
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
            showError("network");
        }

        @Override
        public void onFinish() {
            U.showView(mListView);
            if (refresh) {
                swipeRefreshLayout.setRefreshing(false);
            } else {
                U.hideView(progressBar);
            }
        }
    });
}

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

/**
 * Checks the source of the icon.//from   w w  w  .ja va2 s  . c  om
 * 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:net.unit8.maven.plugins.handlebars.HandlebarsEngine.java

protected void fetchHandlebars(String handlebarsName) throws MojoExecutionException {
    String downloadUrl = null;/*from w  ww.  ja  va 2  s.  com*/
    URLConnection conn = null;
    try {
        conn = handlebarsDownloadsUri.toURL().openConnection();
        List<GitHubDownloadDto> githubDownloadDtoList = JSON.decode(conn.getInputStream(),
                (new ArrayList<GitHubDownloadDto>() {
                }).getClass().getGenericSuperclass());
        for (GitHubDownloadDto githubDownloadDto : githubDownloadDtoList) {
            if (StringUtils.equals(githubDownloadDto.getName(), handlebarsName)) {
                downloadUrl = githubDownloadDto.getHtmlUrl();
            }
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Failure fetch handlebars.", e);
    } finally {
        if (conn != null) {
            ((HttpURLConnection) conn).disconnect();
        }
    }

    conn = null;
    try {
        if (!cacheDir.exists()) {
            FileUtils.forceMkdir(cacheDir);
        }
        conn = new URL(downloadUrl).openConnection();
        if (((HttpURLConnection) conn).getResponseCode() == 302) {
            String location = conn.getHeaderField("Location");
            ((HttpURLConnection) conn).disconnect();
            conn = new URL(location).openConnection();
        }
        LOG.info("Fetch handlebars.js from GitHub (" + conn.getURL() + ")");
        IOUtils.copy(conn.getInputStream(), new FileOutputStream(new File(cacheDir, handlebarsName)));
    } catch (Exception e) {
        throw new MojoExecutionException("Failure fetch handlebars.", e);
    } finally {
        if (conn != null) {
            ((HttpURLConnection) conn).disconnect();
        }
    }
}

From source file:org.kuali.mobility.people.dao.DirectoryDaoUMImpl.java

@Override
public SearchResultImpl findEntries(SearchCriteria search) {
    SearchResultImpl results = null;//w w w  .  j  ava  2 s .  com
    String searchText = search.getSearchText();
    if (searchText != null && searchText.contains("<script>")) {
        // Do not perform any search
    }
    if (searchText != null && searchText.contains(";")) {
        // Do not perform any search
    } else if (searchText != null && searchText.contains("eval")) {
        // Do not perform any search
    } else {
        results = (SearchResultImpl) getApplicationContext().getBean("searchResult");

        StringBuilder queryString = new StringBuilder();

        if (search.getSearchText() != null && !search.getSearchText().trim().isEmpty()) {
            searchText = searchText.replaceAll("[^\\w\\s]", ""); //Removes all special character
            queryString.append("searchCriteria=");
            queryString.append(searchText.trim());
        } else if (search.getUserName() != null && !search.getUserName().isEmpty()) {
            queryString.append("uniqname=");
            queryString.append(search.getUserName().trim());
        } else {
            if ("starts".equalsIgnoreCase(search.getExactness())) {
                search.setExactness("starts with");
            }
            if (search.getFirstName() != null && !search.getFirstName().trim().isEmpty()) {
                queryString.append("givenName=");
                queryString.append(search.getFirstName().trim());
                queryString.append("&givenNameSearchType=");
                queryString.append(search.getExactness());
                queryString.append("&");
            }
            if (search.getLastName() != null && !search.getLastName().trim().isEmpty()) {
                queryString.append("sn=");
                queryString.append(search.getLastName().trim());
                queryString.append("&snSearchType=");
                queryString.append(search.getExactness());
            }
        }

        LOG.debug("QueryString will be : " + queryString.toString());

        try {
            URLConnection connection = new URL(SEARCH_URL).openConnection();

            connection.setDoOutput(true); // Triggers POST.
            connection.setRequestProperty("Accept-Charset", DEFAULT_CHARACTER_SET);
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=" + DEFAULT_CHARACTER_SET);
            OutputStream output = null;

            output = connection.getOutputStream();
            output.write(queryString.toString().getBytes(DEFAULT_CHARACTER_SET));

            InputStream response = connection.getInputStream();
            String contentType = connection.getHeaderField("Content-Type");

            if (contentType != null && "application/json".equalsIgnoreCase(contentType)) {
                //               LOG.debug("Attempting to parse JSON using Gson.");

                List<Person> peeps = new ArrayList<Person>();
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(response, DEFAULT_CHARACTER_SET));

                    String jsonData = IOUtils.toString(response, DEFAULT_CHARACTER_SET);

                    LOG.debug("Attempting to parse JSON using JSON.simple.");
                    LOG.debug(jsonData);

                    JSONParser parser = new JSONParser();

                    Object rootObj = parser.parse(jsonData);

                    JSONObject jsonObject = (JSONObject) rootObj;
                    JSONArray jsonPerson = (JSONArray) jsonObject.get("person");
                    for (Object o : jsonPerson) {
                        peeps.add(parsePerson((JSONObject) o));
                    }
                } catch (UnsupportedEncodingException uee) {
                    LOG.error(uee.getLocalizedMessage());
                } catch (IOException ioe) {
                    LOG.error(ioe.getLocalizedMessage());
                } catch (ParseException pe) {
                    LOG.error(pe.getLocalizedMessage(), pe);
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException logOrIgnore) {
                            LOG.error(logOrIgnore.getLocalizedMessage());
                        }
                    }
                }
                results.setPeople(peeps);
            } else {
                LOG.debug("Content type was not application/json.");
            }
        } catch (IOException ioe) {
            LOG.error(ioe.getLocalizedMessage());
        }
        LOG.debug("Searching for groups.");
        results.setGroups(searchForGroup(search));
    }
    return results;
}

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

protected URLConnection getConnection(String resource) throws IOException {

    URLConnection conn = null;

    try {/*from   ww w.j  av  a  2  s  .  co  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:iracing.webapi.IracingWebApi.java

private boolean isMaintenancePage(URLConnection conn) {
    String location = conn.getHeaderField("Location");
    if (location != null && location.startsWith(MAINTENANCE_URL)) {
        System.err.println("iRacing website is down for maintenance");
        return true;
    }/*from   ww  w . j a  v a  2s  .c  o m*/
    return false;
}

From source file:hudson.remoting.Launcher.java

/**
 * Parses the connection arguments from JNLP file given in the URL.
 *//*from ww  w  . j  av  a  2 s.  c  o  m*/
public List<String> parseJnlpArguments()
        throws ParserConfigurationException, SAXException, IOException, InterruptedException {
    while (true) {
        try {
            URLConnection con = slaveJnlpURL.openConnection();
            if (con instanceof HttpURLConnection && slaveJnlpCredentials != null) {
                HttpURLConnection http = (HttpURLConnection) con;
                String userPassword = slaveJnlpCredentials;
                String encoding = new String(Base64.encodeBase64(userPassword.getBytes()));
                http.setRequestProperty("Authorization", "Basic " + encoding);
            }
            con.connect();

            if (con instanceof HttpURLConnection) {
                HttpURLConnection http = (HttpURLConnection) con;
                if (http.getResponseCode() >= 400)
                    // got the error code. report that (such as 401)
                    throw new IOException("Failed to load " + slaveJnlpURL + ": " + http.getResponseCode() + " "
                            + http.getResponseMessage());
            }

            Document dom;

            // check if this URL points to a .jnlp file
            String contentType = con.getHeaderField("Content-Type");
            if (contentType == null || !contentType.startsWith("application/x-java-jnlp-file")) {
                // load DOM anyway, but if it fails to parse, that's probably because this is not an XML file to begin with.
                try {
                    dom = loadDom(slaveJnlpURL, con);
                } catch (SAXException e) {
                    throw new IOException(
                            slaveJnlpURL + " doesn't look like a JNLP file; content type was " + contentType);
                } catch (IOException e) {
                    throw new IOException(
                            slaveJnlpURL + " doesn't look like a JNLP file; content type was " + contentType);
                }
            } else {
                dom = loadDom(slaveJnlpURL, con);
            }

            // exec into the JNLP launcher, to fetch the connection parameter through JNLP.
            NodeList argElements = dom.getElementsByTagName("argument");
            List<String> jnlpArgs = new ArrayList<String>();
            for (int i = 0; i < argElements.getLength(); i++)
                jnlpArgs.add(argElements.item(i).getTextContent());
            if (slaveJnlpCredentials != null) {
                jnlpArgs.add("-credentials");
                jnlpArgs.add(slaveJnlpCredentials);
            }
            // force a headless mode
            jnlpArgs.add("-headless");
            return jnlpArgs;
        } catch (SSLHandshakeException e) {
            if (e.getMessage().contains("PKIX path building failed")) {
                // invalid SSL certificate. One reason this happens is when the certificate is self-signed
                IOException x = new IOException(
                        "Failed to validate a server certificate. If you are using a self-signed certificate, you can use the -noCertificateCheck option to bypass this check.");
                x.initCause(e);
                throw x;
            } else
                throw e;
        } catch (IOException e) {
            System.err.println("Failing to obtain " + slaveJnlpURL);
            e.printStackTrace(System.err);
            System.err.println("Waiting 10 seconds before retry");
            Thread.sleep(10 * 1000);
            // retry
        }
    }
}