Example usage for java.net HttpURLConnection setInstanceFollowRedirects

List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects

Introduction

In this page you can find the example usage for java.net HttpURLConnection setInstanceFollowRedirects.

Prototype

public void setInstanceFollowRedirects(boolean followRedirects) 

Source Link

Document

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

Usage

From source file:manchester.synbiochem.datacapture.SeekConnector.java

private Document get(String suffix) throws IOException, SAXException, ParserConfigurationException {
    DocumentBuilder builder = parser();
    HttpURLConnection conn = connect(suffix);
    conn.setInstanceFollowRedirects(true);
    try (InputStream is = conn.getInputStream()) {
        return builder.parse(is, new URL(seek, suffix).toString());
    }/*from  w  w w . ja  va  2 s.  c o m*/
}

From source file:co.aikar.timings.TimingsExport.java

@Override
public void run() {
    out.put("data", toArrayMapper(history, TimingHistory::export));

    String response = null;//from w w  w.  j a v  a2  s  .  c o  m
    String timingsURL = null;
    try {
        HttpURLConnection con = (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection();
        con.setDoOutput(true);
        String hostName = "BrokenHost";
        try {
            hostName = InetAddress.getLocalHost().getHostName();
        } catch (Exception ignored) {
        }
        con.setRequestProperty("User-Agent", "Paper/" + Bukkit.getServerName() + "/" + hostName);
        con.setRequestMethod("POST");
        con.setInstanceFollowRedirects(false);

        OutputStream request = new GZIPOutputStream(con.getOutputStream()) {
            {
                this.def.setLevel(7);
            }
        };

        request.write(JSONValue.toJSONString(out).getBytes("UTF-8"));
        request.close();

        response = getResponse(con);

        if (con.getResponseCode() != 302) {
            listeners.sendMessage(
                    ChatColor.RED + "Upload Error: " + con.getResponseCode() + ": " + con.getResponseMessage());
            listeners.sendMessage(ChatColor.RED + "Check your logs for more information");
            if (response != null) {
                Bukkit.getLogger().log(Level.SEVERE, response);
            }
            return;
        }

        timingsURL = con.getHeaderField("Location");
        listeners.sendMessage(ChatColor.GREEN + "View Timings Report: " + timingsURL);

        if (response != null && !response.isEmpty()) {
            Bukkit.getLogger().log(Level.INFO, "Timing Response: " + response);
        }
    } catch (IOException ex) {
        listeners.sendMessage(ChatColor.RED + "Error uploading timings, check your logs for more information");
        if (response != null) {
            Bukkit.getLogger().log(Level.SEVERE, response);
        }
        Bukkit.getLogger().log(Level.SEVERE, "Could not paste timings", ex);
    } finally {
        this.listeners.done(timingsURL);
    }
}

From source file:net.ymate.module.webproxy.WebProxy.java

@SuppressWarnings("unchecked")
public void transmission(HttpServletRequest request, HttpServletResponse response, String url,
        Type.HttpMethod method) throws Exception {
    StopWatch _consumeTime = null;/* w  w w .  j av  a  2s.  c  o  m*/
    long _threadId = 0;
    if (_LOG.isDebugEnabled()) {
        _consumeTime = new StopWatch();
        _consumeTime.start();
        _threadId = Thread.currentThread().getId();
        _LOG.debug("-------------------------------------------------");
        _LOG.debug("--> [" + _threadId + "] URL: " + url);
    }
    //
    HttpURLConnection _conn = null;
    try {
        if (__moduleCfg.isUseProxy()) {
            _conn = (HttpURLConnection) new URL(url).openConnection(__moduleCfg.getProxy());
        } else {
            _conn = (HttpURLConnection) new URL(url).openConnection();
        }
        _conn.setUseCaches(__moduleCfg.isUseCaches());
        _conn.setInstanceFollowRedirects(__moduleCfg.isInstanceFollowRedirects());
        //
        boolean _postFlag = Type.HttpMethod.POST.equals(method);
        boolean _multipartFlag = _postFlag && StringUtils.contains(request.getContentType(), "multipart/");
        if (_postFlag) {
            _conn.setDoOutput(true);
            _conn.setDoInput(true);
            _conn.setRequestMethod(method.name());
        }
        if (__moduleCfg.getConnectTimeout() > 0) {
            _conn.setConnectTimeout(__moduleCfg.getConnectTimeout());
        }
        if (__moduleCfg.getReadTimeout() > 0) {
            _conn.setReadTimeout(__moduleCfg.getReadTimeout());
        }
        //
        if (_LOG.isDebugEnabled()) {
            _LOG.debug("--> [" + _threadId + "] Method: " + method.name());
            _LOG.debug("--> [" + _threadId + "] Request Headers: ");
        }
        //
        Enumeration _header = request.getHeaderNames();
        while (_header.hasMoreElements()) {
            String _name = (String) _header.nextElement();
            String _value = request.getHeader(_name);
            boolean _flag = false;
            if (_postFlag && StringUtils.equalsIgnoreCase(_name, "content-type")
                    || __moduleCfg.isTransferHeaderEnabled()
                            && (!__moduleCfg.getTransferHeaderBlackList().isEmpty()
                                    && !__moduleCfg.getTransferHeaderBlackList().contains(_name)
                                    || !__moduleCfg.getTransferHeaderWhiteList().isEmpty()
                                            && __moduleCfg.getTransferHeaderWhiteList().contains(_name))) {
                _conn.setRequestProperty(_name, _value);
                _flag = true;
            }
            //
            if (_LOG.isDebugEnabled()) {
                _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _name + ": " + _value);
            }
        }
        _conn.connect();
        //
        if (_postFlag) {
            DataOutputStream _output = new DataOutputStream(_conn.getOutputStream());
            try {
                if (_multipartFlag) {
                    if (_LOG.isDebugEnabled()) {
                        _LOG.debug("--> [" + _threadId + "] Multipart: TRUE");
                    }
                    IOUtils.copyLarge(request.getInputStream(), _output);
                } else {
                    String _charset = request.getCharacterEncoding();
                    String _queryStr = ParamUtils.buildQueryParamStr(request.getParameterMap(), true, _charset);
                    IOUtils.write(_queryStr, _output, _charset);
                    //
                    if (_LOG.isDebugEnabled()) {
                        _LOG.debug("--> [" + _threadId + "] Request Parameters: ");
                        Map<String, String> _paramsMap = ParamUtils.parseQueryParamStr(_queryStr, true,
                                _charset);
                        for (Map.Entry<String, String> _param : _paramsMap.entrySet()) {
                            _LOG.debug("--> [" + _threadId + "] \t - " + _param.getKey() + ": "
                                    + _param.getValue());
                        }
                    }
                }
                _output.flush();
            } finally {
                IOUtils.closeQuietly(_output);
            }
        }
        //
        int _code = _conn.getResponseCode();
        //
        if (_LOG.isDebugEnabled()) {
            _LOG.debug("--> [" + _threadId + "] Response Code: " + _code);
            _LOG.debug("--> [" + _threadId + "] Response Headers: ");
        }
        //
        Map<String, List<String>> _headers = _conn.getHeaderFields();
        for (Map.Entry<String, List<String>> _entry : _headers.entrySet()) {
            if (_entry.getKey() != null) {
                boolean _flag = false;
                String _values = StringUtils.join(_entry.getValue(), ",");
                if (StringUtils.equalsIgnoreCase(_entry.getKey(), "content-type")
                        || __moduleCfg.isTransferHeaderEnabled()
                                && !__moduleCfg.getResponseHeaderWhileList().isEmpty()
                                && __moduleCfg.getResponseHeaderWhileList().contains(_entry.getKey())) {
                    response.setHeader(_entry.getKey(), _values);
                    _flag = true;
                }
                if (_LOG.isDebugEnabled()) {
                    _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _entry.getKey() + ": "
                            + _values);
                }
            }
        }
        if (HttpURLConnection.HTTP_BAD_REQUEST <= _conn.getResponseCode()) {
            response.sendError(_code);
        } else {
            if (HttpURLConnection.HTTP_OK == _code) {
                InputStream _inputStream = _conn.getInputStream();
                if (_inputStream != null) {
                    if (!_multipartFlag) {
                        byte[] _content = IOUtils.toByteArray(_inputStream);
                        IOUtils.write(_content, response.getOutputStream());
                        //
                        if (_LOG.isDebugEnabled()) {
                            _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody(
                                    _conn, _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding()));
                        }
                    } else {
                        IOUtils.copyLarge(_conn.getInputStream(), response.getOutputStream());
                        //
                        if (_LOG.isDebugEnabled()) {
                            _LOG.debug("--> [" + _threadId + "] Response Content: MultipartBody");
                        }
                    }
                } else if (_LOG.isDebugEnabled()) {
                    _LOG.debug("--> [" + _threadId + "] Response Content: NULL");
                }
                response.flushBuffer();
            } else {
                InputStream _inputStream = _conn.getInputStream();
                if (_inputStream != null) {
                    byte[] _content = IOUtils.toByteArray(_inputStream);
                    IOUtils.write(_content, response.getOutputStream());
                    //
                    if (_LOG.isDebugEnabled()) {
                        _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody(_conn,
                                _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding()));
                    }
                } else if (_LOG.isDebugEnabled()) {
                    _LOG.debug("--> [" + _threadId + "] Response Content: NULL");
                }
                response.setStatus(_code);
                response.flushBuffer();
            }
        }
    } catch (Throwable e) {
        _LOG.warn("An exception occurred while processing request mapping '" + url + "': ",
                RuntimeUtils.unwrapThrow(e));
    } finally {
        IOUtils.close(_conn);
        //
        if (_LOG.isDebugEnabled()) {
            if (_consumeTime != null) {
                _consumeTime.stop();
                _LOG.debug("--> [" + _threadId + "] Total execution time: " + _consumeTime.getTime() + "ms");
            }
            _LOG.debug("-------------------------------------------------");
        }
    }
}

