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:de.mpg.mpdl.inge.pubman.web.util.FileLocatorUploadBean.java

/**
 * Executes a HEAD request to the locator.
 * //from   w w w .j av  a  2 s  .c o  m
 * @param locator
 * @return true if locator is accessible
 */
public boolean checkLocator(String locator) {
    this.locator = locator;
    if (locator != null) {
        this.locator = this.locator.trim();
    }
    URLConnection conn = null;
    byte[] input = null;
    String mimeType = null;
    String fileName = null;
    URL locatorURL = null;

    try {
        locatorURL = new URL(locator);
        conn = locatorURL.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        int responseCode = httpConn.getResponseCode();
        switch (responseCode) {
        case 503:
            this.error = getMessage("errorLocatorServiceUnavailable");
            return false;
        case 302:
            this.error = getMessage("errorLocatorServiceUnavailable");
            return false;
        case 200:
            this.logger.debug("Source responded with 200.");
            break;
        case 403:
            this.error = getMessage("errorLocatorAccessDenied");
            this.logger.warn("Access to url " + locator + " is restricted.");
            return false;
        default:
            this.error = getMessage("errorLocatorTechnicalException");
            this.logger.warn("An error occurred during importing from external system: " + responseCode + ": "
                    + httpConn.getResponseMessage() + ".");
            return false;
        }
    } catch (AccessException e) {
        this.logger.error("Access denied.", e);
        this.error = getMessage("errorLocatorAccessDenied");
        return false;
    } catch (MalformedURLException e) {
        this.error = getMessage("errorLocatorInvalidURL");
        this.logger.warn("Invalid locator URL:" + locator, e);
        return false;
    } catch (Exception e) {
        this.error = getMessage("errorLocatorTechnicalException");
        return false;
    }

    // Get Content Type
    mimeType = conn.getHeaderField("Content-Type");
    if (mimeType.contains(";")) {
        mimeType = mimeType.substring(0, mimeType.indexOf(";"));
    }
    if (mimeType != null) {
        this.setType(mimeType);
    }
    // Get File Name
    fileName = conn.getHeaderField("file-name");
    if (fileName != null) {
        this.setName(fileName);
    } else {
        this.setName(locatorURL.toString());
    }
    // Get File Length
    try {
        this.setSize(Integer.parseInt(conn.getHeaderField("Content-Length")));
    } catch (NumberFormatException e) {
        input = this.fetchLocator(locatorURL);
        if (input != null) {
            this.setSize(input.length);
        }
    }
    return true;
}

From source file:de.mpg.escidoc.pubman.util.FileLocatorUploadBean.java

/**
 * Executes a HEAD request to the locator.
 * //  w w w.j  a  va  2 s.c o m
 * @param locator
 * @return true if locator is accessible
 */
public boolean checkLocator(String locator) {
    this.locator = locator;
    if (locator != null) {
        this.locator = this.locator.trim();
    }
    URLConnection conn = null;
    byte[] input = null;
    String mimeType = null;
    String fileName = null;
    URL locatorURL = null;

    try {
        locatorURL = new URL(locator);
        conn = locatorURL.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        int responseCode = httpConn.getResponseCode();
        switch (responseCode) {
        case 503:
            this.error = getMessage("errorLocatorServiceUnavailable");
            return false;
        case 302:
            this.error = getMessage("errorLocatorServiceUnavailable");
            return false;
        case 200:
            this.logger.debug("Source responded with 200.");
            break;
        case 403:
            this.error = getMessage("errorLocatorAccessDenied");
            this.logger.warn("Access to url " + locator + " is restricted.");
            return false;
        default:
            this.error = getMessage("errorLocatorTechnicalException");
            this.logger.warn("An error occurred during importing from external system: " + responseCode + ": "
                    + httpConn.getResponseMessage() + ".");
            return false;
        }
    } catch (AccessException e) {
        this.logger.error("Access denied.", e);
        this.error = getMessage("errorLocatorAccessDenied");
        return false;
    } catch (MalformedURLException e) {
        this.error = getMessage("errorLocatorInvalidURL");
        this.logger.warn("Invalid locator URL:" + locator, e);
        return false;
    } catch (Exception e) {
        this.error = getMessage("errorLocatorTechnicalException");
        return false;
    }

    //Get Content Type
    mimeType = conn.getHeaderField("Content-Type");
    if (mimeType.contains(";")) {
        mimeType = mimeType.substring(0, mimeType.indexOf(";"));
    }
    if (mimeType != null) {
        this.setType(mimeType);
    }
    //Get File Name
    fileName = conn.getHeaderField("file-name");
    if (fileName != null) {
        this.setName(fileName);
    } else {
        this.setName(locatorURL.toString());
    }
    //Get File Length
    try {
        this.setSize(Integer.parseInt(conn.getHeaderField("Content-Length")));
    } catch (NumberFormatException e) {
        input = this.fetchLocator(locatorURL);
        if (input != null) {
            this.setSize(input.length);
        }
    }
    return true;
}

