Java Code Examples for java.net.URLConnection#setUseCaches()

The following examples show how to use java.net.URLConnection#setUseCaches() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CertificateValidator.java    From keycloak with Apache License 2.0 7 votes vote down vote up
private Collection<X509CRL> loadFromURI(CertificateFactory cf, URI remoteURI) throws GeneralSecurityException {
    try {
        logger.debugf("Loading CRL from %s", remoteURI.toString());

        URLConnection conn = remoteURI.toURL().openConnection();
        conn.setDoInput(true);
        conn.setUseCaches(false);
        X509CRL crl = loadFromStream(cf, conn.getInputStream());
        return Collections.singleton(crl);
    }
    catch(IOException ex) {
        logger.errorf(ex.getMessage());
    }
    return Collections.emptyList();

}
 
Example 2
Source File: ServiceLoader.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Parse the content of the given URL as a provider-configuration file.
 */
private Iterator<String> parse(URL u) {
    Set<String> names = new LinkedHashSet<>(); // preserve insertion order
    try {
        URLConnection uc = u.openConnection();
        uc.setUseCaches(false);
        try (InputStream in = uc.getInputStream();
             BufferedReader r
                 = new BufferedReader(new InputStreamReader(in, UTF_8.INSTANCE)))
        {
            int lc = 1;
            while ((lc = parseLine(u, r, lc, names)) >= 0);
        }
    } catch (IOException x) {
        fail(service, "Error accessing configuration file", x);
    }
    return names.iterator();
}
 
Example 3
Source File: LolaSoundnessChecker.java    From codebase with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Calls the LoLA service with the given PNML under the given URL.
 * @param pnml of the Petri net
 * @param address - URL of the LoLA service 
 * @return text response from LoLA
 * @throws IOException 
 */
private static String callLola(String pnml, String address) throws IOException {
	URL url = new URL(address);
       URLConnection conn = url.openConnection();
       conn.setDoOutput(true);
       conn.setUseCaches(false);
       conn.setReadTimeout(TIMEOUT);
       OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
   
       // send pnml
       writer.write("input=" + URLEncoder.encode(pnml, "UTF-8"));
       writer.flush();
       
       // get the response
       StringBuffer answer = new StringBuffer();
       BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
       String line;
       while ((line = reader.readLine()) != null) {
           answer.append(line);
       }
       writer.close();
       reader.close();
       return answer.toString();
}
 
Example 4
Source File: NativeDataLoaderCall.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public byte[] call() {
	OutputStream out = null;
	InputStream inputStream = null;
	byte[] result = null;
	try {
		URLConnection connection = createConnection();

		connection.setUseCaches(useCaches);
		connection.setDoInput(true);
		if (content != null) {
			connection.setDoOutput(true);
			out = connection.getOutputStream();
			Utils.write(content, out);
		}
		inputStream = connection.getInputStream();
		result = Utils.toByteArray(maxInputSize > 0? new MaxSizeInputStream(inputStream, maxInputSize, url): inputStream);
	} catch (IOException e) {
		throw new DSSException(String.format(ERROR_MESSAGE, url, e.getMessage()), e);
	} finally {
		Utils.closeQuietly(out);
		Utils.closeQuietly(inputStream);
	}
	return result;
}
 
Example 5
Source File: PasteBinOccurrenceDownloader.java    From wandora with GNU General Public License v3.0 6 votes vote down vote up
public static String getUrl(URL url) throws IOException {
    StringBuilder sb = new StringBuilder(5000);
    if(url != null) {
        URLConnection con = url.openConnection();
        Wandora.initUrlConnection(con);
        con.setUseCaches(false);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
 
        String s;
        while ((s = in.readLine()) != null) {
            sb.append(s);
        }
        in.close();
    }
    return sb.toString();
}
 
Example 6
Source File: FileServiceApp.java    From product-ei with Apache License 2.0 5 votes vote down vote up
private void doPost(String url, String content) throws IOException {
	URL urlObj = new URL(url);
	URLConnection conn = urlObj.openConnection();
	conn.setDoInput(true);
	conn.setDoOutput(true);
	conn.setUseCaches(false);
	conn.setRequestProperty("Content-Type",	"application/x-www-form-urlencoded");
	DataOutputStream out = new DataOutputStream(conn.getOutputStream());
	out.writeBytes(content);
	out.flush();
	out.close();
	conn.getInputStream().close();
}
 
