下面列出了java.net.URLConnection#setDefaultUseCaches ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
void checkJAR(boolean defaultValue) throws IOException {
URLConnection.setDefaultUseCaches("JAR", defaultValue);
assertEquals(URLConnection.getDefaultUseCaches("JAr"), defaultValue);
URLConnection jarFileURLConn = jarFileURL.openConnection();
URLConnection jarHttpURLConn = jarHttpURL.openConnection();
assertEquals(jarFileURLConn.getUseCaches(), defaultValue);
assertEquals(jarHttpURLConn.getUseCaches(), defaultValue);
jarFileURLConn.setUseCaches(!defaultValue);
jarHttpURLConn.setUseCaches(!defaultValue);
assertEquals(jarFileURLConn.getUseCaches(), !defaultValue);
assertEquals(jarHttpURLConn.getUseCaches(), !defaultValue);
URLConnection.setDefaultUseCaches("JaR", !defaultValue); // case-insensitive
assertEquals(URLConnection.getDefaultUseCaches("jAR"), !defaultValue);
jarFileURLConn = jarFileURL.openConnection();
jarHttpURLConn = jarHttpURL.openConnection();
assertEquals(jarFileURLConn.getUseCaches(), !defaultValue);
assertEquals(jarHttpURLConn.getUseCaches(), !defaultValue);
jarFileURLConn.setUseCaches(defaultValue);
jarHttpURLConn.setUseCaches(defaultValue);
assertEquals(jarFileURLConn.getUseCaches(), defaultValue);
assertEquals(jarHttpURLConn.getUseCaches(), defaultValue);
}
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
protected Optional<InputStream> newStream(final URL url) {
try {
final URLConnection connection = urlConnectionFactory.apply(url);
// Turn off URL connection caching to avoid open file leaks. When caching is on, the
// InputStream
// returned is left open, even after you call 'InputStream.close()'
connection.setDefaultUseCaches(
false); // TODO: verify - setDefaultUseCaches(false) may not be necessary
connection.setUseCaches(false);
return Optional.of(connection.getInputStream());
} catch (final IOException e) {
log.log(Level.SEVERE, "Unable to open: " + url, e);
return Optional.empty();
}
}
/**
* Disables caching for JAR URL connections. For Java 8 and earlier, this also disables
* caching for ALL URL connections.
*
* @throws IOException If a dummy JAR URLConnection can not be created
*/
public void disableCachingForJarUrlConnections() throws IOException {
// Doesn't matter that this JAR doesn't exist - just as
// long as the URL is well-formed
URL url = new URL("jar:file://dummy.jar!/");
URLConnection uConn = url.openConnection();
uConn.setDefaultUseCaches(false);
}
/**
* Enables or disables caching for URLConnection.
*
* @return the value of useCaching before this call
*/
public static boolean setUseCaching(boolean useCache) {
try {
URLConnection URLConnection = new URL("http://localhost/").openConnection();
boolean oldValue = URLConnection.getDefaultUseCaches();
URLConnection.setDefaultUseCaches(useCache);
return oldValue;
} catch(Exception ex) {
return true;
}
}
void checkFile() throws IOException {
URLConnection fileURLConn = fileURL.openConnection();
assertTrue(fileURLConn.getDefaultUseCaches());
// set default default to false and check other values the same
fileURLConn.setDefaultUseCaches(false);
fileURLConn.setDefaultUseCaches("fiLe", true);
assertFalse(fileURLConn.getDefaultUseCaches());
assertTrue(URLConnection.getDefaultUseCaches("fiLE"));
}
/**
* Called when the applet is initialized.
*/
@Override
public void init() {
try {
// get applet parameter - URL from which to get the CAS
String casURL = getParameter("CasUrl");
// open URL connection to get the serialized CAS
URLConnection con = new URL(casURL).openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setDefaultUseCaches(false);
con.setRequestProperty("Content-Type", "application/octet-stream");
// con.connect();
InputStream in = con.getInputStream();
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] buf = new byte[2048];
int bytesRead = in.read(buf);
while (bytesRead > 0) {
byteStream.write(buf, 0, bytesRead);
bytesRead = in.read(buf);
}
byte[] bytes = byteStream.toByteArray();
in.close();
byteStream.close();
System.out.println("Got " + bytes.length + " bytes.");
// deserialize CAS
CASMgr casMgr = CASFactory.createCAS();
CASCompleteSerializer serializer = (CASCompleteSerializer) SerializationUtils
.deserialize(bytes);
Serialization.deserializeCASComplete(serializer, casMgr);
// get 2nd applet parameter - right-to-left text orientation
boolean rightToLeft = false;
String rightToLeftParam = getParameter("RightToLeftTextOrientation");
if (rightToLeftParam != null && rightToLeftParam.equalsIgnoreCase("true")) {
rightToLeft = true;
}
// create viewer component and add to this applet
mViewer = new CasAnnotationViewer();
// NOTE: it seems to be important to add the viewer to the frame
// before calling setCAS. If we do it the other way around
// we seem to frequently cause the browser to hang.
getContentPane().add(mViewer);
mViewer.setCAS(casMgr.getCAS().getView(CAS.NAME_DEFAULT_SOFA));
mViewer.setRightToLeftTextOrientation(rightToLeft);
// add a listener that detects resize events
addComponentListener(new MyComponentListener());
// set initial size of tree viewer panel
resizeTreeViewer();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected
void
doProcess()
{
try
{
ProxyWrapper proxyWrapper = ApplicationProperties.getProxy();
URL url = new URL(getURL());
URLConnection connection = url.openConnection(proxyWrapper.createProxy());
String latestVersion = null;
connection.setConnectTimeout(TIMEOUT);
connection.setDefaultUseCaches(false);
connection.setReadTimeout(TIMEOUT);
latestVersion = readVersion(connection);
signalProcessIsDone();
if(CURRENT_VERSION.equals(latestVersion) == true)
{
inform(getProperty("no_update.title"),
getProperty("no_update.description"));
}
else
{
if(decide(getProperty("update.title"),
getProperty("update.description")) == true)
{
ResourceHelper.openURL(getSharedProperty("url"));
}
}
}
catch(Exception exception)
{
// Ignore errors if the dialog was canceled.
if(canProcess() == true)
{
signalProcessIsDone();
if(exception instanceof SocketTimeoutException)
{
error(getProperty("error.title"),
getProperty("network_error.description"));
}
else
{
error(getProperty("error.title"),
getProperty("no_service_error.description"));
}
}
}
}
private InputStream openConnectionForUrl(URL url) throws IOException {
URLConnection urlConnection = url.openConnection();
urlConnection.setDefaultUseCaches(false);
return urlConnection.getInputStream();
}
/**
* Override to set up your specific external resource.
* @throws Throwable if setup fails (which will disable {@code after}
*/
public void before() throws Throwable {
for (Handler h : Logger.getLogger("").getHandlers()) {
if (h instanceof ConsoleHandler) {
((ConsoleHandler) h).setFormatter(new DeltaSupportLogFormatter());
}
}
if (Thread.interrupted()) { // JENKINS-30395
LOGGER.warning("was interrupted before start");
}
if(Functions.isWindows()) {
// JENKINS-4409.
// URLConnection caches handles to jar files by default,
// and it prevents delete temporary directories on Windows.
// Disables caching here.
// Though defaultUseCache is a static field,
// its setter and getter are provided as instance methods.
URLConnection aConnection = new File(".").toURI().toURL().openConnection();
origDefaultUseCache = aConnection.getDefaultUseCaches();
aConnection.setDefaultUseCaches(false);
}
// Not ideal (https://github.com/junit-team/junit/issues/116) but basically works.
if (Boolean.getBoolean("ignore.random.failures")) {
RandomlyFails rf = testDescription.getAnnotation(RandomlyFails.class);
if (rf != null) {
throw new AssumptionViolatedException("Known to randomly fail: " + rf.value());
}
}
env = new TestEnvironment(testDescription);
env.pin();
recipe();
AbstractProject.WORKSPACE.toString();
User.clear();
try {
Field theInstance = Jenkins.class.getDeclaredField("theInstance");
theInstance.setAccessible(true);
if (theInstance.get(null) != null) {
LOGGER.warning("Jenkins.theInstance was not cleared by a previous test, doing that now");
theInstance.set(null, null);
}
} catch (Exception x) {
LOGGER.log(Level.WARNING, null, x);
}
try {
jenkins = hudson = newHudson();
// If the initialization graph is corrupted, we cannot expect that Jenkins is in the good shape.
// Likely it is an issue in @Initializer() definitions (see JENKINS-37759).
// So we just fail the test.
if (jenkins.getInitLevel() != InitMilestone.COMPLETED) {
throw new Exception("Jenkins initialization has not reached the COMPLETED initialization stage. Current state is " + jenkins.getInitLevel() +
". Likely there is an issue with the Initialization task graph (e.g. usage of @Initializer(after = InitMilestone.COMPLETED)). See JENKINS-37759 for more info");
}
} catch (Exception e) {
// if Hudson instance fails to initialize, it leaves the instance field non-empty and break all the rest of the tests, so clean that up.
Field f = Jenkins.class.getDeclaredField("theInstance");
f.setAccessible(true);
f.set(null,null);
throw e;
}
jenkins.setCrumbIssuer(new TestCrumbIssuer()); // TODO: Move to _configureJenkinsForTest after JENKINS-55240
_configureJenkinsForTest(jenkins);
configureUpdateCenter();
// expose the test instance as a part of URL tree.
// this allows tests to use a part of the URL space for itself.
jenkins.getActions().add(this);
JenkinsLocationConfiguration.get().setUrl(getURL().toString());
}
/**
* Override to tear down your specific external resource.
*/
public void after() throws Exception {
try {
if (jenkins!=null) {
for (EndOfTestListener tl : jenkins.getExtensionList(EndOfTestListener.class))
tl.onTearDown();
}
// cancel pending asynchronous operations, although this doesn't really seem to be working
for (WebClient client : clients) {
// unload the page to cancel asynchronous operations
try {
client.getPage("about:blank");
} catch (IOException e) {
// ignore
}
client.close();
}
clients.clear();
} finally {
_stopJenkins(server, tearDowns, jenkins);
try {
env.dispose();
} finally {
// Hudson creates ClassLoaders for plugins that hold on to file descriptors of its jar files,
// but because there's no explicit dispose method on ClassLoader, they won't get GC-ed until
// at some later point, leading to possible file descriptor overflow. So encourage GC now.
// see http://bugs.sun.com/view_bug.do?bug_id=4950148
// TODO use URLClassLoader.close() in Java 7
System.gc();
// restore defaultUseCache
if(Functions.isWindows()) {
URLConnection aConnection = new File(".").toURI().toURL().openConnection();
aConnection.setDefaultUseCaches(origDefaultUseCache);
}
}
}
}
@Override
protected void setUp() throws Exception {
if (Thread.interrupted()) { // JENKINS-30395
LOGGER.warning("was interrupted before start");
}
if(Functions.isWindows()) {
// JENKINS-4409.
// URLConnection caches handles to jar files by default,
// and it prevents delete temporary directories on Windows.
// Disables caching here.
// Though defaultUseCache is a static field,
// its setter and getter are provided as instance methods.
URLConnection aConnection = new File(".").toURI().toURL().openConnection();
origDefaultUseCache = aConnection.getDefaultUseCaches();
aConnection.setDefaultUseCaches(false);
}
env.pin();
recipe();
for (Runner r : recipes) {
if (r instanceof WithoutJenkins.RunnerImpl)
return; // no setup
}
AbstractProject.WORKSPACE.toString();
User.clear();
// just in case tearDown failed in the middle, make sure to really clean them up so that there's no left-over from earlier tests
ExtensionList.clearLegacyInstances();
DescriptorExtensionList.clearLegacyInstances();
try {
jenkins = hudson = newHudson();
} catch (Exception e) {
// if Jenkins instance fails to initialize, it leaves the instance field non-empty and break all the rest of the tests, so clean that up.
Field f = Jenkins.class.getDeclaredField("theInstance");
f.setAccessible(true);
f.set(null,null);
throw e;
}
jenkins.setNoUsageStatistics(true); // collecting usage stats from tests are pointless.
jenkins.setCrumbIssuer(new TestCrumbIssuer());
jenkins.servletContext.setAttribute("app", jenkins);
jenkins.servletContext.setAttribute("version","?");
WebAppMain.installExpressionFactory(new ServletContextEvent(jenkins.servletContext));
JenkinsLocationConfiguration.get().setUrl(getURL().toString());
// set a default JDK to be the one that the harness is using.
jenkins.getJDKs().add(new JDK("default",System.getProperty("java.home")));
configureUpdateCenter();
// expose the test instance as a part of URL tree.
// this allows tests to use a part of the URL space for itself.
jenkins.getActions().add(this);
// cause all the descriptors to reload.
// ideally we'd like to reset them to properly emulate the behavior, but that's not possible.
for( Descriptor d : jenkins.getExtensionList(Descriptor.class) )
d.load();
// allow the test class to inject Jenkins components
jenkins.lookup(Injector.class).injectMembers(this);
setUpTimeout();
}
@Override
protected void tearDown() throws Exception {
try {
if (jenkins!=null) {
for (EndOfTestListener tl : jenkins.getExtensionList(EndOfTestListener.class))
tl.onTearDown();
}
if (timeoutTimer!=null) {
timeoutTimer.cancel();
timeoutTimer = null;
}
// cancel pending asynchronous operations, although this doesn't really seem to be working
for (WebClient client : clients) {
// unload the page to cancel asynchronous operations
client.getPage("about:blank");
client.close();
}
clients.clear();
} finally {
if (server!=null)
server.stop();
for (LenientRunnable r : tearDowns)
r.run();
if (jenkins!=null)
jenkins.cleanUp();
ExtensionList.clearLegacyInstances();
DescriptorExtensionList.clearLegacyInstances();
try {
env.dispose();
} catch (Exception x) {
x.printStackTrace();
}
// Jenkins creates ClassLoaders for plugins that hold on to file descriptors of its jar files,
// but because there's no explicit dispose method on ClassLoader, they won't get GC-ed until
// at some later point, leading to possible file descriptor overflow. So encourage GC now.
// see http://bugs.sun.com/view_bug.do?bug_id=4950148
System.gc();
// restore defaultUseCache
if(Functions.isWindows()) {
URLConnection aConnection = new File(".").toURI().toURL().openConnection();
aConnection.setDefaultUseCaches(origDefaultUseCache);
}
}
}