From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java

/**
 * Fetches a eSciDoc Record from eSciDoc system.
 * //from  w  w w .j av a  2  s  . c o  m
 * @param identifier
 *            of the item
 * @return itemXML as String
 * @throws IdentifierNotRecognisedException
 * @throws RuntimeException
 */
private byte[] fetchEjbFile(FullTextVO ft, String identifier)
        throws IdentifierNotRecognisedException, RuntimeException {
    String itemXML = "";
    String coreservice = "";
    URLConnection contentUrl = null;
    XmlTransforming xmlTransforming = new XmlTransformingBean();
    byte[] input = null;

    try {
        if (this.currentSource.getName().equalsIgnoreCase("escidoc")) {
            itemXML = ServiceLocator.getItemHandler().retrieve(identifier);
            coreservice = ServiceLocator.getFrameworkUrl();
        }
        if (this.currentSource.getName().equalsIgnoreCase("escidocdev")
                || this.currentSource.getName().equalsIgnoreCase("escidocqa")
                || this.currentSource.getName().equalsIgnoreCase("escidocprod")) {
            itemXML = ServiceLocator.getItemHandler(ft.getFtUrl().toString()).retrieve(identifier);
            coreservice = ft.getFtUrl().toString();
        }

        PubItemVO itemVO = xmlTransforming.transformToPubItem(itemXML);
        contentUrl = ProxyHelper.openConnection(new URL(coreservice + itemVO.getFiles().get(0).getContent()));
        HttpURLConnection httpConn = (HttpURLConnection) contentUrl;
        int responseCode = httpConn.getResponseCode();
        switch (responseCode) {
        case 503:
            // request was not processed by source
            this.logger.warn("Import source " + this.currentSource.getName() + "did not provide file.");
            throw new FormatNotAvailableException(ft.getFtLabel());
        case 302:
            String alternativeLocation = contentUrl.getHeaderField("Location");
            ft.setFtUrl(new URL(alternativeLocation));
            return fetchEjbFile(ft, identifier);
        case 200:
            this.logger.info("Source responded with 200.");
            GetMethod method = new GetMethod(coreservice + itemVO.getFiles().get(0).getContent());
            HttpClient client = new HttpClient();
            ProxyHelper.executeMethod(client, method);
            input = method.getResponseBody();
            httpConn.disconnect();
            break;
        case 403:
            throw new AccessException("Access to url " + this.currentSource.getName() + " is restricted.");
        default:
            throw new RuntimeException("An error occurred during importing from external system: "
                    + responseCode + ": " + httpConn.getResponseMessage());
        }
    }

    catch (ItemNotFoundException e) {
        this.logger.error("Item with identifier " + identifier + " was not found.", e);
        throw new IdentifierNotRecognisedException(e);
    } catch (Exception e) {
        this.logger.error("An error occurred while retrieving the item " + identifier + ".", e);
        throw new RuntimeException(e);
    }

    return input;
}