From source file:com.gelakinetic.mtgfam.FamiliarActivity.java

/**
 * Open an inputStream to the HTML content at the given URL, making recursive calls for
 * redirection (HTTP 301, 302).//from   w  ww.j  a  va2s  . co  m
 *
 * @param url            The URL to open a stream to
 * @param logWriter      A PrintWriter to log debug info to. Can be null
 * @param recursionLevel The redirect recursion level. Starts at 0, doesn't go past 10
 * @return An InputStream to the content at the URL, or null
 * @throws IOException Thrown if something goes terribly wrong
 */
private static @Nullable InputStream getHttpInputStream(URL url, @Nullable PrintWriter logWriter,
        int recursionLevel) throws IOException {

    /* Don't allow infinite recursion */
    if (recursionLevel > 10) {
        return null;
    }

    /* Make the URL & connection objects, follow redirects, timeout after 5s */
    HttpURLConnection.setFollowRedirects(true);
    HttpURLConnection connection = (HttpURLConnection) (url).openConnection();
    connection.setConnectTimeout(5000);
    connection.setInstanceFollowRedirects(true);

    /* If the connection is not OK, debug print the response */
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        /* Log the URL and response code */
        if (logWriter != null) {
            logWriter.write("URL : " + url.toString() + '\n');
            logWriter.write("RESP: " + connection.getResponseCode() + '\n');
        }

        /* Comb through header fields for a redirect location */
        URL nextUrl = null;
        for (String key : connection.getHeaderFields().keySet()) {
            /* Log the header */
            if (logWriter != null) {
                logWriter.write("HDR : [" + key + "] " + connection.getHeaderField(key) + '\n');
            }

            /* Found the URL to try next */
            if (key != null && key.equalsIgnoreCase("location")) {
                nextUrl = new URL(connection.getHeaderField(key));
            }
        }

        /* If the next location is still null, comb through the HTML
         * This is kind of a hack for when sites.google.com is serving up malformed 302
         * redirects and all the header fields end up being in this input stream
         */
        if (nextUrl == null) {
            /* Open the stream */
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            int linesRead = 0;
            /* Read one line at a time */
            while ((line = br.readLine()) != null) {
                /* Log the line */
                if (logWriter != null) {
                    logWriter.write("HTML:" + line + '\n');
                }
                /* Check for a location */
                if (line.toLowerCase().contains("location")) {
                    nextUrl = new URL(line.split("\\s+")[1]);
                    break;
                }
                /* Count the line, make sure to quit after 1000 */
                linesRead++;
                if (linesRead > 1000) {
                    break;
                }
            }
        }

        if (nextUrl != null) {
            /* If there is a URL to follow, follow it */
            return getHttpInputStream(nextUrl, logWriter, recursionLevel + 1);
        } else {
            /* Otherwise return null */
            return null;
        }

    } else {
        /* HTTP response is A-OK. Return the inputStream */
        return connection.getInputStream();
    }
}

