Example usage for java.net URLConnection setUseCaches

List of usage examples for java.net URLConnection setUseCaches

Introduction

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

Prototype

public void setUseCaches(boolean usecaches) 

Source Link

Document

Sets the value of the useCaches field of this URLConnection to the specified value.

Usage

From source file:com.gmail.tracebachi.DeltaSkins.Shared.MojangApi.java

private HttpURLConnection openNameToIdConnection() throws IOException {
    URL url = new URL(NAMES_TO_IDS_ADDR);
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(CONNECT_TIMEOUT);
    connection.setReadTimeout(READ_TIMEOUT);
    connection.setDoInput(true);//from ww  w .j  av a 2 s . co m
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    return (HttpURLConnection) connection;
}

From source file:com.sabre.hack.travelachievementgame.DSCommHandler.java

@SuppressWarnings("deprecation")
public String sendRequest(String payLoad, String authToken) {
    URLConnection conn = null;
    String strRet = null;/*  w  w w .j  av  a 2 s.  co  m*/
    try {
        URL urlConn = new URL(payLoad);

        conn = null;
        conn = urlConn.openConnection();

        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Accept", "application/json");

        DataInputStream dataIn = new DataInputStream(conn.getInputStream());
        String strChunk = "";
        StringBuilder sb = new StringBuilder("");
        while (null != ((strChunk = dataIn.readLine())))
            sb.append(strChunk);

        strRet = sb.toString();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        System.out.println("MalformedURLException in DSCommHandler");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("IOException in DSCommHandler: " + conn.getHeaderField(0));
        //         e.printStackTrace();
    }
    return strRet;
}

From source file:dk.netarkivet.common.distribute.HTTPRemoteFile.java

/** Get an input stream representing the remote file.
 * If the file resides on the current machine, the input stream is to the
 * local file. Otherwise, the remote file is transferred over http.
 * The close method of the input stream will cleanup this handle, and if
 * checksums are requested, will check the checksums on close.
 * If the file is not set to be able to be transferred multiple times, it is
 * cleaned up after the transfer.//from www  .  j a  v  a 2  s.co m
 * @return An input stream for the remote file.
 * @throws IOFailure on I/O trouble generating inputstream for remote file.
 * Also, the returned remote file will throw IOFailure on close, if
 * checksums are requested, but do not match.
 */
public InputStream getInputStream() {
    if (filesize == 0) {
        return new ByteArrayInputStream(new byte[] {});
    }
    try {
        InputStream is = null;
        if (isLocal()) {
            is = new FileInputStream(file);
        } else {
            URLConnection urlConnection = getRegistry().openConnection(url);
            //ensure not getting some cached version
            urlConnection.setUseCaches(false);
            is = urlConnection.getInputStream();
        }
        if (useChecksums) {
            is = new DigestInputStream(is, ChecksumCalculator.getMessageDigest(ChecksumCalculator.MD5));
        }
        return new FilterInputStream(is) {
            public void close() {
                if (useChecksums) {
                    String newChecksum = ChecksumCalculator
                            .toHex(((DigestInputStream) in).getMessageDigest().digest());
                    if (!newChecksum.equals(checksum)) {
                        throw new IOFailure(
                                "Checksum mismatch! Expected '" + checksum + "' but was '" + newChecksum + "'");
                    }
                }
                if (!multipleDownloads) {
                    cleanup();
                }
            }
        };
    } catch (IOException e) {
        throw new IOFailure("Unable to get inputstream for '" + file + "' from '" + url + "'", e);
    }
}

From source file:org.apache.ojb.broker.metadata.RepositoryPersistor.java

/**
 *
 * TODO: We should re-design the configuration file reading
 *//* www .  j a  v a  2 s .c o  m*/
private Object buildRepository(String repositoryFileName, Class targetRepository)
        throws MalformedURLException, ParserConfigurationException, SAXException, IOException {
    URL url = buildURL(repositoryFileName);
    /*
    arminw:
    strange, when using 'url.openStream()' argument repository
    could not be parsed
    ipriha:
    parser needs a base url to find referenced entities.
    */
    // InputSource source = new InputSource(url.openStream());

    String pathName = url.toExternalForm();

    log.info("Building repository from :" + pathName);
    InputSource source = new InputSource(pathName);
    URLConnection conn = url.openConnection();
    conn.setUseCaches(false);
    conn.connect();
    InputStream in = conn.getInputStream();
    source.setByteStream(in);
    try {
        return readMetadataFromXML(source, targetRepository);
    } finally {
        try {
            in.close();
        } catch (IOException x) {
            log.warn("unable to close repository input stream [" + x.getMessage() + "]", x);
        }
    }
}

From source file:com.concentricsky.android.khanacademy.util.CaptionManager.java

/**
 * Get a {@link WebResourceResponse} with subtitles for the video with the given youtube id.
 * //from   w w  w.  jav a2  s  .c om
 * The response contains a UTF-8 encoded json object with the subtitles received 
 * from universalsubtitles.org. 
 * 
 * @param youtubeId The youtube id of the video whose subtitles we need.
 * @return The {@link WebResourceResponse} with the subtitles, or {@code null} in case of error or if none are found.
 */