From source file:de.mpg.mpdl.inge.dataacquisition.DataHandlerBean.java

/**
 * Fetches a eSciDoc Record from eSciDoc system.
 * /*from  ww  w.  java2 s .com*/
 * @param identifier of the item
 * @return itemXML as String
 * @throws IdentifierNotRecognisedException
 * @throws RuntimeException
 */
private byte[] fetchEjbFile(FullTextVO ft, String identifier)
        throws IdentifierNotRecognisedException, RuntimeException {
    String itemXML = "";
    String coreservice = "";
    URLConnection contentUrl = null;
    de.mpg.mpdl.inge.xmltransforming.XmlTransforming xmlTransforming = new de.mpg.mpdl.inge.xmltransforming.xmltransforming.XmlTransformingBean();
    byte[] input = null;

    try {
        if (this.currentSource.getName().equalsIgnoreCase("escidoc")) {
            itemXML = ServiceLocator.getItemHandler().retrieve(identifier);
            coreservice = PropertyReader.getFrameworkUrl();
        }
        if (this.currentSource.getName().equalsIgnoreCase("escidocdev")
                || this.currentSource.getName().equalsIgnoreCase("escidocqa")
                || this.currentSource.getName().equalsIgnoreCase("escidocprod")) {
            itemXML = ServiceLocator.getItemHandler(ft.getFtUrl().toString()).retrieve(identifier);
            coreservice = ft.getFtUrl().toString();
        }

        PubItemVO itemVO = xmlTransforming.transformToPubItem(itemXML);
        contentUrl = ProxyHelper.openConnection(new URL(coreservice + itemVO.getFiles().get(0).getContent()));
        HttpURLConnection httpConn = (HttpURLConnection) contentUrl;
        int responseCode = httpConn.getResponseCode();
        switch (responseCode) {
        case 503:
            // request was not processed by source
            this.logger.warn("Import source " + this.currentSource.getName() + "did not provide file.");
            throw new FormatNotAvailableException(ft.getFtLabel());
        case 302:
            String alternativeLocation = contentUrl.getHeaderField("Location");
            ft.setFtUrl(new URL(alternativeLocation));
            return fetchEjbFile(ft, identifier);
        case 200:
            this.logger.info("Source responded with 200.");
            GetMethod method = new GetMethod(coreservice + itemVO.getFiles().get(0).getContent());
            HttpClient client = new HttpClient();
            ProxyHelper.executeMethod(client, method);
            input = method.getResponseBody();
            httpConn.disconnect();
            break;
        case 403:
            throw new AccessException("Access to url " + this.currentSource.getName() + " is restricted.");
        default:
            throw new RuntimeException("An error occurred during importing from external system: "
                    + responseCode + ": " + httpConn.getResponseMessage());
        }
    }

    catch (ItemNotFoundException e) {
        this.logger.error("Item with identifier " + identifier + " was not found.", e);
        throw new IdentifierNotRecognisedException(e);
    } catch (Exception e) {
        this.logger.error("An error occurred while retrieving the item " + identifier + ".", e);
        throw new RuntimeException(e);
    }

    return input;
}

From source file:osu.beatmapdownloader.JFrame.java