From source file:com.hellofyc.base.net.http.HttpUtils.java

protected void configConnection(HttpURLConnection connection) throws IOException {
    connection.setConnectTimeout(mConnectTimeout);
    connection.setReadTimeout(mReadTimeout);
    connection.setUseCaches(false);/*from  w w  w  .j  a va2s .  com*/
    connection.setDoInput(true);
    connection.setRequestProperty("Charset", Charset.defaultCharset().name());
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("User-Agent", mUserAgent);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("Cookie", CookieHelper.parse(mRequestParams.getCookies()));

    switch (mType) {
    case TYPE_TEXT: {
        connection.setRequestMethod(mMethod.name());
        if (mMethod == Method.POST) {
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", CONTENT_TYPE_TEXT);
            String paramsString;
            if (!TextUtils.isEmpty(mRequestParams.getString())) {
                paramsString = mRequestParams.getString();
            } else {
                paramsString = parseMapToUrlParamsString(mRequestParams.getArrayMap());
            }
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(paramsString.getBytes());
            outputStream.flush();
            outputStream.close();
        }
        break;
    }
    case TYPE_BITMAP: {
        connection.setRequestMethod(Method.POST.name());
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", CONTENT_TYPE_FILE);
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> entry : mRequestParams.getArrayMap().entrySet()) {
            builder.append(PREFIX).append(BOUNDARY).append(LINE_END);
            builder.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"")
                    .append(LINE_END);
            builder.append("Content-Type: text/plain; charset=\"utf-8\"").append(LINE_END);
            builder.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
            builder.append(LINE_END);
            builder.append(entry.getValue());
            builder.append(LINE_END);
        }
        outputStream.write(builder.toString().getBytes());

        outputStream.writeBytes(PREFIX + BOUNDARY + LINE_END);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + "bitmap" + "\";filename=\""
                + "bitmap.jpg" + "\"" + LINE_END);
        outputStream.writeBytes(LINE_END);
        outputStream.write(bitmapToBytes(mBitmap));
        outputStream.writeBytes(LINE_END);
        outputStream.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END);
        outputStream.flush();
        outputStream.close();
        break;
    }
    case TYPE_FILE: {
        connection.setRequestMethod(Method.POST.name());
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", CONTENT_TYPE_FILE);

        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> entry : mRequestParams.getArrayMap().entrySet()) {
            builder.append(PREFIX).append(BOUNDARY).append(LINE_END);
            builder.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"")
                    .append(LINE_END);
            builder.append("Content-Type: text/plain; charset=\"utf-8\"").append(LINE_END);
            builder.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
            builder.append(LINE_END);
            builder.append(entry.getValue());
            builder.append(LINE_END);
        }

        for (ArrayMap.Entry<String, File> entry : mFileMap.entrySet()) {
            String text = PREFIX + BOUNDARY + LINE_END + "Content-Disposition: form-data; name=\""
                    + entry.getKey() + "\"; filename=\"" + entry.getValue().getName() + "\"" + LINE_END
                    + "Content-Type:" + "application/octet-stream" + LINE_END
                    + "Content-Transfer-Encoding: binary" + LINE_END + LINE_END;
            outputStream.writeBytes(builder.append(text).toString());

            BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(entry.getValue()));
            int length;
            byte[] bytes = new byte[1024 * 1024];
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
            inputStream.close();
        }

        String endTag = LINE_END + PREFIX + BOUNDARY + PREFIX + LINE_END;
        outputStream.writeBytes(endTag);
        outputStream.flush();
        outputStream.close();
        break;
    }
    }
}

