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:edu.stanford.muse.slant.CustomSearchHelper.java

/** returns an oauth token for the user's CSE. returns null if login failed. */
public static String authenticate(String login, String password) {
    //System.out.println("About to post\nURL: "+target+ "content: " + content);
    String authToken = null;// w  w  w .j  av  a2  s  .co m
    String response = "";
    try {
        URL url = new URL("https://www.google.com/accounts/ClientLogin");
        URLConnection conn = url.openConnection();
        // Set connection parameters.
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        // Make server believe we are form data...

        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        // TODO: escape password, we'll fail if password has &
        // login = "musetestlogin1";
        // password = "whowonthelottery";
        String content = "accountType=HOSTED_OR_GOOGLE&Email=" + login + "&Passwd=" + password
                + "&service=cprose&source=muse.chrome.extension";
        out.writeBytes(content);
        out.flush();
        out.close();

        // Read response from the input stream.
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String temp;
        while ((temp = in.readLine()) != null) {
            response += temp + "\n";
        }
        temp = null;
        in.close();
        log.info("Obtaining auth token: Server response:\n'" + response + "'");

        String delimiter = "Auth=";
        /* given string will be split by the argument delimiter provided. */
        String[] token = response.split(delimiter);
        authToken = token[1];
        authToken = authToken.trim();
        authToken = authToken.replaceAll("(\\r|\\n)", "");
        log.info("auth token: " + authToken);
        return authToken;
    } catch (Exception e) {
        log.warn("Unable to authorize: " + e.getMessage());
        return null;
    }
}

From source file:com.sun.faces.generate.RenderKitSpecificationGenerator.java

public static void appendResourceToStringBuffer(String resourceName, StringBuffer sb) throws Exception {
    InputStreamReader isr = null;
    URL url = null;/*w  w w .  ja  v  a2  s . co m*/
    URLConnection conn = null;
    char[] chars = new char[1024];
    int len = 0;

    url = getCurrentLoader(sb).getResource(resourceName);
    conn = url.openConnection();
    conn.setUseCaches(false);
    isr = new InputStreamReader(conn.getInputStream());
    while (-1 != (len = isr.read(chars, 0, 1024))) {
        sb.append(chars, 0, len);
    }
    isr.close();
}

From source file:org.java.plugin.standard.ShadingPathResolver.java