public boolean downloadSong(String idMap, int prio, String Directory) {
       String fileName = null;// w  w w .  j a  va 2  s. co  m
       try {
           String url = "";
           if (model.get(prio).toString().contains("Blood")) {
               url = "http://bloodcat.com/osu/d/" + idMap;
               L_server.setText("Bloodcat Server");
           } else {
               if (C_OsuServer.isSelected() && model.get(0).toString().contains("Osu")) {
                   if (C_noVideo.isSelected())
                       url = "http://osu.ppy.sh/d/" + idMap + "n";
                   else
                       url = "http://osu.ppy.sh/d/" + idMap;
                   L_server.setText("Osu! Server");
               }
           }
           long start = System.nanoTime();
           long totalRead = 0;
           final double NANOS_PER_SECOND = 1000000000.0;
           final double BYTES_PER_MIB = 1024 * 1024;
           URLConnection request = null;
           request = new URL(url).openConnection();
           request.setRequestProperty("Cookie", url.contains("ppy") ? Cookie : "");
           request.setRequestProperty("User-Agent",
                   "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
           InputStream in = request.getInputStream();
           String raw = request.getHeaderField("Content-Disposition");
           fileName = raw.split("=")[1].replaceAll("\"", "").replaceAll("; filename*", "");
           request.getContentLength();
           double size = request.getContentLength();
           File aux = File.createTempFile(fileName.replaceAll("\\*", "").replaceAll(";", ""), ".osz");
           L_FileName.setText(fileName.replaceAll("\\*", "").replaceAll(";", ""));
           FileOutputStream out = new FileOutputStream(aux);
           byte[] buffer = new byte[1024];
           int len = in.read(buffer);
           L_totalSize.setText((String) new DecimalFormat("#.##").format(size * 0.000001) + " Mb");
           int bytes = 0;
           Pro_ProgressBar.setMinimum(0);
           Pro_ProgressBar.setMaximum((int) (size / 1000));
           long acu = 0;
           while (len != -1) {
               bytes++;
               out.write(buffer, 0, len);
               len = in.read(buffer);
               if (len == 1024) {
                   acu += len;
                   BigDecimal a = new BigDecimal(acu * 0.000001);
                   BigDecimal roundOff = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
                   L_fileValue.setText(roundOff + "");
               }
               Pro_ProgressBar.setValue(bytes);
               totalRead += len;
               BigDecimal a = new BigDecimal(
                       ((NANOS_PER_SECOND / BYTES_PER_MIB * totalRead / (System.nanoTime() - start + 1)) * 1000));
               BigDecimal speed = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
               //String speed = new DecimalFormat("#.##").format(((NANOS_PER_SECOND / BYTES_PER_MIB * totalRead / (System.nanoTime() - start + 1)) * 1000));
               L_Second.setText(speed + "");
               BigDecimal b = new BigDecimal((((size * 0.000001) - (acu * 0.000001)) * 0.1)
                       / (((NANOS_PER_SECOND / BYTES_PER_MIB * totalRead / (System.nanoTime() - start + 1))
                               * 1000))
                       * 10000);
               BigDecimal speed_total = b.setScale(2, BigDecimal.ROUND_HALF_EVEN);
               L_seconds.setText(speed_total + "");
               if (Thread.interrupted()) {
                   in.close();
                   out.close();
                   aux.deleteOnExit();
                   throw new InterruptedException();
               }
           }
           in.close();
           out.close();
           FileUtils.copyFile(aux,
                   new File(Directory + File.separator + fileName.replaceAll("\\*", "").replaceAll(";", "")));
           aux.deleteOnExit();
           return true;
       } catch (Exception e) {
           errorFatal("DOWNLOADING");
           errorFatal(e.toString());
           errorFatal("--------------------------------------");
           prio++;
           errorConection++;
           L_Trying.setText(errorConection + "");
           int limitTry = 3;
           if (errorConection >= limitTry) {
               Errors++;
               L_Errors.setText(Errors + "");
               errorDownload("-The connection to this Beatmap was failed, '" + errorConection
                       + "' times, it was skipped.");
               errorDownload("--The filename is '" + fileName + "', with the id '" + idMap + "'. ");
               errorDownload("----------------------");
           } else {
               if (model.getSize() == prio)
                   prio = 0;
               downloadSong(idMap, prio, Directory);
           }
           return false;
       }
   }

From source file:com.ikanow.infinit.e.data_model.driver.InfiniteDriver.java

public String sendGetRequest(String urlAddress, int redirects) throws Exception {
    if (urlAddress.startsWith("https:")) {
        TrustManagerManipulator.allowAllSSL();
    }/*from   w  w  w. j  a  v a 2  s  .  c om*/

    URL url = new URL(urlAddress);
    URLConnection urlConnection = url.openConnection();
    if (cookie != null)
        urlConnection.setRequestProperty("Cookie", cookie);
    if (apiKey != null)
        urlConnection.setRequestProperty("Cookie", apiKey);

    ((HttpURLConnection) urlConnection).setRequestMethod("GET");

    int status = ((HttpURLConnection) urlConnection).getResponseCode();
    // normally, 3xx is redirect
    if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER) {
            if (redirects <= 5) {
                String newUrlAddress = ((HttpURLConnection) urlConnection).getHeaderField("Location");
                if (null != newUrlAddress) {
                    return sendGetRequest(newUrlAddress, redirects + 1);
                }
            }
            //(else carry on, will exception out or something below)
        }
    } //TESTED

    //read back result
    BufferedReader inStream = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    StringBuilder strBuilder = new StringBuilder();
    String buffer;
    while ((buffer = inStream.readLine()) != null) {
        strBuilder.append(buffer);
    }
    inStream.close();

    //save cookie if cookie is null
    if (cookie == null) {
        String headername;
        for (int i = 1; (headername = urlConnection.getHeaderFieldKey(i)) != null; i++) {
            if (headername.equals("Set-Cookie")) {
                cookie = urlConnection.getHeaderField(i);
                break;
            }
        }
    }
    return strBuilder.toString();
}