Example 7
Source File: XMLEntityManager.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static OutputStream createOutputStream(String uri) throws IOException {
    // URI was specified. Handle relative URIs.
    final String expanded = XMLEntityManager.expandSystemId(uri, null, true);
    final URL url = new URL(expanded != null ? expanded : uri);
    OutputStream out = null;
    String protocol = url.getProtocol();
    String host = url.getHost();
    // Use FileOutputStream if this URI is for a local file.
    if (protocol.equals("file")
            && (host == null || host.length() == 0 || host.equals("localhost"))) {
        File file = new File(getPathWithoutEscapes(url.getPath()));
        if (!file.exists()) {
            File parent = file.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
        }
        out = new FileOutputStream(file);
    }
    // Try to write to some other kind of URI. Some protocols
    // won't support this, though HTTP should work.
    else {
        URLConnection urlCon = url.openConnection();
        urlCon.setDoInput(false);
        urlCon.setDoOutput(true);
        urlCon.setUseCaches(false); // Enable tunneling.
        if (urlCon instanceof HttpURLConnection) {
            // The DOM L3 REC says if we are writing to an HTTP URI
            // it is to be done with an HTTP PUT.
            HttpURLConnection httpCon = (HttpURLConnection) urlCon;
            httpCon.setRequestMethod("PUT");
        }
        out = urlCon.getOutputStream();
    }
    return out;
}
 
Example 8
Source File: PropertiesReaderControl.java    From es6draft with MIT License 5 votes vote down vote up
private static InputStream getInputStream(ClassLoader loader, String resourceName, boolean reload)
        throws IOException {
    URL url = loader.getResource(resourceName);
    if (url == null) {
        return null;
    }
    URLConnection connection = url.openConnection();
    connection.setUseCaches(!reload);
    return connection.getInputStream();
}
 
Example 9
Source File: GenerateUTR30DataFiles.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static URLConnection openConnection(URL url) throws IOException {
  final URLConnection connection = url.openConnection();
  connection.setUseCaches(false);
  connection.addRequestProperty("Cache-Control", "no-cache");
  connection.connect();
  return connection;
}
 
Example 10
Source File: AbstractMillionFirstStepsExtractor.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
protected String doUrl (URL url) throws IOException {
    StringBuilder sb = new StringBuilder(5000);
    
    if (url != null) {
        URLConnection con = url.openConnection();
        Wandora.initUrlConnection(con);
        con.setDoInput(true);
        con.setUseCaches(false);
        con.setRequestProperty("Content-type", "text/plain");
            
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset.forName(defaultEncoding)));

            String s;
            while ((s = in.readLine()) != null) {
                sb.append(s);
                if(!(s.endsWith("\n") || s.endsWith("\r"))) sb.append("\n");
            }
            in.close();
        } 
        catch (Exception ex) {
            log(ex);
        }
    }
    
    return sb.toString();
}
 
Example 11
Source File: EuropeanaSearchExtractor.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
public String doUrl (URL url) throws IOException {
    StringBuilder sb = new StringBuilder(5000);
    
    if (url != null) {
       
            URLConnection con = url.openConnection();
            Wandora.initUrlConnection(con);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-type", "text/plain");
            
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset.forName(defaultEncoding)));

            String s;
            while ((s = in.readLine()) != null) {
                sb.append(s);
                if(!(s.endsWith("\n") || s.endsWith("\r"))) sb.append("\n");
            }
            in.close();
        } catch (Exception ex) {
            log("Authentication failed. Check API Key.");
        }
    }
    
    return sb.toString();
}
 
Example 12
Source File: TabooLibSettings.java    From TabooLib with MIT License 5 votes vote down vote up
public static InputStream getSettingsInputStream() {
    try {
        URL url = TabooLibServer.class.getClassLoader().getResource("__resources__/settings.properties");
        if (url == null) {
            return null;
        } else {
            URLConnection connection = url.openConnection();
            connection.setUseCaches(false);
            return connection.getInputStream();
        }
    } catch (IOException ignored) {
        return null;
    }
}
 
Example 13
Source File: ExtensionLoader.java    From immutables with Apache License 2.0 5 votes vote down vote up
private static String getClasspathResourceText(URL requestURL) throws IOException {
  URLConnection connection = requestURL.openConnection();
  connection.setUseCaches(false);
  try (Reader r = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)) {
    return CharStreams.toString(r);
  }
}
 
