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:CounterApp.java

public int getCount() throws Exception {
    java.net.URL url = new java.net.URL(servletURL);
    java.net.URLConnection con = url.openConnection();
    if (sessionCookie != null) {
        con.setRequestProperty("cookie", sessionCookie);
    }// ww w .j av  a  2  s .  c  o  m
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(byteOut);
    out.flush();
    byte buf[] = byteOut.toByteArray();
    con.setRequestProperty("Content-type", "application/octet-stream");
    con.setRequestProperty("Content-length", "" + buf.length);
    DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
    dataOut.write(buf);
    dataOut.flush();
    dataOut.close();
    DataInputStream in = new DataInputStream(con.getInputStream());
    int count = in.readInt();
    in.close();
    if (sessionCookie == null) {
        String cookie = con.getHeaderField("set-cookie");
        if (cookie != null) {
            sessionCookie = parseCookie(cookie);
            System.out.println("Setting session ID=" + sessionCookie);
        }
    }

    return count;
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPAuthenticatorIT.java

@Test()
public void saveToDatabase() throws Exception {
    assertEquals("Unexpected calls to password provider", 0,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
    assertEquals("Unexpected calls to authenticator", 0, authenticator.calls);
    Authenticator.setDefault(authenticator);

    // Make the server expect different password so our cache is no longer
    // valid (In case CredManager.resetAuthCache() did not succeed on non-Sun VMs)
    userRealm.put(USERNAME, PASSWORD3);/* w  w w.  ja v  a2s .  c  om*/
    // But we'll try with the old one, which we'll this time ask to save in
    // DB
    UsernamePassword usernamePassword = new UsernamePassword(USERNAME, PASSWORD2);
    usernamePassword.setShouldSave(true);
    //HTTPAuthenticatorServiceUsernameAndPasswordProvider.setUsernamePassword(usernamePassword);

    URL url = new URL("http://localhost:" + PORT + "/test.html");
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), usernamePassword);
    URLConnection c = url.openConnection();
    try {
        c.getContent();
    } catch (Exception ex) {
    }

    assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage());
    assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString());

    assertEquals("HTTP/1.1 401 Unauthorized", c.getHeaderField(0));

    assertTrue("Did not invoke authenticator enough times", authenticator.calls > 1);
    assertEquals("Asked our provider more than once, not saved in credMan?", 1,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());

    // Expect the old one again
    userRealm.put(USERNAME, PASSWORD2);
    // We'll now set our provider to give an invalid password, but we should
    // not be asked
    // as the old one (now correct agian) is stored in DB
    //      HTTPAuthenticatorServiceUsernameAndPasswordProvider.setUsernamePassword(new UsernamePassword(
    //            USERNAME, WRONG_PASSWORD));
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), new UsernamePassword(USERNAME, WRONG_PASSWORD));

    HTTPAuthenticatorServiceUsernameAndPasswordProvider.resetCalls();
    authenticator.calls = 0;

    URLConnection c2 = url.openConnection();
    try {
        c2.getContent();
    } catch (Exception ex) {
    }
    assertEquals("Did not call authenticator again with cache pw invalid", 1, authenticator.calls);
    assertEquals("Called our password provider instead of using credMan saved one", 0,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPAuthenticatorIT.java

@Test()
public void differentRealm() throws Exception {

    assertEquals("Unexpected calls to password provider", 0,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());
    CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager);
    assertEquals("Unexpected calls to authenticator", 0, authenticator.calls);
    Authenticator.setDefault(authenticator);
    // Different password in case resetAuthCache() did not run
    UsernamePassword userPassword = new UsernamePassword(USERNAME, PASSWORD4);
    userRealm.put(USERNAME, PASSWORD4);//w w w . ja va  2  s  .  c o  m
    //      userPassword.setShouldSave(true);
    //FixedPasswordProvider.setUsernamePassword(userPassword);

    URL url = new URL("http://localhost:" + PORT + "/test.html");
    httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), userPassword);
    URLConnection c = url.openConnection();

    c.connect();
    try {
        c.getContent();
    } catch (Exception ex) {
    }

    assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage());
    assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString());

    assertEquals("HTTP/1.1 200 OK", c.getHeaderField(0));

    assertEquals("Did not invoke authenticator", 1, authenticator.calls);
    assertEquals("Did not invoke our password provider", 1,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());

    // different realm should be treated as a second connection, and not even use saved credentials

    credentialManager.resetAuthCache();
    userRealm.setName(REALM2);

    URLConnection c2 = url.openConnection();
    c2.connect();
    try {
        c.getContent();
    } catch (Exception ex) {
    }

    assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0));

    assertEquals("Did not invoke authenticator again", 2, authenticator.calls);
    assertEquals("Did not invoke provider again", 2,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls());

    assertEquals("Unexpected prompt/realm", REALM2, httpAuthProvider.getRequestMessage());
    assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM2,
            HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString());
}