From source file:com.ikanow.infinit.e.data_model.driver.InfiniteDriver.java

private String sendPostRequest(String urlAddress, String data, int redirects)
        throws MalformedURLException, IOException {
    String result = "";

    if (urlAddress.startsWith("https:")) {
        TrustManagerManipulator.allowAllSSL();
    }// www.  j  a v a2s  . c  o  m
    URLConnection urlConnection = new URL(urlAddress).openConnection();

    if (cookie != null)
        urlConnection.setRequestProperty("Cookie", cookie);
    if (apiKey != null)
        urlConnection.setRequestProperty("Cookie", apiKey);

    urlConnection.setDoOutput(true);
    urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
    ((HttpURLConnection) urlConnection).setRequestMethod("POST");

    // Post JSON string to URL

    OutputStream os = urlConnection.getOutputStream();

    byte[] b = data.getBytes("UTF-8");

    os.write(b);

    int status = ((HttpURLConnection) urlConnection).getResponseCode();
    // normally, 3xx is redirect
    if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER) {
            if (redirects <= 5) {
                String newUrlAddress = ((HttpURLConnection) urlConnection).getHeaderField("Location");
                if (null != newUrlAddress) {
                    return sendPostRequest(newUrlAddress, data, redirects + 1);
                }
            }
            //(else carry on, will exception out or something below)
        }
    } //TESTED

    // Receive results back from API

    InputStream inStream = urlConnection.getInputStream();

    result = IOUtils.toString(inStream, "UTF-8");

    inStream.close();

    //save cookie if cookie is null
    if (cookie == null) {
        String headername;
        for (int i = 1; (headername = urlConnection.getHeaderFieldKey(i)) != null; i++) {
            if (headername.equals("Set-Cookie")) {
                cookie = urlConnection.getHeaderField(i);
                break;
            }
        }
    }

    return result;
}

From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java