From source file:groovyx.net.http.HttpURLClient.java

/**
 * Perform a request.  Parameters are://from w  w w  .  j av a2 s .co  m
 * <dl>
 *   <dt>url</dt><dd>the entire request URL</dd>
 *   <dt>path</dt><dd>the path portion of the request URL, if a default
 *     URL is set on this instance.</dd>
 *   <dt>query</dt><dd>URL query parameters for this request.</dd>
 *   <dt>timeout</dt><dd>see {@link HttpURLConnection#setReadTimeout(int)}</dd>
 *   <dt>method</dt><dd>This defaults to GET, or POST if a <code>body</code>
 *   parameter is also specified.</dd>
 *   <dt>contentType</dt><dd>Explicitly specify how to parse the response.
 *     If this value is ContentType.ANY, the response <code>Content-Type</code>
 *     header is used to determine how to parse the response.</dd>
 *   <dt>requestContentType</dt><dd>used in a PUT or POST request to
 *     transform the request body and set the proper
 *     <code>Content-Type</code> header.  This defaults to the
 *     <code>contentType</code> if unset.</dd>
 *   <dt>auth</dt><dd>Basic authorization; pass the value as a list in the
 *   form [user, pass]</dd>
 *   <dt>headers</dt><dd>additional request headers, as a map</dd>
 *   <dt>body</dt><dd>request content body, for a PUT or POST request.
 *     This will be encoded using the requestContentType</dd>
 * </dl>
 * @param args named parameters
 * @return the parsed response
 * @throws URISyntaxException
 * @throws MalformedURLException
 * @throws IOException
 */