From source file:hudson.cli.CLI.java

/**
 * If the server advertises CLI endpoint, returns its location.
 * @deprecated Specific to {@link Mode#REMOTING}.
 *///from  w  w  w. j a  va  2s. com
@Deprecated
protected CliPort getCliTcpPort(URL url) throws IOException {
    if (url.getHost() == null || url.getHost().length() == 0) {
        throw new IOException("Invalid URL: " + url);
    }
    URLConnection head = url.openConnection();
    try {
        head.connect();
    } catch (IOException e) {
        throw (IOException) new IOException("Failed to connect to " + url).initCause(e);
    }

    String h = head.getHeaderField("X-Jenkins-CLI-Host");
    if (h == null)
        h = head.getURL().getHost();
    String p1 = head.getHeaderField("X-Jenkins-CLI-Port");
    if (p1 == null)
        p1 = head.getHeaderField("X-Hudson-CLI-Port"); // backward compatibility
    String p2 = head.getHeaderField("X-Jenkins-CLI2-Port");

    String identity = head.getHeaderField("X-Instance-Identity");

    flushURLConnection(head);
    if (p1 == null && p2 == null) {
        verifyJenkinsConnection(head);

        throw new IOException("No X-Jenkins-CLI2-Port among " + head.getHeaderFields().keySet());
    }

    if (p2 != null)
        return new CliPort(new InetSocketAddress(h, Integer.parseInt(p2)), identity, 2);
    else
        return new CliPort(new InetSocketAddress(h, Integer.parseInt(p1)), identity, 1);
}

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

/**
 * set a "cookie" request header and expects the same value in the "cookie"
 * response header//from   w w w  .j a v  a  2 s.c o m
 * 
 * @throws Exception
 */
@Test
public void testMultipleRequestHeader() throws Exception {
    final String headerValue = "bla blah";
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, Response response) throws HandlerException {
            log.info("handling testMultipleRequestHeader");

            String receivedHeaderValue = request.getHeaderValues(HeaderName.COOKIE)[0];
            response.setHeader(HeaderName.COOKIE, receivedHeaderValue);
            assertEquals(headerValue, receivedHeaderValue);
        }
    }, serverBinding);

    try {
        URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        URLConnection connection = serverURL.openConnection();
        connection.setRequestProperty("CoOkie", headerValue);
        connection.setRequestProperty("FOO", "bar");
        connection.connect();
        // for the handler to be invoked, something of the response has to
        // be asked
        assertEquals(headerValue, connection.getHeaderField("Cookie"));
        connection.getContentLength();
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
}

From source file:org.infoglue.igide.helper.http.HTTPTextDocumentListenerEngine.java