public ProcessResult loadFromProxy(HttpServletRequest request, HttpServletResponse response, String uri,
        String servletPath, String proxyPath) throws ServletException, IOException {
    //System.out.println("LOAD "+uri); 
    //System.out.println("LOAD "+proxyPath);

    if ("CONNECT".equalsIgnoreCase(request.getMethod())) {
        handleConnect(request, response);

    } else {//www .j av  a2  s .c  om
        URL url = new URL(uri);

        URLConnection connection = url.openConnection();
        connection.setAllowUserInteraction(false);

        // Set method
        HttpURLConnection http = null;
        if (connection instanceof HttpURLConnection) {
            http = (HttpURLConnection) connection;
            http.setRequestMethod(request.getMethod());
            http.setInstanceFollowRedirects(false);
        }

        // check connection header
        String connectionHdr = request.getHeader("Connection");
        if (connectionHdr != null) {
            connectionHdr = connectionHdr.toLowerCase();
            if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
                connectionHdr = null;
        }

        // copy headers
        boolean xForwardedFor = false;
        boolean hasContent = false;
        Enumeration enm = request.getHeaderNames();
        while (enm.hasMoreElements()) {
            // TODO could be better than this!
            String hdr = (String) enm.nextElement();
            String lhdr = hdr.toLowerCase();

            if (_DontProxyHeaders.contains(lhdr))
                continue;
            if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0)
                continue;

            if ("content-type".equals(lhdr))
                hasContent = true;

            Enumeration vals = request.getHeaders(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val != null) {
                    connection.addRequestProperty(hdr, val);
                    xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr);
                }
            }
        }

        // Proxy headers
        connection.setRequestProperty("Via", "1.1 (jetty)");
        if (!xForwardedFor)
            connection.addRequestProperty("X-Forwarded-For", request.getRemoteAddr());

        // a little bit of cache control
        String cache_control = request.getHeader("Cache-Control");
        if (cache_control != null
                && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
            connection.setUseCaches(false);

        // customize Connection

        try {
            connection.setDoInput(true);

            // do input thang!
            InputStream in = request.getInputStream();
            if (hasContent) {
                connection.setDoOutput(true);
                IOUtils.copy(in, connection.getOutputStream());
            }

            // Connect
            connection.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        InputStream proxy_in = null;

        // handler status codes etc.
        int code = 500;
        if (http != null) {
            proxy_in = http.getErrorStream();

            code = http.getResponseCode();
            response.setStatus(code, http.getResponseMessage());
        }

        if (proxy_in == null) {
            try {
                proxy_in = connection.getInputStream();
            } catch (Exception e) {
                e.printStackTrace();
                proxy_in = http.getErrorStream();
            }
        }

        // clear response defaults.
        response.setHeader("Date", null);
        response.setHeader("Server", null);

        // set response headers
        int h = 0;
        String hdr = connection.getHeaderFieldKey(h);
        String val = connection.getHeaderField(h);
        while (hdr != null || val != null) {
            String lhdr = hdr != null ? hdr.toLowerCase() : null;
            if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) {
                if (hdr.equalsIgnoreCase("Location")) {
                    val = Rewriter.translateCleanUrl(val, servletPath, proxyPath);
                }
                response.addHeader(hdr, val);

            }

            h++;
            hdr = connection.getHeaderFieldKey(h);
            val = connection.getHeaderField(h);

        }

        boolean isGzipped = connection.getContentEncoding() != null
                && connection.getContentEncoding().contains("gzip");
        response.addHeader("Via", "1.1 (jetty)");
        // boolean process = connection.getContentType() == null
        // || connection.getContentType().isEmpty()
        // || connection.getContentType().contains("html");
        boolean process = connection.getContentType() != null && connection.getContentType().contains("text");
        if (proxy_in != null) {
            if (!process) {
                IOUtils.copy(proxy_in, response.getOutputStream());
                proxy_in.close();
            } else {
                InputStream in;
                if (isGzipped && proxy_in != null && proxy_in.available() > 0) {
                    in = new GZIPInputStream(proxy_in);
                } else {
                    in = proxy_in;
                }
                ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream();
                IOUtils.copy(in, byteArrOS);
                in.close();
                if (in != proxy_in)
                    proxy_in.close();
                String charset = response.getCharacterEncoding();
                if (charset == null || charset.isEmpty()) {
                    charset = "ISO-8859-1";
                }
                String originalContent = new String(byteArrOS.toByteArray(), charset);
                byteArrOS.close();
                return new ProcessResult(originalContent, connection.getContentType(), charset, isGzipped);
            }
        }

    }
    return null;
}

From source file:net.lightbody.bmp.proxy.jetty.http.handler.ProxyHandler.java