Example 14
Source File: UrlJar.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private NonClosingJarInputStream createJarInputStream() throws IOException {
    JarURLConnection jarConn = (JarURLConnection) url.openConnection();
    URL resourceURL = jarConn.getJarFileURL();
    URLConnection resourceConn = resourceURL.openConnection();
    resourceConn.setUseCaches(false);
    return new NonClosingJarInputStream(resourceConn.getInputStream());
}
 
Example 15
Source File: DefaultEntityResolver.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves the requested external entity. This is the default
 * implementation of the {@code EntityResolver} interface. It checks
 * the passed in public ID against the registered entity IDs and uses a
 * local URL if possible.
 *
 * @param publicId the public identifier of the entity being referenced
 * @param systemId the system identifier of the entity being referenced
 * @return an input source for the specified entity
 * @throws org.xml.sax.SAXException if a parsing exception occurs
 */
@SuppressWarnings("resource") // The stream is managed by the InputSource returned by this method.
@Override
public InputSource resolveEntity(final String publicId, final String systemId)
        throws SAXException
{
    // Has this system identifier been registered?
    URL entityURL = null;
    if (publicId != null)
    {
        entityURL = getRegisteredEntities().get(publicId);
    }

    if (entityURL != null)
    {
        // Obtain an InputSource for this URL. This code is based on the
        // createInputSourceFromURL() method of Commons Digester.
        try
        {
            final URLConnection connection = entityURL.openConnection();
            connection.setUseCaches(false);
            final InputStream stream = connection.getInputStream();
            final InputSource source = new InputSource(stream);
            source.setSystemId(entityURL.toExternalForm());
            return source;
        }
        catch (final IOException e)
        {
            throw new SAXException(e);
        }
    }
    // default processing behavior
    return null;
}
 
Example 16
Source File: UrlJar.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected NonClosingJarInputStream createJarInputStream() throws IOException {
    JarURLConnection jarConn = (JarURLConnection) getJarFileURL().openConnection();
    URL resourceURL = jarConn.getJarFileURL();
    URLConnection resourceConn = resourceURL.openConnection();
    resourceConn.setUseCaches(false);
    return new NonClosingJarInputStream(resourceConn.getInputStream());
}
 
Example 17
Source File: TGShareSongRequest.java    From tuxguitar with GNU Lesser General Public License v2.1 4 votes vote down vote up
public TGShareSongResponse getResponse() throws Throwable {
	URL url = new URL(TGCommunityWeb.getHomeUrl(this.context) + "/rd.php/sharing/tuxguitar/upload.do");
	URLConnection conn = url.openConnection();
	conn.setDoInput(true);
	conn.setDoOutput(true);
	conn.setUseCaches(false);
	conn.setRequestProperty("Connection", "Keep-Alive");
	conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDARY);
	
	DataOutputStream out = new DataOutputStream( conn.getOutputStream() );
	
	// auth
	out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + EOL);
	out.writeBytes("Content-Disposition: form-data; name=\"auth\";" + EOL);
	out.writeBytes(EOL);
	out.writeBytes(this.auth.getAuthCode());
	out.writeBytes(EOL);
	
	// title
	out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + EOL);
	out.writeBytes("Content-Disposition: form-data; name=\"title\";" + EOL);
	out.writeBytes(EOL);
	out.writeBytes(this.file.getTitle());
	out.writeBytes(EOL);
	
	// description
	out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + EOL);
	out.writeBytes("Content-Disposition: form-data; name=\"description\";" + EOL);
	out.writeBytes(EOL);
	out.writeBytes(this.file.getDescription());
	out.writeBytes(EOL);
	
	// tagkeys
	out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + EOL);
	out.writeBytes("Content-Disposition: form-data; name=\"tagkeys\";" + EOL);
	out.writeBytes(EOL);
	out.writeBytes(this.file.getTagkeys());
	out.writeBytes(EOL);
	
	// file
	out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + EOL);
	out.writeBytes("Content-Disposition: form-data; name=\"fileName\";" + " filename=\"" + this.file.getFilename() +"\"" + EOL);
	out.writeBytes(EOL);
	out.write( this.file.getFile() );
	out.writeBytes(EOL);
	
	out.writeBytes(BOUNDARY_SEPARATOR + BOUNDARY + BOUNDARY_SEPARATOR + EOL);
	out.flush();
	out.close();
	
	return new TGShareSongResponse( conn.getInputStream() );
}
 