public HttpResponseDecorator request(Map<String, ?> args)
        throws URISyntaxException, MalformedURLException, IOException {

    // copy so we don't modify the original collection when removing items:
    args = new HashMap<String, Object>(args);

    Object arg = args.remove("url");
    if (arg == null && this.defaultURL == null)
        throw new IllegalStateException("Either the 'defaultURL' property"
                + " must be set or a 'url' parameter must be passed to the " + "request method.");
    URIBuilder url = arg != null ? new URIBuilder(arg.toString()) : defaultURL.clone();

    arg = null;
    arg = args.remove("path");
    if (arg != null)
        url.setPath(arg.toString());
    arg = null;
    arg = args.remove("query");
    if (arg != null) {
        if (!(arg instanceof Map<?, ?>))
            throw new IllegalArgumentException("'query' must be a map");
        url.setQuery((Map<?, ?>) arg);
    }

    HttpURLConnection conn = (HttpURLConnection) url.toURL().openConnection();
    conn.setInstanceFollowRedirects(this.followRedirects);

    arg = null;
    arg = args.remove("timeout");
    if (arg != null)
        conn.setConnectTimeout(Integer.parseInt(arg.toString()));

    arg = null;
    arg = args.remove("method");
    if (arg != null)
        conn.setRequestMethod(arg.toString());

    arg = null;
    arg = args.remove("contentType");
    Object contentType = arg != null ? arg : this.contentType;
    if (contentType instanceof ContentType)
        conn.addRequestProperty("Accept", ((ContentType) contentType).getAcceptHeader());

    arg = null;
    arg = args.remove("requestContentType");
    String requestContentType = arg != null ? arg.toString()
            : this.requestContentType != null ? this.requestContentType.toString()
                    : contentType != null ? contentType.toString() : null;

    // must add default headers before setting auth:
    for (String key : defaultHeaders.keySet())
        conn.addRequestProperty(key, defaultHeaders.get(key));

    arg = null;
    arg = args.remove("auth");
    if (arg != null) {
        if (oauth != null)
            log.warn("You are trying to use both OAuth and basic authentication!");
        try {
            List<?> vals = (List<?>) arg;
            conn.addRequestProperty("Authorization",
                    getBasicAuthHeader(vals.get(0).toString(), vals.get(1).toString()));
        } catch (Exception ex) {
            throw new IllegalArgumentException("Auth argument must be a list in the form [user,pass]");
        }
    }

    arg = null;
    arg = args.remove("headers");
    if (arg != null) {
        if (!(arg instanceof Map<?, ?>))
            throw new IllegalArgumentException("'headers' must be a map");
        Map<?, ?> headers = (Map<?, ?>) arg;
        for (Object key : headers.keySet())
            conn.addRequestProperty(key.toString(), headers.get(key).toString());
    }

    arg = null;
    arg = args.remove("body");
    if (arg != null) { // if there is a request POST or PUT body
        conn.setDoOutput(true);
        final HttpEntity body = (HttpEntity) encoderRegistry.getAt(requestContentType).call(arg);
        // TODO configurable request charset

        //TODO don't override if there is a 'content-type' in the headers list
        conn.addRequestProperty("Content-Type", requestContentType);
        try {
            // OAuth Sign if necessary.
            if (oauth != null)
                conn = oauth.sign(conn, body);
            // send request data
            DefaultGroovyMethods.leftShift(conn.getOutputStream(), body.getContent());
        } finally {
            conn.getOutputStream().close();
        }
    }
    // sign the request if we're using OAuth
    else if (oauth != null)
        conn = oauth.sign(conn, null);

    if (args.size() > 0) {
        String illegalArgs = "";
        for (String k : args.keySet())
            illegalArgs += k + ",";
        throw new IllegalArgumentException("Unknown named parameters: " + illegalArgs);
    }

    String method = conn.getRequestMethod();
    log.debug(method + " " + url);

    HttpResponse response = new HttpURLResponseAdapter(conn);
    if (ContentType.ANY.equals(contentType))
        contentType = conn.getContentType();

    Object result = this.getparsedResult(method, contentType, response);

    log.debug(response.getStatusLine());
    HttpResponseDecorator decoratedResponse = new HttpResponseDecorator(response, result);

    if (log.isTraceEnabled()) {
        for (Header h : decoratedResponse.getHeaders())
            log.trace(" << " + h.getName() + " : " + h.getValue());
    }

    if (conn.getResponseCode() > 399)
        throw new HttpResponseException(decoratedResponse);

    return decoratedResponse;
}