public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response)
        throws HttpException, IOException {
    URI uri = request.getURI();//from  w  ww .j  a v  a 2 s.co  m

    // Is this a CONNECT request?
    if (HttpRequest.__CONNECT.equalsIgnoreCase(request.getMethod())) {
        response.setField(HttpFields.__Connection, "close"); // TODO Needed for IE????
        handleConnect(pathInContext, pathParams, request, response);
        return;
    }

    try {
        // Do we proxy this?
        URL url = isProxied(uri);
        if (url == null) {
            if (isForbidden(uri))
                sendForbid(request, response, uri);
            return;
        }

        if (log.isDebugEnabled())
            log.debug("PROXY URL=" + url);

        URLConnection connection = url.openConnection();
        connection.setAllowUserInteraction(false);

        // Set method
        HttpURLConnection http = null;
        if (connection instanceof HttpURLConnection) {
            http = (HttpURLConnection) connection;
            http.setRequestMethod(request.getMethod());
            http.setInstanceFollowRedirects(false);
        }

        // check connection header
        String connectionHdr = request.getField(HttpFields.__Connection);
        if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive)
                || connectionHdr.equalsIgnoreCase(HttpFields.__Close)))
            connectionHdr = null;

        // copy headers
        boolean xForwardedFor = false;
        boolean hasContent = false;
        Enumeration enm = request.getFieldNames();
        while (enm.hasMoreElements()) {
            // TODO could be better than this!
            String hdr = (String) enm.nextElement();

            if (_DontProxyHeaders.containsKey(hdr) || !_chained && _ProxyAuthHeaders.containsKey(hdr))
                continue;
            if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0)
                continue;

            if (HttpFields.__ContentType.equals(hdr))
                hasContent = true;

            Enumeration vals = request.getFieldValues(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val != null) {
                    connection.addRequestProperty(hdr, val);
                    xForwardedFor |= HttpFields.__XForwardedFor.equalsIgnoreCase(hdr);
                }
            }
        }

        // Proxy headers
        if (!_anonymous)
            connection.setRequestProperty("Via", "1.1 (jetty)");
        if (!xForwardedFor)
            connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr());

        // a little bit of cache control
        String cache_control = request.getField(HttpFields.__CacheControl);
        if (cache_control != null
                && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
            connection.setUseCaches(false);

        // customize Connection
        customizeConnection(pathInContext, pathParams, request, connection);

        try {
            connection.setDoInput(true);

            // do input thang!
            InputStream in = request.getInputStream();
            if (hasContent) {
                connection.setDoOutput(true);
                IO.copy(in, connection.getOutputStream());
            }

            // Connect
            connection.connect();
        } catch (Exception e) {
            LogSupport.ignore(log, e);
        }

        InputStream proxy_in = null;

        // handler status codes etc.
        int code = HttpResponse.__500_Internal_Server_Error;
        if (http != null) {
            proxy_in = http.getErrorStream();

            code = http.getResponseCode();
            response.setStatus(code);
            response.setReason(http.getResponseMessage());
        }

        if (proxy_in == null) {
            try {
                proxy_in = connection.getInputStream();
            } catch (Exception e) {
                LogSupport.ignore(log, e);
                proxy_in = http.getErrorStream();
            }
        }

        // clear response defaults.
        response.removeField(HttpFields.__Date);
        response.removeField(HttpFields.__Server);

        // set response headers
        int h = 0;
        String hdr = connection.getHeaderFieldKey(h);
        String val = connection.getHeaderField(h);
        while (hdr != null || val != null) {
            if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr)
                    && (_chained || !_ProxyAuthHeaders.containsKey(hdr)))
                response.addField(hdr, val);
            h++;
            hdr = connection.getHeaderFieldKey(h);
            val = connection.getHeaderField(h);
        }
        if (!_anonymous)
            response.setField("Via", "1.1 (jetty)");

        // Handled
        request.setHandled(true);
        if (proxy_in != null)
            IO.copy(proxy_in, response.getOutputStream());

    } catch (Exception e) {
        log.warn(e.toString());
        LogSupport.ignore(log, e);
        if (!response.isCommitted())
            response.sendError(HttpResponse.__400_Bad_Request);
    }
}

