Example usage for java.net URLConnection setDefaultUseCaches

List of usage examples for java.net URLConnection setDefaultUseCaches

Introduction

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

Prototype

public void setDefaultUseCaches(boolean defaultusecaches) 

Source Link

Document

Sets the default value of the useCaches field to the specified value.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {

    URL u = new URL("http://www.java2s.com");
    URLConnection uc = u.openConnection();

    uc.setDefaultUseCaches(true);
    System.out.println(uc.getDefaultUseCaches());
}

From source file:org.fragzone.unrealmmo.bukkit.entities.npcs.NPCProfile.java

private static void addProperties(GameProfile profile, UUID id) {
    String uuid = id.toString().replaceAll("-", "");

    try {//  w  w w .ja v a 2s.  c o  m
        // Get the name from SwordPVP
        URL url = new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid);
        URLConnection uc = url.openConnection();
        uc.setUseCaches(false);
        uc.setDefaultUseCaches(false);
        uc.addRequestProperty("User-Agent", "Mozilla/5.0");
        uc.addRequestProperty("Cache-Control", "no-cache, no-store, must-revalidate");
        uc.addRequestProperty("Pragma", "no-cache");

        // Parse it
        Scanner scanner = new Scanner(uc.getInputStream(), "UTF-8");
        String json = scanner.useDelimiter("\\A").next();
        scanner.close();
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(json);
        JSONArray properties = (JSONArray) ((JSONObject) obj).get("properties");

        for (int i = 0; i < properties.size(); i++) {
            try {
                JSONObject property = (JSONObject) properties.get(i);
                String name = (String) property.get("name");
                String value = (String) property.get("value");
                String signature = property.containsKey("signature") ? (String) property.get("signature")
                        : null;
                if (signature != null) {
                    profile.getProperties().put(name, new Property(name, value, signature));
                } else {
                    profile.getProperties().put(name, new Property(value, name));
                }
            } catch (Exception e) {
                Bukkit.getLogger().log(Level.WARNING, "Failed to apply auth property", e);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.pms.util.OpenSubtitle.java

public static String postPage(URLConnection connection, String query) throws IOException {
    connection.setDoOutput(true);/*from  ww  w.jav a2  s. c  o m*/
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.setDefaultUseCaches(false);
    connection.setRequestProperty("Content-Type", "text/xml");
    connection.setRequestProperty("Content-Length", "" + query.length());
    ((HttpURLConnection) connection).setRequestMethod("POST");
    //LOGGER.debug("opensub query "+query);
    // open up the output stream of the connection
    if (!StringUtils.isEmpty(query)) {
        try (DataOutputStream output = new DataOutputStream(connection.getOutputStream())) {
            output.writeBytes(query);
            output.flush();
        }
    }

    StringBuilder page;
    try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        page = new StringBuilder();
        String str;
        while ((str = in.readLine()) != null) {
            page.append(str.trim());
            page.append("\n");
        }
    }
    //LOGGER.debug("opensubs result page "+page.toString());
    return page.toString();
}

From source file:me.mast3rplan.phantombot.twitch.TwitchAPI.java

public JSONObject getObject(String url) throws IOException {
    URLConnection connection = new URL(url).openConnection();
    connection.setUseCaches(false);/*  w  w  w. j a va 2s .c  om*/
    connection.setDefaultUseCaches(false);
    String content = IOUtils.toString(connection.getInputStream(), connection.getContentEncoding());
    return new JSONObject(content);
}

From source file:me.mast3rplan.phantombot.twitch.TwitchAPI.java

public JSONObject postObject(String url) throws IOException {
    URLConnection connection = new URL(url).openConnection();
    connection.setUseCaches(false);//ww w  . ja v  a  2s .c  om
    connection.setDefaultUseCaches(false);
    connection.addRequestProperty(url, url);
    String content = IOUtils.toString(connection.getInputStream(), connection.getContentEncoding());
    return new JSONObject(content);
}

From source file:info.mallmc.framework.util.ProfileLoader.java

private void addProperties(GameProfile profile) {
    String uuid = getUUID(skinOwner);
    try {/*w ww  .jav a  2s  . c o m*/
        // Get the name from SwordPVP
        URL url = new URL(
                "https://sessionserver.mojang.com/session/minecraft/profile/" + uuid + "?unsigned=false");
        URLConnection uc = url.openConnection();
        uc.setUseCaches(false);
        uc.setDefaultUseCaches(false);
        uc.addRequestProperty("User-Agent", "Mozilla/5.0");
        uc.addRequestProperty("Cache-Control", "no-cache, no-store, must-revalidate");
        uc.addRequestProperty("Pragma", "no-cache");

        // Parse it
        String json = new Scanner(uc.getInputStream(), "UTF-8").useDelimiter("\\A").next();
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(json);
        JSONArray properties = (JSONArray) ((JSONObject) obj).get("properties");
        for (int i = 0; i < properties.size(); i++) {
            try {
                JSONObject property = (JSONObject) properties.get(i);
                String name = (String) property.get("name");
                String value = (String) property.get("value");
                String signature = property.containsKey("signature") ? (String) property.get("signature")
                        : null;
                if (signature != null) {
                    profile.getProperties().put(name, new Property(name, value, signature));
                } else {
                    profile.getProperties().put(name, new Property(value, name));
                }
            } catch (Exception e) {
                L.ogError(LL.ERROR, Trigger.LOAD, "Failed to apply auth property",
                        "Failed to apply auth property");
            }
        }
    } catch (Exception e) {
        ; // Failed to load skin
    }
}

From source file:org.openmrs.module.ModuleUtil.java

/**
 * Downloads the contents of a URL and copies them to a string (Borrowed from oreilly)
 *
 * @param url//from  w  ww. ja va  2  s.c  om
 * @return InputStream of contents
 * @should return a valid input stream for old module urls
 */
public static InputStream getURLStream(URL url) {
    InputStream in = null;
    try {
        URLConnection uc = url.openConnection();
        uc.setDefaultUseCaches(false);
        uc.setUseCaches(false);
        uc.setRequestProperty("Cache-Control", "max-age=0,no-cache");
        uc.setRequestProperty("Pragma", "no-cache");

        log.debug("Logging an attempt to connect to: " + url);

        in = openConnectionCheckRedirects(uc);
    } catch (IOException io) {
        log.warn("io while reading: " + url, io);
    }

    return in;
}

From source file:com.wavemaker.runtime.module.ModuleController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    String requestURI = request.getRequestURI();
    final String moduleURI = "/" + MODULES_PREFIX;
    final String moduleURIAbs = moduleURI + "/";
    final String moduleJsURI = moduleURIAbs + MODULES_JS;
    final String epURI = moduleURIAbs + EXTENSION_PATH;
    final String epURIAbs = epURI + "/";
    final String idURI = moduleURIAbs + ID_PATH;
    final String idURIAbs = idURI + "/";

    // trim off the servlet name
    requestURI = requestURI.substring(requestURI.indexOf('/', 1));

    if (moduleURI.equals(requestURI) || moduleURIAbs.equals(requestURI)) {
    } else if (epURI.equals(requestURI) || epURIAbs.equals(requestURI)) {
        Set<String> names = this.moduleManager.listExtensionPoints();

        response.setContentType("text/html");
        Writer writer = response.getWriter();
        writer.write("<html><body>\n");
        for (String ext : names) {
            writer.write(ext + "<br />\n");
        }//from   www .  j av a2s  . c om
        writer.write("</body></html>\n");
        writer.close();
    } else if (idURI.equals(requestURI) || idURIAbs.equals(requestURI)) {
        Set<String> names = this.moduleManager.listModules();

        response.setContentType("text/html");
        Writer writer = response.getWriter();
        writer.write("<html><body>\n");
        for (String ext : names) {
            writer.write(ext + "<br />\n");
        }
        writer.write("</body></html>\n");
        writer.close();
    } else if (moduleJsURI.equals(requestURI)) {
        Set<String> extensions = this.moduleManager.listExtensionPoints();

        JSONObject jo = new JSONObject();

        JSONObject extJO = new JSONObject();
        for (String extension : extensions) {
            JSONArray ja = new JSONArray();

            List<ModuleWire> wires = this.moduleManager.getModules(extension);
            for (ModuleWire wire : wires) {
                ja.add(wire.getName());
            }

            extJO.put(extension, ja);
        }

        jo.put("extensionPoints", extJO);

        response.setContentType(ServerConstants.JSON_CONTENT_TYPE);
        Writer writer = response.getWriter();
        writer.write(jo.toString());
        writer.close();
    } else {
        Tuple.Two<ModuleWire, String> tuple = parseRequestPath(requestURI);
        if (tuple.v1 == null) {
            String message = MessageResource.NO_MODULE_RESOURCE.getMessage(requestURI, tuple.v2);
            this.logger.error(message);

            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            Writer outputWriter = response.getWriter();
            outputWriter.write(message);

            return null;
        }

        URL url = this.moduleManager.getModuleResource(tuple.v1, tuple.v2);
        URLConnection conn = url.openConnection();
        if (SystemUtils.IS_OS_WINDOWS) {
            conn.setDefaultUseCaches(false);
        }

        response.setContentType(conn.getContentType());
        OutputStream os = null;
        InputStream is = null;

        try {
            os = response.getOutputStream();
            is = conn.getInputStream();

            IOUtils.copy(conn.getInputStream(), os);
        } finally {
            if (os != null) {
                os.close();
            }
            if (is != null) {
                is.close();
            }
        }
    }

    return null;
}

From source file:org.openmrs.util.OpenmrsClassLoader.java

/**
 * Creates the instance for the OpenmrsClassLoader
 *///from   www.  j av a  2 s  . co  m
public OpenmrsClassLoader(ClassLoader parent) {
    super(new URL[0], parent);

    if (parent instanceof OpenmrsClassLoader) {
        throw new IllegalArgumentException("Parent must not be OpenmrsClassLoader nor null");
    } else if (parent instanceof ModuleClassLoader) {
        throw new IllegalArgumentException("Parent must not be ModuleClassLoader");
    }

    OpenmrsClassLoaderHolder.INSTANCE = this;

    if (log.isDebugEnabled()) {
        log.debug("Creating new OpenmrsClassLoader instance with parent: " + parent);
    }

    //disable caching so the jars aren't locked
    //if performance is effected, this can be disabled in favor of
    //copying all opened jars to a temp location
    //(ala org.apache.catalina.loader.WebappClassLoader antijarlocking)
    URLConnection urlConnection = new OpenmrsURLConnection();
    urlConnection.setDefaultUseCaches(false);
}

From source file:com.google.gwt.dev.shell.jetty.JettyLauncher.java

/**
 * This is a modified version of JreMemoryLeakPreventionListener.java found
 * in the Apache Tomcat project at//from   w  w  w. ja v a  2 s . c om
 *
 * http://svn.apache.org/repos/asf/tomcat/trunk/java/org/apache/catalina/core/
 * JreMemoryLeakPreventionListener.java
 *
 * Relevant part of the Tomcat NOTICE, retrieved from
 * http://svn.apache.org/repos/asf/tomcat/trunk/NOTICE Apache Tomcat Copyright
 * 1999-2010 The Apache Software Foundation
 *
 * This product includes software developed by The Apache Software Foundation
 * (http://www.apache.org/).
 */
private void jreLeakPrevention(TreeLogger logger) {
    // Trigger a call to sun.awt.AppContext.getAppContext(). This will
    // pin the common class loader in memory but that shouldn't be an
    // issue.
    ImageIO.getCacheDirectory();

    /*
     * Several components end up calling: sun.misc.GC.requestLatency(long)
     *
     * Those libraries / components known to trigger memory leaks due to
     * eventual calls to requestLatency(long) are: -
     * javax.management.remote.rmi.RMIConnectorServer.start()
     */
    try {
        Class<?> clazz = Class.forName("sun.misc.GC");
        Method method = clazz.getDeclaredMethod("requestLatency", new Class[] { long.class });
        method.invoke(null, Long.valueOf(3600000));
    } catch (ClassNotFoundException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.gcDaemonFail", e);
    } catch (SecurityException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.gcDaemonFail", e);
    } catch (NoSuchMethodException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.gcDaemonFail", e);
    } catch (IllegalArgumentException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.gcDaemonFail", e);
    } catch (IllegalAccessException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.gcDaemonFail", e);
    } catch (InvocationTargetException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.gcDaemonFail", e);
    }

    /*
     * Calling getPolicy retains a static reference to the context class loader.
     */
    try {
        // Policy.getPolicy();
        Class<?> policyClass = Class.forName("javax.security.auth.Policy");
        Method method = policyClass.getMethod("getPolicy");
        method.invoke(null);
    } catch (ClassNotFoundException e) {
        // Ignore. The class is deprecated.
    } catch (SecurityException e) {
        // Ignore. Don't need call to getPolicy() to be successful,
        // just need to trigger static initializer.
    } catch (NoSuchMethodException e) {
        logger.log(TreeLogger.WARN, "jreLeakPrevention.authPolicyFail", e);
    } catch (IllegalArgumentException e) {
        logger.log(TreeLogger.WARN, "jreLeakPrevention.authPolicyFail", e);
    } catch (IllegalAccessException e) {
        logger.log(TreeLogger.WARN, "jreLeakPrevention.authPolicyFail", e);
    } catch (InvocationTargetException e) {
        logger.log(TreeLogger.WARN, "jreLeakPrevention.authPolicyFail", e);
    }

    /*
     * Creating a MessageDigest during web application startup initializes the
     * Java Cryptography Architecture. Under certain conditions this starts a
     * Token poller thread with TCCL equal to the web application class loader.
     *
     * Instead we initialize JCA right now.
     */
    java.security.Security.getProviders();

    /*
     * Several components end up opening JarURLConnections without first
     * disabling caching. This effectively locks the file. Whilst more
     * noticeable and harder to ignore on Windows, it affects all operating
     * systems.
     *
     * Those libraries/components known to trigger this issue include: - log4j
     * versions 1.2.15 and earlier - javax.xml.bind.JAXBContext.newInstance()
     */

    // Set the default URL caching policy to not to cache
    try {
        // 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);
    } catch (MalformedURLException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.jarUrlConnCacheFail", e);
    } catch (IOException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.jarUrlConnCacheFail", e);
    }

    /*
     * Haven't got to the root of what is going on with this leak but if a web
     * app is the first to make the calls below the web application class loader
     * will be pinned in memory.
     */
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.xmlParseFail", e);
    }
}