public WebResourceResponse fetchRawCaptionResponse(String youtubeId) {
    Log.d(LOG_TAG, "fetchRawCaptionResponse");
    String youtube_url = "http://www.youtube.com/watch?v=" + youtubeId;
    try {
        URL url = new URL(String.format(subtitleFormat, youtube_url, "en"));
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(CONNECT_TIMEOUT);
        connection.setUseCaches(true);
        InputStream in = null;
        try {
            in = connection.getInputStream();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            //various exceptions including at least ConnectException and UnknownHostException can happen if we're offline
        }

        return in == null ? null : new WebResourceResponse("application/json", "UTF-8", in);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:net.dmulloy2.ultimatearena.api.ArenaType.java

/**
 * Gets an embedded resource in this arena type's jar file.
 *
 * @param fileName Name of the resource/*from   www .j a va 2 s .  c o  m*/
 * @return File, or null if it cannot be found
 */
protected final InputStream getResource(String fileName) {
    try {
        URL url = getClassLoader().getResource(fileName);
        if (url == null)
            return null;

        URLConnection connection = url.openConnection();
        connection.setUseCaches(false);
        return connection.getInputStream();
    } catch (Throwable ex) {
    }
    return null;
}

From source file:org.wso2.es.integration.common.utils.AssetsRESTClient.java

/**
 * This methods make a call to ES-Publisher REST API and obtain a valid sessionID
 *
 * @return SessionId for the authenticated user
 *//*from   ww w. jav  a2s .  co m*/
private String login() throws IOException {
    String sessionID = null;
    Reader input = null;
    BufferedWriter writer = null;
    String authenticationEndpoint = getBaseUrl() + PUBLISHER_APIS_AUTHENTICATE_ENDPOINT;
    //construct full authenticate endpoint
    try {
        //authenticate endpoint URL
        URL endpointUrl = new URL(authenticationEndpoint);
        URLConnection urlConn = endpointUrl.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        // Specify the content type.
        urlConn.setRequestProperty(CONTENT_TYPE_HEADER, CONTENT_TYPE);
        // Send POST output.
        writer = new BufferedWriter(new OutputStreamWriter(urlConn.getOutputStream()));
        String content = USERNAME + "=" + URLEncoder.encode(USERNAME_VAL, UTF_8) + "&" + PASSWORD + "="
                + URLEncoder.encode(PASSWORD_VAl, UTF_8);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Send Login Information : " + content);
        }
        writer.write(content);
        writer.flush();

        // Get response data.
        input = new InputStreamReader(urlConn.getInputStream());
        JsonElement elem = parser.parse(input);
        sessionID = elem.getAsJsonObject().getAsJsonObject(AUTH_RESPONSE_WRAP_KEY).get(SESSIONID).toString();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Received SessionID : " + sessionID);
        }

    } catch (MalformedURLException e) {
        LOG.error(getLoginErrorMassage(authenticationEndpoint), e);
        throw e;
    } catch (IOException e) {
        LOG.error(getLoginErrorMassage(authenticationEndpoint), e);
        throw e;
    } finally {
        if (input != null) {
            try {
                input.close();// will close the URL connection as well
            } catch (IOException e) {
                LOG.error("Failed to close input stream ", e);
            }
        }
        if (writer != null) {
            try {
                writer.close();// will close the URL connection as well
            } catch (IOException e) {
                LOG.error("Failed to close output stream ", e);
            }
        }
    }
    return sessionID;
}

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

private InputStream grabStream() throws IOException {
    URLConnection con = openURLConnection(this.url);
    con.setUseCaches(false);

    if (con instanceof HttpURLConnection) {
        if ("enabled".equalsIgnoreCase(basicAuthentication)) {
            String userpassword = username + ":" + password;
            byte[] authEncBytes = Base64.encodeBase64(userpassword.getBytes(IoUtils.UTF8_CHARSET));

            ((HttpURLConnection) con).setRequestProperty("Authorization",
                    "Basic " + new String(authEncBytes, IoUtils.UTF8_CHARSET));
        }//from  w w  w .  j  a va 2 s . c o m

    }

    return con.getInputStream();
}

From source file:org.jab.docsearch.utils.NetUtils.java

/**
 * Gets URL size (content)//from  ww  w  .j a v  a  2 s .  co m
 *
 * @param url  URL for connect
 * @return     size in bytes of a url or 0 if broken or timed out connection
 */
public long getURLSize(final String url) {
    try {
        URL tmpURL = new URL(url);
        URLConnection conn = tmpURL.openConnection();

        // set connection parameter
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("User-Agent", USER_AGENT);

        // connect
        conn.connect();

        long contentLength = conn.getContentLength();

        if (logger.isDebugEnabled()) {
            logger.debug("getURLSize() content lentgh=" + contentLength + " of URL='" + url + "'");
        }

        return contentLength;
    } catch (IOException ioe) {
        logger.error("getURLSize() failed for URL='" + url + "'", ioe);
        return 0;
    }
}

From source file:org.jab.docsearch.utils.NetUtils.java

/**
 * Gets URL modified date as long/*from  w  w  w .  ja  v a 2s.  co  m*/
 *
 * @param url  URL to connect
 * @return         date of URLs modification or 0 if an error occurs
 */
public long getURLModifiedDate(final String url) {
    try {
        URL tmpURL = new URL(url);
        URLConnection conn = tmpURL.openConnection();

        // set connection parameter
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("User-Agent", USER_AGENT);

        // connect
        conn.connect();

        long modifiedDate = conn.getLastModified();

        if (logger.isDebugEnabled()) {
            logger.debug("getURLModifiedDate() modified date=" + modifiedDate + " of URL='" + url + "'");
        }

        return modifiedDate;
    } catch (IOException ioe) {
        logger.error("getURLModifiedDate() failed for URL='" + url + "'", ioe);
        return 0;
    }
}