From source file:org.lockss.proxy.ProxyHandler.java

/** Proxy a connection using Java's native URLConection */
void doSun(String pathInContext, String pathParams, HttpRequest request, HttpResponse response)
        throws IOException {
    URI uri = request.getURI();//from w w w . jav a 2  s.  c o m
    try {
        // Do we proxy this?
        URL url = isProxied(uri);
        if (url == null) {
            if (isForbidden(uri)) {
                sendForbid(request, response, uri);
                logAccess(request, "forbidden method: " + request.getMethod());
            }
            return;
        }

        if (jlog.isDebugEnabled())
            jlog.debug("PROXY URL=" + url);

        URLConnection connection = url.openConnection();
        connection.setAllowUserInteraction(false);

        // Set method
        HttpURLConnection http = null;
        if (connection instanceof HttpURLConnection) {
            http = (HttpURLConnection) connection;
            http.setRequestMethod(request.getMethod());
            http.setInstanceFollowRedirects(false);
        }

        // check connection header
        String connectionHdr = request.getField(HttpFields.__Connection);
        if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive)
                || connectionHdr.equalsIgnoreCase(HttpFields.__Close)))
            connectionHdr = null;

        // copy headers
        boolean hasContent = false;
        Enumeration en = request.getFieldNames();

        while (en.hasMoreElements()) {
            // XXX could be better than this!
            String hdr = (String) en.nextElement();

            if (_DontProxyHeaders.containsKey(hdr))
                continue;

            if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0)
                continue;

            if (HttpFields.__ContentType.equalsIgnoreCase(hdr))
                hasContent = true;

            Enumeration vals = request.getFieldValues(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val != null) {
                    connection.addRequestProperty(hdr, val);
                }
            }
        }

        // Proxy headers
        connection.addRequestProperty(HttpFields.__Via, makeVia(request));
        connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr());
        // a little bit of cache control
        String cache_control = request.getField(HttpFields.__CacheControl);
        if (cache_control != null
                && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
            connection.setUseCaches(false);

        // customize Connection
        customizeConnection(pathInContext, pathParams, request, connection);

        try {
            connection.setDoInput(true);

            // do input thang!
            InputStream in = request.getInputStream();
            if (hasContent) {
                connection.setDoOutput(true);
                IO.copy(in, connection.getOutputStream());
            }

            // Connect
            connection.connect();
        } catch (Exception e) {
            LogSupport.ignore(jlog, e);
        }

        InputStream proxy_in = null;

        // handler status codes etc.
        int code = HttpResponse.__500_Internal_Server_Error;
        if (http != null) {
            proxy_in = http.getErrorStream();

            code = http.getResponseCode();
            response.setStatus(code);
            response.setReason(http.getResponseMessage());
        }

        if (proxy_in == null) {
            try {
                proxy_in = connection.getInputStream();
            } catch (Exception e) {
                LogSupport.ignore(jlog, e);
                proxy_in = http.getErrorStream();
            }
        }

        // clear response defaults.
        response.removeField(HttpFields.__Date);
        response.removeField(HttpFields.__Server);

        // set response headers
        int h = 0;
        String hdr = connection.getHeaderFieldKey(h);
        String val = connection.getHeaderField(h);
        while (hdr != null || val != null) {
            if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr))
                response.addField(hdr, val);
            h++;
            hdr = connection.getHeaderFieldKey(h);
            val = connection.getHeaderField(h);
        }
        response.addField(HttpFields.__Via, makeVia(request));

        // Handled
        request.setHandled(true);
        if (proxy_in != null)
            IO.copy(proxy_in, response.getOutputStream());

    } catch (Exception e) {
        log.warning("doSun error", e);
        if (!response.isCommitted())
            response.sendError(HttpResponse.__400_Bad_Request, e.getMessage());
    }
}