static Date getLastModified(final URL url) throws IOException {
    long result = 0;
    if ("jar".equalsIgnoreCase(url.getProtocol())) { //$NON-NLS-1$
        String urlStr = url.toExternalForm();
        int p = urlStr.indexOf("!/"); //$NON-NLS-1$
        if (p != -1) {
            //sourceFile = IoUtil.url2file(new URL(urlStr.substring(4, p)));
            return getLastModified(new URL(urlStr.substring(4, p)));
        }//from  ww w. ja va 2 s . c  o m
    }
    File sourceFile = IoUtil.url2file(url);
    if (sourceFile != null) {
        result = sourceFile.lastModified();
    } else {
        URLConnection cnn = url.openConnection();
        try {
            cnn.setUseCaches(false);
            cnn.setDoInput(false); // this should force using HTTP HEAD method
            result = cnn.getLastModified();
        } finally {
            try {
                cnn.getInputStream().close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    }
    if (result == 0) {
        throw new IOException("can't retrieve modification date for resource " //$NON-NLS-1$
                + url);
    }
    // for some reason modification milliseconds for some files are unstable
    Calendar cldr = Calendar.getInstance(Locale.ENGLISH);
    cldr.setTime(new Date(result));
    cldr.set(Calendar.MILLISECOND, 0);
    return cldr.getTime();
}

From source file:com.sun.faces.generate.RenderKitSpecificationGenerator.java

public static void copyResourceToFile(String resourceName, File file) throws Exception {
    FileOutputStream fos = null;//from  w  ww  .ja v  a 2s . com
    BufferedInputStream bis = null;
    URL url = null;
    URLConnection conn = null;
    byte[] bytes = new byte[1024];
    int len = 0;

    fos = new FileOutputStream(file);
    url = getCurrentLoader(fos).getResource(resourceName);
    conn = url.openConnection();
    conn.setUseCaches(false);
    bis = new BufferedInputStream(conn.getInputStream());
    while (-1 != (len = bis.read(bytes, 0, 1024))) {
        fos.write(bytes, 0, len);
    }
    fos.close();
    bis.close();

}

From source file:mashapeautoloader.MashapeAutoloader.java

/**
 * @param libraryName/* w w  w . jav a2 s.c  o m*/
 *
 * Returns false if something wrong, otherwise true (API interface
 * already exists or just well downloaded)
 */
private static boolean downloadLib(String libraryName) {
    URL url;
    URLConnection urlConn;

    // check (or make) for apiStore directory
    File apiStoreDir = new File(apiStore);
    if (!apiStoreDir.isDirectory())
        apiStoreDir.mkdir();

    String javaFilePath = apiStore + libraryName + ".java";
    File javaFile = new File(javaFilePath);

    // check if the API interface exists
    if (javaFile.exists())
        return true;
    try {
        // download the API interface's archive
        url = new URL(MASHAPE_DOWNLOAD_ROOT + libraryName);
        urlConn = url.openConnection();

        HttpURLConnection httpConn = (HttpURLConnection) urlConn;
        httpConn.setInstanceFollowRedirects(false);

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

        // extract the archive stream
        ZipInputStream zip = new ZipInputStream(urlConn.getInputStream());
        String expectedEntryName = libraryName + ".java";
        while (true) {
            ZipEntry nextEntry = zip.getNextEntry();
            if (nextEntry == null)
                return false;

            String name = nextEntry.getName();
            if (name.equals(expectedEntryName)) {
                // save .java locally
                FileOutputStream javaFileStream = new FileOutputStream(javaFilePath);
                byte[] buf = new byte[1024];
                int n;
                while ((n = zip.read(buf, 0, 1024)) > -1)
                    javaFileStream.write(buf, 0, n);

                // compile it into .class file
                JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
                int result = compiler.run(null, null, null, javaFilePath);
                System.out.println(result);
                return result == 0;
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

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);
    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);
    connection.setDefaultUseCaches(false);
    connection.addRequestProperty(url, url);
    String content = IOUtils.toString(connection.getInputStream(), connection.getContentEncoding());
    return new JSONObject(content);
}

From source file:org.carrot2.util.attribute.metadata.ClassRelativeResourceLoader.java

/**
 * /*  w w  w  .  java 2s.  c om*/
 */
@Override
public InputStream getResourceStream(String name) throws ResourceNotFoundException {
    /*
     * Do some protocol connection magic because JAR URLs are cached and this complicates
     * development (the template is not found once loaded).
     */
    URL resource = clazz.getResource(name);
    if (resource == null)
        throw new ResourceNotFoundException("Resource not found: " + name);

    try {
        URLConnection connection = resource.openConnection();
        connection.setUseCaches(false);
        return connection.getInputStream();
    } catch (Exception e) {
        throw new ResourceNotFoundException(e);
    }
}

From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java

/**
 * Connects to the  server, authenticates the provided username and
 * password.//w ww. ja v  a2  s  . c  o  m
 * 
 * @param username The user's username
 * @param password The user's password
 * @return String The authentication token returned by the server (or null)
 */
public static String authenticate(String username, String accessKey, String base_url) {
    String token = null;
    String hash = null;
    authenticate_log_text = "authenticate()\n";
    AUTH_URI = base_url + "/webservice.php";
    authenticate_log_text = authenticate_log_text + "url: " + AUTH_URI + "?operation=getchallenge&username="
            + username + "\n";

    Log.d(TAG, "AUTH_URI : ");
    Log.d(TAG, AUTH_URI + "?operation=getchallenge&username=" + username);
    // =========== get challenge token ==============================
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    try {

        URL url;

        // HTTP GET REQUEST
        url = new URL(AUTH_URI + "?operation=getchallenge&username=" + username);
        HttpURLConnection con;
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-length", "0");
        con.setUseCaches(false);
        // for some site that redirects based on user agent
        con.setInstanceFollowRedirects(true);
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.15) Gecko/2009101600 Firefox/3.0.15");
        con.setAllowUserInteraction(false);
        int timeout = 20000;
        con.setConnectTimeout(timeout);
        con.setReadTimeout(timeout);
        con.connect();
        int status = con.getResponseCode();

        authenticate_log_text = authenticate_log_text + "Request status = " + status + "\n";
        switch (status) {
        case 200:
        case 201:
        case 302:
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            Log.d(TAG, "message body");
            Log.d(TAG, sb.toString());

            authenticate_log_text = authenticate_log_text + "body : " + sb.toString();
            if (status == 302) {
                authenticate_log_text = sb.toString();
                return null;
            }

            JSONObject result = new JSONObject(sb.toString());
            Log.d(TAG, result.getString("result"));
            JSONObject data = new JSONObject(result.getString("result"));
            token = data.getString("token");
            break;
        case 401:
            Log.e(TAG, "Server auth error: ");// + readResponse(con.getErrorStream()));
            authenticate_log_text = authenticate_log_text + "Server auth error";
            return null;
        default:
            Log.e(TAG, "connection status code " + status);// + readResponse(con.getErrorStream()));
            authenticate_log_text = authenticate_log_text + "connection status code :" + status;
            return null;
        }

    } catch (ClientProtocolException e) {
        Log.i(TAG, "getchallenge:http protocol error");
        Log.e(TAG, e.getMessage());
        authenticate_log_text = authenticate_log_text + "ClientProtocolException :" + e.getMessage() + "\n";
        return null;
    } catch (IOException e) {
        Log.e(TAG, "getchallenge: IO Exception");
        Log.e(TAG, e.getMessage());
        Log.e(TAG, AUTH_URI + "?operation=getchallenge&username=" + username);
        authenticate_log_text = authenticate_log_text + "getchallenge: IO Exception : " + e.getMessage() + "\n";
        return null;

    } catch (JSONException e) {
        Log.i(TAG, "json exception");
        authenticate_log_text = authenticate_log_text + "JSon exception\n";

        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

    // ================= login ==================

    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(token.getBytes());
        m.update(accessKey.getBytes());
        hash = new BigInteger(1, m.digest()).toString(16);
        Log.i(TAG, "hash");
        Log.i(TAG, hash);
    } catch (NoSuchAlgorithmException e) {
        authenticate_log_text = authenticate_log_text + "MD5 => no such algorithm\n";
        e.printStackTrace();
    }

    try {
        String charset;
        charset = "utf-8";
        String query = String.format("operation=login&username=%s&accessKey=%s",
                URLEncoder.encode(username, charset), URLEncoder.encode(hash, charset));
        authenticate_log_text = authenticate_log_text + "login()\n";
        URLConnection connection = new URL(AUTH_URI).openConnection();
        connection.setDoOutput(true); // Triggers POST.
        int timeout = 20000;
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        connection.setAllowUserInteraction(false);
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
        connection.setUseCaches(false);

        OutputStream output = connection.getOutputStream();
        try {
            output.write(query.getBytes(charset));
        } finally {
            try {
                output.close();
            } catch (IOException logOrIgnore) {

            }
        }
        Log.d(TAG, "Query written");
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        Log.d(TAG, "message post body");
        Log.d(TAG, sb.toString());
        authenticate_log_text = authenticate_log_text + "post message body :" + sb.toString() + "\n";
        JSONObject result = new JSONObject(sb.toString());

        String success = result.getString("success");
        Log.i(TAG, success);

        if (success == "true") {
            Log.i(TAG, result.getString("result"));
            Log.i(TAG, "sucesssfully logged  in is");
            JSONObject data = new JSONObject(result.getString("result"));
            sessionName = data.getString("sessionName");

            Log.i(TAG, sessionName);
            authenticate_log_text = authenticate_log_text + "successfully logged in\n";
            return token;
        } else {
            // success is false, retrieve error
            JSONObject data = new JSONObject(result.getString("error"));
            authenticate_log_text = "can not login :\n" + data.toString();

            return null;
        }
        //token = data.getString("token");
        //Log.i(TAG,token);
    } catch (ClientProtocolException e) {
        Log.d(TAG, "login: http protocol error");
        Log.d(TAG, e.getMessage());
        authenticate_log_text = authenticate_log_text + "HTTP Protocol error \n";
        authenticate_log_text = authenticate_log_text + e.getMessage() + "\n";
    } catch (IOException e) {
        Log.d(TAG, "login: IO Exception");
        Log.d(TAG, e.getMessage());

        authenticate_log_text = authenticate_log_text + "login: IO Exception \n";
        authenticate_log_text = authenticate_log_text + e.getMessage() + "\n";

    } catch (JSONException e) {
        Log.d(TAG, "JSON exception");
        // TODO Auto-generated catch block
        authenticate_log_text = authenticate_log_text + "JSON exception ";
        authenticate_log_text = authenticate_log_text + e.getMessage();
        e.printStackTrace();
    }
    return null;
    // ========================================================================

}

From source file:XMLResourceBundleControl.java

  public ResourceBundle newBundle(String baseName, Locale locale, String format,
    ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException,
    IOException {// w ww. ja  v  a  2 s  .  c  o  m

  if ((baseName == null) || (locale == null) || (format == null) || (loader == null)) {
    throw new NullPointerException();
  }
  ResourceBundle bundle = null;
  if (!format.equals(XML)) {
    return null;
  }

  String bundleName = toBundleName(baseName, locale);
  String resourceName = toResourceName(bundleName, format);
  URL url = loader.getResource(resourceName);
  if (url == null) {
    return null;
  }
  URLConnection connection = url.openConnection();
  if (connection == null) {
    return null;
  }
  if (reload) {
    connection.setUseCaches(false);
  }
  InputStream stream = connection.getInputStream();
  if (stream == null) {
    return null;
  }
  BufferedInputStream bis = new BufferedInputStream(stream);
  bundle = new XMLResourceBundle(bis);
  bis.close();

  return bundle;
}