private void listen() {
    String errorMessage;/*from www  .  ja va2s .  com*/
    boolean error;
    errorMessage = "";
    error = false;
    try {
        Logger.logConsole("Starting listen thread");
        URLConnection urlConn = url.openConnection();
        urlConn.setConnectTimeout(3000);
        urlConn.setRequestProperty("Connection", "Keep-Alive");
        urlConn.setReadTimeout(0);
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setAllowUserInteraction(false);
        if (urlConn.getHeaderFields().toString().indexOf("401 Unauthorized") > -1) {
            Logger.logConsole("User has no access to the CMS - closing connection");
            throw new AccessControlException("User has no access to the CMS - closing connection");
        }
        String boundary = urlConn.getHeaderField("boundary");
        DataInputStream input = new DataInputStream(urlConn.getInputStream());
        StringBuffer buf = new StringBuffer();
        if (listener != null)
            listener.onConnection(url);
        String str = null;
        while ((str = input.readLine()) != null) {
            if (str.indexOf("XMLNotificationWriter.ping") == -1) {
                if (str.equals(boundary)) {
                    String message = buf.toString();

                    // By checking there is more in the String than the XML declaration we assume the message is valid
                    if (message != null
                            && !message.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").equals("")) {
                        if (listener != null)
                            listener.recieveDocument(buf.toString());
                        else
                            Logger.logConsole((new StringBuilder("NEW DOCUMENT!!\r\n")).append(buf.toString())
                                    .append("\r\n").toString());
                    }
                    buf = new StringBuffer();
                } else {
                    buf.append(str);
                }
            }
        }
        input.close();
    } catch (MalformedURLException me) {
        error = true;
        errorMessage = (new StringBuilder("Faulty CMS-url:")).append(url).toString();
        if (listener != null)
            listener.onException(me);
        else
            System.err.println((new StringBuilder("MalformedURLException: ")).append(me).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (IOException ioe) {
        error = true;
        errorMessage = "Got an I/O-Exception talking to the CMS. Check that it is started and in valid state.";
        Logger.logConsole((new StringBuilder("ioe: ")).append(ioe.getMessage()).toString());
        if (listener != null)
            listener.onException(ioe);
        else
            Logger.logConsole((new StringBuilder("TextDocumentListener cannot connect to: "))
                    .append(url.toExternalForm()).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (AccessControlException ace) {
        error = true;
        errorMessage = "The user you tried to connect with did not have the correct access rights. Check that he/she has roles etc enough to access the CMS";
        Logger.logConsole((new StringBuilder("ioe: ")).append(ace.getMessage()).toString());
        if (listener != null)
            listener.onException(ace);
        else
            Logger.logConsole((new StringBuilder()).append(ace.getMessage()).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (Exception exception) {
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (Throwable e) {
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e2) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e2.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    }
}

From source file:com.c4mprod.utils.ImageManager.java

/**
 * //from  www.j  a  v  a2 s.  c om
 * @param listener
 *            call when download is finished
 * @param url
 *            url of the image to download
 * @param view
 *            image container (put in background if is not an ImageView)
 * @param flags
 * @param checkNewVersionDelay
 *            delay between two checks of the image in milliseconds
 * @param defaultImageId
 *            TODO
 * @param defaultDrawableId
 */
public void download(ImageDownloaderListener listener, final String url, View view, int flags,
        long checkNewVersionDelay, int defaultImageId) {
    if (mStopped || TextUtils.isEmpty(url)) {
        return;
    }
    // mListener = listener;

    // get image from cache
    Bitmap cachedBitmap = null;
    if ((flags & FLAG_GET_THUMBNAIL) != 0) {
        cachedBitmap = mImageLiveCache.get(url + THUMB_FOLDER);
    } else {
        cachedBitmap = mImageLiveCache.get(url);
    }

    ImageDownloadMessageData messageData = new ImageDownloadMessageData(url, view, defaultImageId);
    messageData.listerner = listener;
    DownloadedDrawable downloadedDrawable;
    downloadedDrawable = new DownloadedDrawable(messageData, mContext.getResources(),
            cachedBitmap != null ? cachedBitmap : getDefaultImage(defaultImageId));

    if (view != null) {
        if (view instanceof ImageView) {
            if ((flags & FLAG_IN_BACKGROUND) != 0) {
                view.setBackgroundDrawable(downloadedDrawable);
            } else {
                ((ImageView) view).setImageDrawable(downloadedDrawable);
            }

        } else if (view instanceof ImageButton) {
            if ((flags & FLAG_IN_BACKGROUND) != 0) {
                view.setBackgroundDrawable(downloadedDrawable);
            } else {
                ((ImageButton) view).setImageDrawable(downloadedDrawable);
            }
        } else {
            view.setBackgroundDrawable(downloadedDrawable);
        }
    }

    if (cachedBitmap != null) {
        // Log.d("test", "version form cache");
        Message respMessage = new Message();
        messageData.bitmap = cachedBitmap;
        messageData.flags = flags;
        respMessage.obj = messageData;
        mUiHandler.sendMessage(respMessage);
    } else {
        messageData.flags = flags;

        // check if available from sd card
        if (isSDCacheReadable()) {
            File extCacheDir = mContext.getExternalCacheDir();
            final File img = new File(extCacheDir, md5(url));
            final Long currentDate = Calendar.getInstance().getTimeInMillis();

            if (img.exists()) {

                Message msg = new Message();
                msg.obj = messageData;
                msg.what = MSG_LOAD_FROM_SD;
                mDowloadLooper.enqueueMessage(msg, true);
                // Log.d("test", "version form sdcard");
                if (img.lastModified() + checkNewVersionDelay < currentDate) {
                    final ImageDownloadMessageData test = messageData;
                    Thread thread = new Thread(new Runnable() {

                        @Override
                        public void run() {

                            Message msg = new Message();
                            msg.obj = test;
                            URL connexion;
                            try {

                                connexion = new URL(url);
                                URLConnection urlConnection;
                                urlConnection = connexion.openConnection();
                                urlConnection.connect();
                                String date = urlConnection.getHeaderField("Last-Modified");
                                if (img.lastModified() >= mDateFormater.parse(date).getTime()) {
                                    // Log.d("test", "version form sdcard after server check");
                                    return;
                                } else {
                                    // load from web
                                    // Log.d("test", "version form server");
                                    msg.what = MSG_DOWNLOAD;
                                    mDowloadLooper.enqueueMessage(msg, false);
                                }
                                urlConnection = null;
                            } catch (Exception e) {
                                return;
                            }

                        }
                    });
                    thread.start();

                }
            } else {
                Message msg = new Message();
                msg.obj = messageData;
                // load from web
                // Log.d("test", "version form server");
                msg.what = MSG_DOWNLOAD;
                mDowloadLooper.enqueueMessage(msg, false);
            }
        }

    }
}

From source file:org.chililog.server.workbench.WorkbenchServiceTest.java

/**
 * Check if our expected file types are compressed
 * /*w  ww.ja  va  2s  .  c  o  m*/
 * @throws IOException
 * @throws ParseException
 * @throws DecoderException
 */
@Test()
public void testStaticFileCompression() throws IOException, ParseException, DecoderException {
    String[] fileExtensions = new String[] { ".html", ".js", ".css", ".json", ".txt", ".xml",
            ".nocompression" };

    // Get 10K string
    String TEXT = new RandomString(1024 * 10).nextString();
    byte[] TEXT_ARRAY = TEXT.getBytes("UTF-8");

    for (String fileExtension : fileExtensions) {
        String fileName = UUID.randomUUID().toString() + fileExtension;
        File file = new File(_workbenchStaticFilesDirectory, fileName);

        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");
        out.write(TEXT);
        out.close();

        // Refresh
        file = new File(file.getPath());

        // Create a URL for the desired page
        URL url = new URL("http://localhost:8989/static/testdata/" + fileName + "?testquerystring=abc");
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");

        // Read all the compressed data
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        InputStream is = conn.getInputStream();
        int b;
        while ((b = is.read()) != -1) {
            os.write(b);
        }

        // Get headers
        String responseCode = "";
        HashMap<String, String> headers = new HashMap<String, String>();
        for (int i = 0;; i++) {
            String name = conn.getHeaderFieldKey(i);
            String value = conn.getHeaderField(i);
            if (name == null && value == null) {
                break;
            }
            if (name == null) {
                responseCode = value;
                _logger.debug("*** Intial Call, Response code: %s", value);
            } else {
                headers.put(name, value);
                _logger.debug("%s = %s", name, value);
            }
        }

        // Should get back a 200
        assertEquals("HTTP/1.1 200 OK", responseCode);
        assertTrue(!StringUtils.isBlank(headers.get("Date")));

        if (fileExtension != ".nocompression") {
            // Uncompress and check it out
            assertEquals("gzip", headers.get("Content-Encoding"));
            byte[] uncompressedContent = uncompress(os.toByteArray());
            for (int j = 0; j < TEXT_ARRAY.length; j++) {
                assertEquals(TEXT_ARRAY[j], uncompressedContent[j]);
            }
        }

        // Clean up
        file.delete();
    }

    return;
}

From source file:org.chililog.server.workbench.WorkbenchServiceTest.java

/**
 * Check if our 304 Not Modified is working when getting a static file.
 * /*  w  ww  .ja va 2  s.co  m*/
 * @throws IOException
 * @throws ParseException
 */
@Test()
public void testStaticFileCache() throws IOException, ParseException {
    String TEXT = "abc\n123";

    String fileName = UUID.randomUUID().toString() + ".txt";
    File file = new File(_workbenchStaticFilesDirectory, fileName);

    FileOutputStream fos = new FileOutputStream(file);
    OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");
    out.write(TEXT);
    out.close();

    // Refresh
    file = new File(file.getPath());

    // ******************************************************
    // Initial request
    // ******************************************************
    // Create a URL for the desired page
    URL url = new URL("http://localhost:8989/static/testdata/" + fileName);
    URLConnection conn = url.openConnection();

    // Read all the text returned by the server
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer sb = new StringBuffer();
    String str;
    while ((str = in.readLine()) != null) {
        sb.append(str + "\n");
    }
    in.close();

    assertEquals(TEXT, sb.toString().trim());

    // Get headers
    HashMap<String, String> headers = new HashMap<String, String>();
    for (int i = 0;; i++) {
        String name = conn.getHeaderFieldKey(i);
        String value = conn.getHeaderField(i);
        if (name == null && value == null) {
            break;
        }
        if (name == null) {
            _logger.debug("*** Intial Call, Response code: %s", value);
        } else {
            headers.put(name, value);
            _logger.debug("%s = %s", name, value);
        }
    }

    assertEquals("7", headers.get("Content-Length"));
    assertEquals("text/plain", headers.get("Content-Type"));

    // Check last modified should be the same as the file's last modified date
    SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
    fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
    assertEquals(fmt.format(new Date(file.lastModified())), headers.get("Last-Modified"));

    // Check Expiry
    Date expires = fmt.parse(headers.get("Expires"));
    Date serverDate = fmt.parse(headers.get("Date"));
    Calendar cal = new GregorianCalendar();
    cal.setTime(serverDate);
    cal.add(Calendar.SECOND, AppProperties.getInstance().getWorkbenchStaticFilesCacheSeconds());
    assertEquals(cal.getTimeInMillis(), expires.getTime());

    // ******************************************************
    // Cache Validation
    // ******************************************************
    url = new URL("http://localhost:8989/static/testdata/" + fileName);
    conn = url.openConnection();
    conn.setIfModifiedSince(fmt.parse(headers.get("Last-Modified")).getTime());

    in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuffer();
    while ((str = in.readLine()) != null) {
        sb.append(str + "\n");
    }
    in.close();

    // No content should be returned
    assertEquals("", sb.toString().trim());

    HashMap<String, String> headers2 = new HashMap<String, String>();
    String responseCode = "";
    for (int i = 0;; i++) {
        String name = conn.getHeaderFieldKey(i);
        String value = conn.getHeaderField(i);
        if (name == null && value == null) {
            break;
        }
        if (name == null) {
            responseCode = value;
            _logger.debug("*** Cache Call, Response code: %s", value);
        } else {
            headers2.put(name, value);
            _logger.debug("%s = %s", name, value);
        }
    }

    // Should get back a 304
    assertEquals("HTTP/1.1 304 Not Modified", responseCode);
    assertTrue(!StringUtils.isBlank(headers2.get("Date")));

    // ******************************************************
    // Finish
    // ******************************************************
    // Clean up
    file.delete();
}

From source file:org.drools.core.io.impl.UrlResource.java

private long grabLastMod() throws IOException {
    // use File if possible, as http rounds milliseconds on some machines, this fine level of granularity is only really an issue for testing
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4504473
    if ("file".equals(url.getProtocol())) {
        File file = getFile();//  w  w  w . j av  a  2s.  c  o  m
        return file.lastModified();
    } else {
        URLConnection conn = openURLConnection(getURL());
        if (conn instanceof HttpURLConnection) {
            ((HttpURLConnection) conn).setRequestMethod("HEAD");
            if ("enabled".equalsIgnoreCase(basicAuthentication)) {
                String userpassword = username + ":" + password;
                byte[] authEncBytes = Base64.encodeBase64(userpassword.getBytes(IoUtils.UTF8_CHARSET));

                ((HttpURLConnection) conn).setRequestProperty("Authorization",
                        "Basic " + new String(authEncBytes, IoUtils.UTF8_CHARSET));
            }
        }
        long date = conn.getLastModified();
        if (date == 0) {
            try {
                date = Long.parseLong(conn.getHeaderField("lastModified"));
            } catch (Exception e) { /* well, we tried ... */
            }
        }
        return date;
    }
}