From source file:guru.benson.pinch.Pinch.java

/**
 * Searches for the ZIP central directory.
 *
 * @param length/*from www.ja  v  a 2  s . co m*/
 *     The content length of the file to search.
 *
 * @return {@code true} if central directory was found and parsed, otherwise {@code false}
 */
private boolean findCentralDirectory(int length) {
    HttpURLConnection conn = null;
    InputStream bis = null;

    long start = length - 4096;
    long end = length - 1;
    byte[] data = new byte[2048];

    try {
        conn = openConnection();
        conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
        conn.setInstanceFollowRedirects(true);
        conn.connect();

        int responseCode = conn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_PARTIAL) {
            throw new IOException("Unexpected HTTP server response: " + responseCode);
        }

        bis = conn.getInputStream();
        int read, bytes = 0;
        while ((read = bis.read(data)) != -1) {
            bytes += read;
        }

        log("Read " + bytes + " bytes");

    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        close(bis);
        disconnect(conn);
    }

    return parseEndOfCentralDirectory(data);
}

From source file:guru.benson.pinch.Pinch.java

/**
 * Get a {@link java.net.HttpURLConnection} that has its {@link java.io.InputStream} pointing at
 * the file data of the given {@link guru.benson.pinch.ExtendedZipEntry}.
 *
 * @throws IOException/*from  w w w . j av a2  s.  c  o  m*/
 */