Example 18
Source File: Resolver.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Query an external RFC2483 resolver.
 *
 * @param resolver The URL of the RFC2483 resolver.
 * @param command The command to send the resolver.
 * @param arg1 The first argument to the resolver.
 * @param arg2 The second argument to the resolver, usually null.
 *
 * @return The Resolver constructed.
 */
protected Resolver queryResolver(String resolver,
                                 String command,
                                 String arg1,
                                 String arg2) {
    InputStream iStream = null;
    String RFC2483 = resolver + "?command=" + command
        + "&format=tr9401&uri=" + arg1
        + "&uri2=" + arg2;
    String line = null;

    try {
        URL url = new URL(RFC2483);

        URLConnection urlCon = url.openConnection();

        urlCon.setUseCaches(false);

        Resolver r = (Resolver) newCatalog();

        String cType = urlCon.getContentType();

        // I don't care about the character set or subtype
        if (cType.indexOf(";") > 0) {
            cType = cType.substring(0, cType.indexOf(";"));
        }

        r.parseCatalog(cType, urlCon.getInputStream());

        return r;
    } catch (CatalogException cex) {
      if (cex.getExceptionType() == CatalogException.UNPARSEABLE) {
        catalogManager.debug.message(1, "Unparseable catalog: " + RFC2483);
      } else if (cex.getExceptionType()
                 == CatalogException.UNKNOWN_FORMAT) {
        catalogManager.debug.message(1, "Unknown catalog format: " + RFC2483);
      }
      return null;
    } catch (MalformedURLException mue) {
        catalogManager.debug.message(1, "Malformed resolver URL: " + RFC2483);
        return null;
    } catch (IOException ie) {
        catalogManager.debug.message(1, "I/O Exception opening resolver: " + RFC2483);
        return null;
    }
}
 
Example 19
Source File: upload-app-s3.java    From samples with MIT License 4 votes vote down vote up
public static void uploadFileToS3(String filePath, String presignedUrl) {
    try {
        URLConnection urlconnection = null;
        File appFile = new File(filePath);
        URL url = new URL(presignedUrl);

        urlconnection = url.openConnection();
        urlconnection.setUseCaches(false);
        urlconnection.setDoOutput(true);
        urlconnection.setDoInput(true);

        if (urlconnection instanceof HttpURLConnection) {
            ((HttpURLConnection) urlconnection).setRequestMethod("PUT");
            ((HttpURLConnection) urlconnection).setRequestProperty("Content-Type", "application/octet-stream");
            ((HttpURLConnection) urlconnection).setRequestProperty("x-amz-tagging", "unsaved=true");
            ((HttpURLConnection) urlconnection).setRequestProperty("Content-Length", getFileSizeBytes(appFile));
            ((HttpURLConnection) urlconnection).connect();
        }

        BufferedOutputStream bos = new BufferedOutputStream(urlconnection.getOutputStream());
        FileInputStream bis = new FileInputStream(appFile);
        System.out.println("Total file size to read (in bytes) : " + bis.available());
        int i;
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
        bos.close();
        bis.close();

        InputStream inputStream;
        int responseCode = ((HttpURLConnection) urlconnection).getResponseCode();
        if ((responseCode >= 200) && (responseCode <= 202)) {
            inputStream = ((HttpURLConnection) urlconnection).getInputStream();
            int j;
            while ((j = inputStream.read()) > 0) {
                System.out.println(j);
            }

        } else {
            inputStream = ((HttpURLConnection) urlconnection).getErrorStream();
        }
        ((HttpURLConnection) urlconnection).disconnect();
        System.out.println("uploadFileToS3: " + ((HttpURLConnection) urlconnection).getResponseMessage());

    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
}
 
Example 20
Source File: ResourceUtils2.java    From super-cloudops with Apache License 2.0 2 votes vote down vote up
/**
 * Set the {@link URLConnection#setUseCaches "useCaches"} flag on the given
 * connection, preferring {@code false} but leaving the flag at {@code true}
 * for JNLP based resources.
 * 
 * @param con
 *            the URLConnection to set the flag on
 */
public static void useCachesIfNecessary(URLConnection con) {
	con.setUseCaches(con.getClass().getSimpleName().startsWith("JNLP"));
}