private HttpURLConnection getEntryInputStream(ExtendedZipEntry entry) throws IOException {
    HttpURLConnection conn;
    InputStream is;

    // Define the local header range
    long start = entry.getOffset();
    long end = start + ZipConstants.LOCHDR;

    conn = openConnection();
    conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
    conn.setInstanceFollowRedirects(true);
    conn.connect();

    int responseCode = conn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_PARTIAL) {
        throw new IOException("Unexpected HTTP server response: " + responseCode);
    }

    byte[] dataBuffer = new byte[2048];
    int read, bytes = 0;

    is = conn.getInputStream();
    while ((read = is.read(dataBuffer)) != -1) {
        bytes += read;
    }
    close(is);
    disconnect(conn);
    if (bytes < ZipConstants.LOCHDR) {
        throw new IOException("Unable to fetch the local header");
    }

    ByteBuffer buffer = ByteBuffer.allocate(ZipConstants.LOCHDR);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.put(dataBuffer, 0, ZipConstants.LOCHDR);

    final int headerSignature = buffer.getInt(0);
    if (headerSignature != 0x04034b50) {
        disconnect(conn);
        throw new IOException("Local file header signature mismatch");
    }

    final int localCompressedSize = buffer.getInt(ZipConstants.LOCSIZ);
    final short localFileNameLength = buffer.getShort(ZipConstants.LOCNAM);
    final short localExtraLength = buffer.getShort(ZipConstants.LOCEXT);

    // Define the local file range
    start = entry.getOffset() + ZipConstants.LOCHDR + localFileNameLength + localExtraLength;
    end = start + localCompressedSize;

    // Open a new one with
    conn = openConnection();
    conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
    conn.setInstanceFollowRedirects(true);
    conn.connect();

    responseCode = conn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_PARTIAL) {
        disconnect(conn);
        close(is);
        throw new IOException("Unexpected HTTP server response: " + responseCode);
    }

    return conn;
}

From source file:at.ac.tuwien.dsg.celar.mela.jCatascopiaClient.JCatascopiaDataSource.java

/**
 * Acts directly on the supplied agent and populates its metric list with
 * values/*from   ww w.  j  av a 2 s .  c  o m*/
 *
 * @param agent the agent for which the latest metric values will be
 * retrieved
 */
private void getLatestMetricsValuesForJCatascopiaAgent(JCatascopiaAgent agent) {
    URL url = null;
    HttpURLConnection connection = null;
    try {
        url = new URL(this.url + "/metrics");
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        connection.setRequestProperty("Accept", "application/json");

        //write message body
        OutputStream os = connection.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os));
        String getMetricsInfoQuerry = "metrics=";
        for (JCatascopiaMetric metric : agent.getAgentMetrics()) {
            getMetricsInfoQuerry += metric.getId() + ",";
        }

        //cut the last ","
        getMetricsInfoQuerry = getMetricsInfoQuerry.substring(0, getMetricsInfoQuerry.lastIndexOf(","));

        bufferedWriter.write(getMetricsInfoQuerry);
        bufferedWriter.flush();
        os.flush();
        os.close();

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));
            String line;
            while ((line = reader.readLine()) != null) {
                Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE, line);
            }
        }

        InputStream inputStream = connection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String availableMetrics = "";

        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            availableMetrics += line;
        }

        JSONObject object = new JSONObject(availableMetrics);
        if (object.has("metrics")) {
            JSONArray metrics = object.getJSONArray("metrics");
            List<JCatascopiaMetric> agentMetrics = agent.getAgentMetrics();

            //map of metric indexed on IDs to find easier the metrics (avoids for in for)
            Map<String, JCatascopiaMetric> metricsMap = new HashMap<String, JCatascopiaMetric>(0);
            for (JCatascopiaMetric jCatascopiaMetric : agentMetrics) {
                metricsMap.put(jCatascopiaMetric.getId(), jCatascopiaMetric);
            }

            //populate the metrics pool
            for (int i = 0; i < metrics.length(); i++) {
                JSONObject metric = metrics.getJSONObject(i);
                String metricId = null;
                String metricValue = null;

                //get agent metricID
                if (metric.has("metricID")) {
                    metricId = metric.getString("metricID");
                } else {
                    Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE,
                            "JCatascopia metricID not found in {0}", availableMetrics);
                }

                //get metric value
                if (metric.has("value")) {
                    metricValue = metric.getString("value");
                } else {
                    Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE,
                            "JCatascopia name not found in {0}", availableMetrics);
                }

                if (metricId == null || metricValue == null) {
                    continue;
                }

                if (metricsMap.containsKey(metricId)) {
                    JCatascopiaMetric jCatascopiaMetric = metricsMap.get(metricId);
                    jCatascopiaMetric.setValue(metricValue);
                } else {
                    Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE,
                            "Unrecognized metricId {0} found in {1}",
                            new Object[] { metricId, availableMetrics });
                }

            }

        } else {
            Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE,
                    "No JCatascopia metrics found in {0}", availableMetrics);
        }

    } catch (Exception e) {
        Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE, e.getMessage(), e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}