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:org.openqa.selenium.server.ProxyHandler.java

private void adjustRequestForProxyInjection(HttpRequest request, URLConnection connection) {
    request.setState(HttpMessage.__MSG_EDITABLE);
    if (request.containsField("If-Modified-Since")) {
        // TODO: still need to disable caching?  I want to prevent 304s during this development phase where 
        // I'm often changing the injection, and so need HTML caching to be absolutely defeated 
        request.removeField("If-Modified-Since");
        request.removeField("If-None-Match");
        connection.setUseCaches(false); // maybe I don't need the stuff above?
    }//ww  w  .  j  a  v a2 s  .  com
    request.removeField("Accept-Encoding"); // js injection is hard w/ gzip'd data, so try to prevent it ahead of time
    request.setState(HttpMessage.__MSG_RECEIVED);
}

From source file:savant.view.swing.Savant.java

private static void logUsageStats() {
    try {/*  w w w .j  a  va 2 s. co m*/
        URLConnection urlConn;
        DataOutputStream printout;
        // URL of CGI-Bin script.
        // URL connection channel.
        urlConn = BrowserSettings.LOG_USAGE_STATS_URL.openConnection();
        // Let the run-time system (RTS) know that we want input.
        urlConn.setDoInput(true);
        // Let the RTS know that we want to do output.
        urlConn.setDoOutput(true);
        // No caching, we want the real thing.
        urlConn.setUseCaches(false);
        // Specify the content type.
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // Send POST output.
        printout = new DataOutputStream(urlConn.getOutputStream());

        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        Locale locale = Locale.getDefault();

        String content = post("time", dateFormat.format(date)) + "&"
                + post("language", locale.getDisplayLanguage()) + "&"
                + post("user.timezone", System.getProperty("user.timezone")) + "&"
                + post("savant.version", BrowserSettings.VERSION) + "&"
                + post("savant.build", BrowserSettings.BUILD)
                //+ "&" + post("address", InetAddress.getLocalHost().getHostAddress())
                + "&" + post("java.version", System.getProperty("java.version")) + "&"
                + post("java.vendor", System.getProperty("java.vendor")) + "&"
                + post("os.name", System.getProperty("os.name")) + "&"
                + post("os.arch", System.getProperty("os.arch")) + "&"
                + post("os.version", System.getProperty("os.version")) + "&"
                + post("user.region", System.getProperty("user.region"));

        printout.writeBytes(content);
        printout.flush();
        printout.close();
        urlConn.getInputStream();
    } catch (Exception ex) {
        //LOG.error("Error logging usage stats.", ex);
    }
}

From source file:net.sf.taverna.t2.workbench.ui.impl.UserRegistrationForm.java

/**
 * Post registration data to our server.
 *//* w  w  w.j a  v a 2s.  c  om*/
private boolean postUserRegistrationDataToServer(UserRegistrationData regData) {
    StringBuilder parameters = new StringBuilder();

    /*
     * The 'submit' parameter - to let the server-side script know we are
     * submitting the user's registration form - all other requests will be
     * silently ignored
     */
    try {
        // value does not matter
        enc(parameters, TAVERNA_REGISTRATION_POST_PARAMETER_NAME, "submit");

        enc(parameters, TAVERNA_VERSION_POST_PARAMETER_NAME, regData.getTavernaVersion());
        enc(parameters, FIRST_NAME_POST_PARAMETER_NAME, regData.getFirstName());
        enc(parameters, LAST_NAME_POST_PARAMETER_NAME, regData.getLastName());
        enc(parameters, EMAIL_ADDRESS_POST_PARAMETER_NAME, regData.getEmailAddress());
        enc(parameters, KEEP_ME_INFORMED_POST_PARAMETER_PROPERTY_NAME, regData.getKeepMeInformed());
        enc(parameters, INSTITUTION_OR_COMPANY_POST_PARAMETER_NAME, regData.getInstitutionOrCompanyName());
        enc(parameters, INDUSTRY_TYPE_POST_PARAMETER_NAME, regData.getIndustry());
        enc(parameters, FIELD_POST_PARAMETER_NAME, regData.getField());
        enc(parameters, PURPOSE_POST_PARAMETER_NAME, regData.getPurposeOfUsingTaverna());
    } catch (UnsupportedEncodingException ueex) {
        logger.error(FAILED + "Could not url encode post parameters", ueex);
        showMessageDialog(null, REGISTRATION_FAILED_MSG, "Error encoding registration data", ERROR_MESSAGE);
        return false;
    }
    String server = REGISTRATION_URL;
    logger.info("Posting user registartion to " + server + " with parameters: " + parameters);
    String response = "";
    String failure;
    try {
        URL url = new URL(server);
        URLConnection conn = url.openConnection();
        /*
         * Set timeout to e.g. 7 seconds, otherwise we might hang too long
         * if server is not responding and it will block Taverna
         */
        conn.setConnectTimeout(7000);
        // Set connection parameters
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        // Make server believe we are HTML form data...
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // Write out the bytes of the content string to the stream.
        try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
            out.writeBytes(parameters.toString());
            out.flush();
        }
        // Read response from the input stream.
        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String temp;
            while ((temp = in.readLine()) != null)
                response += temp + "\n";
            // Remove the last \n character
            if (!response.isEmpty())
                response = response.substring(0, response.length() - 1);
        }
        if (response.equals("Registration successful!"))
            return true;
        logger.error(FAILED + "Response form server was: " + response);
        failure = "Error saving registration data on the server";
    } catch (ConnectException ceex) {
        /*
         * the connection was refused remotely (e.g. no process is listening
         * on the remote address/port).
         */
        logger.error(FAILED + "Registration server is not listening of the specified url.", ceex);
        failure = "Registration server is not listening at the specified url";
    } catch (SocketTimeoutException stex) {
        // timeout has occurred on a socket read or accept.
        logger.error(FAILED + "Socket timeout occurred.", stex);
        failure = "Registration server timeout";
    } catch (MalformedURLException muex) {
        logger.error(FAILED + "Registartion server's url is malformed.", muex);
        failure = "Error with registration server's url";
    } catch (IOException ioex) {
        logger.error(
                FAILED + "Failed to open url connection to registration server or writing/reading to/from it.",
                ioex);
        failure = "Error opening connection to the registration server";
    }
    showMessageDialog(null, REGISTRATION_FAILED_MSG, failure, ERROR_MESSAGE);
    return false;
}

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

URL shadowResource(final URL source, final String uid, final boolean unpack) {
    try {/*from   www . j a  v a2  s . com*/
        URL result = deepCheck(source, uid);
        if (result != null) {
            if (log.isDebugEnabled()) {
                log.debug("got actual shaded resource, UID=" + uid //$NON-NLS-1$
                        + ", source=" + source //$NON-NLS-1$
                        + ", file=" + result); //$NON-NLS-1$
            }
            return result;
        }
    } catch (Exception e) {
        log.warn("deep check failed, UID=" + uid //$NON-NLS-1$
                + ", URL=" + source, e); //$NON-NLS-1$
        remove(uid);
    }
    Date lastModified;
    try {
        lastModified = ShadingUtil.getLastModified(source);
    } catch (IOException ioe) {
        log.error("shading failed, can't get modification date for " //$NON-NLS-1$
                + source, ioe);
        return source;
    }
    File file = IoUtil.url2file(source);
    if ((file != null) && file.isDirectory()) {
        // copy local folder to the shadow directory
        try {
            File rootFolder = new File(shadowFolder, uid);
            IoUtil.copyFolder(file, rootFolder, true, true, fileFilter);
            return add(uid, source, rootFolder, lastModified);
        } catch (IOException ioe) {
            log.error("failed shading local folder " + file, ioe); //$NON-NLS-1$
            return source;
        }
    }
    try {
        if ("jar".equalsIgnoreCase(source.getProtocol())) { //$NON-NLS-1$
            String urlStr = source.toExternalForm();
            int p = urlStr.indexOf("!/"); //$NON-NLS-1$
            if (p == -1) {
                p = urlStr.length();
            }
            URL jarFileURL = new URL(urlStr.substring(4, p));
            if (!unpack) {
                String ext = ShadingUtil.getExtension(jarFileURL.getFile());
                if (ext == null) {
                    ext = "jar"; //$NON-NLS-1$
                }
                File shadowFile = new File(shadowFolder, uid + '.' + ext);
                File sourceFile = IoUtil.url2file(jarFileURL);
                InputStream in;
                if (sourceFile != null) {
                    in = new BufferedInputStream(new FileInputStream(sourceFile));
                } else {
                    in = jarFileURL.openStream();
                }
                try {
                    OutputStream out = new FileOutputStream(shadowFile, false);
                    try {
                        IoUtil.copyStream(in, out, 1024);
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
                return add(uid, source, shadowFile, lastModified);
            }
            URLConnection cnn = null;
            try {
                File sourceFile = IoUtil.url2file(jarFileURL);
                ZipFile zipFile;
                if (sourceFile != null) {
                    zipFile = new ZipFile(sourceFile);
                } else {
                    cnn = source.openConnection();
                    cnn.setUseCaches(false);
                    zipFile = ((JarURLConnection) cnn).getJarFile();
                }
                File rootFolder = new File(shadowFolder, uid);
                try {
                    ShadingUtil.unpack(zipFile, rootFolder);
                } finally {
                    zipFile.close();
                }
                return add(uid, source, rootFolder, lastModified);
            } finally {
                if (cnn != null) {
                    cnn.getInputStream().close();
                }
            }
        }
    } catch (IOException ioe) {
        log.error("failed shading URL connection " + source, ioe); //$NON-NLS-1$
        return source;
    }
    String fileName = source.getFile();
    if (fileName == null) {
        log.warn("can't get file name from resource " + source //$NON-NLS-1$
                + ", shading failed"); //$NON-NLS-1$
        return source;
    }
    String ext = ShadingUtil.getExtension(fileName);
    if (ext == null) {
        log.warn("can't get file name extension for resource " + source //$NON-NLS-1$
                + ", shading failed"); //$NON-NLS-1$
        return source;
    }
    if (unpack && ("jar".equalsIgnoreCase(ext) //$NON-NLS-1$
            || "zip".equalsIgnoreCase(ext))) { //$NON-NLS-1$
        try {
            InputStream strm = source.openStream();
            File rootFolder = new File(shadowFolder, uid);
            try {
                ShadingUtil.unpack(strm, rootFolder);
            } finally {
                strm.close();
            }
            return add(uid, source, rootFolder, lastModified);
        } catch (IOException ioe) {
            log.error("failed shading packed resource " + source, ioe); //$NON-NLS-1$
            return source;
        }
    }
    try {
        File shadowFile = new File(shadowFolder, uid + '.' + ext);
        InputStream in = source.openStream();
        try {
            OutputStream out = new FileOutputStream(shadowFile, false);
            try {
                IoUtil.copyStream(in, out, 1024);
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
        return add(uid, source, shadowFile, lastModified);
    } catch (IOException ioe) {
        log.error("failed shading resource file " + source, ioe); //$NON-NLS-1$
        return source;
    }
}

From source file:org.jab.docsearch.spider.LinkFinder.java

/**
 * Get all links from page/*  ww w  . ja va2 s.c  om*/
 */
public void getAllLinks() {
    // writes links from a page out to a file
    String urlStr = pageName;
    String shortUrl = "";
    numUnChanged = 0;
    numSkips = 0;
    int numSuccesses = 0;
    int numFailed = 0;
    int numNoRobots = 0;
    addLink(urlStr);
    domainUrl = Utils.getDomainURL(urlStr);
    if (logger.isDebugEnabled()) {
        logger.debug("getAllLinks() domain url='" + domainUrl + "'");
    }
    SpiderUrl curl = new SpiderUrl(urlStr);
    baseUrlFolder = Utils.getBaseURLFolder(urlStr);
    int curLinkNo = 0;
    boolean completedSpider = false;
    boolean isDead = false;
    int curPread = 0;
    if (ds != null) {
        ds.setIsWorking(true);
        ds.setProgressMax(maxLinksToFind);
        ds.setCurProgressMSG("Spidering Files...");
    }
    int numSpidered = 0;
    int curSuccessNo = 0;

    // start spider
    while (curLinkNo != -1) {
        BufferedInputStream urlStream = null;
        FileOutputStream fileOutStream = null;

        try {
            completedSpider = false;
            isDead = false;
            if (ds != null) {
                ds.setCurProgress(curPread);
                if (!ds.getIsWorking()) {
                    break;
                }
            }
            curLinkNo = getNextUrlNo();
            if (curLinkNo == -1) {
                logger.debug("getAllLinks() end of links reached.");
                break;
            } else {
                urlStr = getLinkNameByNo(curLinkNo);
                logger.info("getAllLinks() analyzing page='" + urlStr + "'");
                curl = getSpiderUrl(curLinkNo);
            }

            shortUrl = Utils.concatEnd(urlStr, 33);
            setStatus(I18n.getString("connecting_to") + " " + shortUrl);

            // open url
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("User-Agent", "DocSearcher " + I18n.getString("ds.version"));
            conn.connect();
            urlStream = new BufferedInputStream(conn.getInputStream());

            // filesize
            int fileSize = conn.getContentLength();
            if (fileSize > maxFileSizeToGet) {
                String ex = I18n.getString("skipping_file_too_big") + " (" + fileSize + " > " + maxFileSizeToGet
                        + ") " + shortUrl;
                setStatus(ex);
                throw new Exception(ex);
            }

            setStatus(I18n.getString("downloading_uc") + "... " + shortUrl + " " + fileSize + " "
                    + I18n.getString("bytes"));
            curl.setSize(fileSize);

            // last modified
            long curModified = conn.getLastModified(); // was .getDate();
            curl.setLastModified(curModified);

            // content type
            String curContentType = netUtils.getContentType(conn);
            curl.setContentType(curContentType);

            // build the value for downloadFile
            String dnldTmpName = getDownloadFileName(curl.getContentType(), urlStr.toLowerCase());
            String downloadFile = FileUtils.addFolder(downloadFileDir, dnldTmpName);

            // TODO it is better to use content type!
            boolean curIsWebPage = isHtml(urlStr.toLowerCase())
                    || (curContentType.toLowerCase().indexOf("html") != -1);

            logger.debug("getAllLinks() saving to " + downloadFile);
            fileOutStream = new FileOutputStream(downloadFile);
            int curSize = 0;
            int curI;
            int lastPercent = 0;
            StringBuilder tag = new StringBuilder();
            String link = null;
            boolean inTag = false;
            boolean getFileSizeFromStream = false;
            if (fileSize == -1) {
                getFileSizeFromStream = true;
            }

            while ((curI = urlStream.read()) != -1) {
                fileOutStream.write(curI);

                curSize++;
                if (ds != null) {
                    if (!ds.getIsWorking()) {
                        break;
                    }
                }

                // fix problem if filesize not in content length
                if (getFileSizeFromStream) {
                    fileSize = curSize + urlStream.available();
                }

                // notify of download progress
                if (curSize > 0 && (curSize % 10) == 0) {
                    int curPercent = (curSize * 100) / fileSize;
                    if (curPercent != lastPercent) {
                        lastPercent = curPercent;
                        setStatus(I18n.getString("downloading_uc") + "... : (" + shortUrl + ") --> "
                                + curPercent + " %" + " ( " + (numSuccesses + numFailed + numNoRobots) + "/"
                                + getNumLinksFound() + ")");
                    }
                } // end for percent updates
                else if (curSize % 40 == 0) {
                    setStatus(I18n.getString("downloading_uc") + "... : (" + shortUrl + ") --> " + curSize + " "
                            + I18n.getString("bytes"));
                }

                // handle links
                if (curIsWebPage) {
                    char c = (char) curI;
                    // LOOK AT THE TAGS

                    // start tag
                    if (c == '<') {
                        inTag = true;
                        tag = new StringBuilder();
                    }
                    // end tag
                    else if (c == '>') {
                        inTag = false;
                        tag.append(c);
                        String realTag = tag.toString();
                        String lowerTag = realTag.toLowerCase();

                        // TODO fix problem with spaces before =

                        // link
                        if (lowerTag.startsWith("<a ")) {
                            link = Utils.getTagString("href=", realTag);
                            link = Utils.getNormalUrl(link);
                            doPossibleAdd(urlStr, link);
                        }
                        // area
                        else if (lowerTag.startsWith("<area")) {
                            link = Utils.getTagString("href=", realTag);
                            link = Utils.getNormalUrl(link);
                            doPossibleAdd(urlStr, link);
                        }
                        // TODO is in param realy a link?
                        else if (lowerTag.startsWith("<param")) {
                            String appletParam = Utils.getTagString("name=", realTag);
                            if (appletParam.toLowerCase().equals("url")) {
                                link = Utils.getTagString("value=", realTag);
                                link = Utils.getNormalUrl(link);
                                doPossibleAdd(urlStr, link);
                            }
                        }
                    }

                    // in tag
                    if (inTag) {
                        tag.append(c);
                    }
                }

                // filesize ok
                if (getFileSizeFromStream && fileSize > maxFileSizeToGet) {
                    break;
                }
            } // end while downloading
            curPread++;
            fileOutStream.close();
            urlStream.close();
            curl.setMd5(FileUtils.getMD5Sum(downloadFile));

            // now add out document
            if (ds != null) {
                curSuccessNo = ds.idx.addDocToIndex(downloadFile, iw, dsi, false, curl);
                switch (curSuccessNo) {
                case 0: // good
                    numSuccesses++;
                    break;
                case 1: // bad
                    numFailed++;
                    break;
                case 2: // meta robots - no index
                    numNoRobots++;
                    break;
                }
            }

            // delete temp file
            if (!FileUtils.deleteFile(downloadFile)) {
                logger.warn("getAllLinks() can't delete file '" + downloadFile + "'");
            }

            numSpidered++;
            completedSpider = true;

            // max links found
            if (numSpidered > maxLinksToFind) {
                break;
            }
        } catch (Exception e) {
            logger.fatal("getAllLinks() failed", e);
            setStatus(I18n.getString("error") + " : " + e.toString());
            isDead = true;
        } finally {
            // close resources
            IOUtils.closeQuietly(urlStream);
            IOUtils.closeQuietly(fileOutStream);

            curl.setSpidered(completedSpider);
            curl.setIsDeadLink(isDead);
            setStatus(I18n.getString("download_complete") + " " + shortUrl);
        }
    } // end for iterating over links

    if (ds != null) {
        ds.resetProgress();
    }
    saveAllLinks();

    logger.info("getAllLinks() " + numSpidered + " total web pages spidered for links.");

    showMessage(I18n.getString("spidering_complete") + " (" + Utils.concatStrToEnd(pageName, 28) + ") ",
            numSpidered + " " + I18n.getString("documents_indexed") + " " + getNumLinksFound() + " "
                    + I18n.getString("links_found") + "\n\n" + numSuccesses + " "
                    + I18n.getString("documents_spidered_successful") + "\n\n" + numFailed + " "
                    + I18n.getString("documents_spidered_failed") + "\n\n" + numNoRobots + " "
                    + I18n.getString("documents_not_spidered"));
}

From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java

@SuppressWarnings("SleepWhileInLoop") // We are just using the sleep for rate limiting
private void tsaRequest() throws Exception {
    final Random rand = new Random();
    final TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
    boolean doRun = true;
    do {//  w  w  w. java2s.  c o m

        final int nonce = rand.nextInt();

        byte[] digest = new byte[20];
        if (instring != null) {
            final byte[] digestBytes = instring.getBytes("UTF-8");
            final MessageDigest dig = MessageDigest.getInstance(TSPAlgorithms.SHA1.getId(), "BC");
            dig.update(digestBytes);
            digest = dig.digest();
            // When we have given input, we don't want to loop
            doRun = false;
        }
        if (infilestring != null) {
            // TSPAlgorithms constants changed from Strings to ASN1Encoded objects
            digest = digestFile(infilestring, TSPAlgorithms.SHA1.getId());
            doRun = false;
        }
        final byte[] hexDigest = Hex.encode(digest);

        if (LOG.isDebugEnabled()) {
            LOG.debug("MessageDigest=" + new String(hexDigest));
        }

        final TimeStampRequest timeStampRequest;
        if (inreqstring == null) {
            LOG.debug("Generating a new request");
            timeStampRequestGenerator.setCertReq(certReq);
            if (reqPolicy != null) {
                timeStampRequestGenerator.setReqPolicy(new ASN1ObjectIdentifier(reqPolicy));
            }
            timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, digest,
                    BigInteger.valueOf(nonce));
        } else {
            LOG.debug("Reading request from file");
            timeStampRequest = new TimeStampRequest(readFiletoBuffer(inreqstring));
        }
        final byte[] requestBytes = timeStampRequest.getEncoded();

        if (outreqstring != null) {
            // Store request
            byte[] outBytes;
            if (base64) {
                outBytes = Base64.encode(requestBytes);
            } else {
                outBytes = requestBytes;
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outreqstring);
                fos.write(outBytes);
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }
        }

        keyStoreOptions.setupHTTPS();

        URL url;
        URLConnection urlConn;
        DataOutputStream printout;
        DataInputStream input;

        url = new URL(urlstring);

        // Take start time
        final long startMillis = System.currentTimeMillis();
        final long startTime = System.nanoTime();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending request at: " + startMillis);
        }

        urlConn = url.openConnection();

        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/timestamp-query");

        // Send POST output.
        printout = new DataOutputStream(urlConn.getOutputStream());
        printout.write(requestBytes);
        printout.flush();
        printout.close();

        // Get response data.
        input = new DataInputStream(urlConn.getInputStream());

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int b;
        while ((b = input.read()) != -1) {
            baos.write(b);
        }

        // Take stop time
        final long estimatedTime = System.nanoTime() - startTime;

        LOG.info("Got reply after " + TimeUnit.NANOSECONDS.toMillis(estimatedTime) + " ms");

        final byte[] replyBytes = baos.toByteArray();
        if (outrepstring != null) {
            // Store request
            byte[] outBytes;
            if (base64) {
                outBytes = Base64.encode(replyBytes);
            } else {
                outBytes = replyBytes;
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outrepstring);
                fos.write(outBytes);
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }
        }

        final TimeStampResponse timeStampResponse = new TimeStampResponse(replyBytes);
        timeStampResponse.validate(timeStampRequest);

        LOG.info("TimeStampRequest validated");

        if (LOG.isDebugEnabled()) {
            final Date genTime;
            if (timeStampResponse.getTimeStampToken() != null
                    && timeStampResponse.getTimeStampToken().getTimeStampInfo() != null) {
                genTime = timeStampResponse.getTimeStampToken().getTimeStampInfo().getGenTime();
            } else {
                genTime = null;
            }
            LOG.debug("(Status: " + timeStampResponse.getStatus() + ", " + timeStampResponse.getFailInfo()
                    + "): " + timeStampResponse.getStatusString()
                    + (genTime != null ? (", genTime: " + genTime.getTime()) : "") + "\n");

        }

        if (doRun) {
            Thread.sleep(sleep);
        }
    } while (doRun);
}

From source file:com.sun.faces.config.ConfigureListener.java

/**
 * <p>Parse the configuration resource at the specified URL, using
 * the specified <code>Digester</code> instance.</p>
 *
 * @param digester Digester to use for parsing
 * @param url      URL of the configuration resource to be parsed
 * @param fcb      FacesConfigBean to accumulate results
 *///from w  w  w  . j  a va2  s . c  o m
protected void parse(Digester digester, URL url, FacesConfigBean fcb) {

    if (log.isDebugEnabled()) {
        log.debug("parse(" + url.toExternalForm() + ')');
    }

    URLConnection conn = null;
    InputStream stream = null;
    InputSource source = null;
    try {
        conn = url.openConnection();
        conn.setUseCaches(false);
        stream = conn.getInputStream();
        source = new InputSource(url.toExternalForm());
        source.setByteStream(stream);
        digester.clear();
        digester.push(fcb);
        digester.parse(source);
        stream.close();
        stream = null;
    } catch (Exception e) {
        String message = null;
        try {
            message = Util.getExceptionMessageString(Util.CANT_PARSE_FILE_ERROR_MESSAGE_ID,
                    new Object[] { url.toExternalForm() });
        } catch (Exception ee) {
            message = "Can't parse configuration file:" + url.toExternalForm();
        }
        if (log.isErrorEnabled()) {
            log.error(message, e);
        }
        throw new FacesException(message, e);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {
                ;
            }
        }
        stream = null;
    }

}

From source file:com.adobe.aem.demo.communities.Loader.java

private static void doAnalytics(String analytics, String event, String pageURL, String resourcePath,
        String resourceType) {//from  w ww.  ja va2 s  .com

    if (analytics != null && pageURL != null && resourcePath != null && resourceType != null && event != null) {

        URLConnection urlConn = null;
        DataOutputStream printout = null;
        BufferedReader input = null;
        String tmp = null;
        try {

            URL pageurl = new URL(pageURL);
            StringBuffer sb = new StringBuffer(
                    "<?xml version=1.0 encoding=UTF-8?><request><sc_xml_ver>1.0</sc_xml_ver>");
            sb.append("<events>" + event + "</events>");
            sb.append("<pageURL>" + pageURL + "</pageURL>");
            sb.append("<pageName>"
                    + pageurl.getPath().substring(1, pageurl.getPath().indexOf(".")).replaceAll("/", ":")
                    + "</pageName>");
            sb.append("<evar1>" + resourcePath + "</evar1>");
            sb.append("<evar2>" + resourceType + "</evar2>");
            sb.append("<visitorID>demomachine</visitorID>");
            sb.append("<reportSuiteID>" + analytics.substring(0, analytics.indexOf(".")) + "</reportSuiteID>");
            sb.append("</request>");

            logger.debug("New Analytics Event: " + sb.toString());

            URL sitecaturl = new URL("http://" + analytics);

            urlConn = sitecaturl.openConnection();
            urlConn.setDoInput(true);
            urlConn.setDoOutput(true);
            urlConn.setUseCaches(false);
            urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            printout = new DataOutputStream(urlConn.getOutputStream());

            printout.writeBytes(sb.toString());
            printout.flush();
            printout.close();

            input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

            while (null != ((tmp = input.readLine()))) {
                logger.debug(tmp);
            }
            printout.close();
            input.close();

        } catch (Exception ex) {

            logger.error(ex.getMessage());

        }

    }

}

From source file:com.itemanalysis.jmetrik.gui.Jmetrik.java

private void checkForUpdates() {
    URL url = null;/*from  w w  w.  j  a v a 2 s.  c  o m*/
    URLConnection urlConn = null;
    BufferedReader br = null;
    logger.info("Checking for updates...");

    try {
        url = new URL("http://www.itemanalysis.com/version/jmetrik-version.txt");
        urlConn = url.openConnection();

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

        br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        String s = "";
        String[] availableVersion = null;
        String[] currentVersion = VERSION.split("\\.");
        int needUpdate = 0;

        while ((s = br.readLine()) != null) {
            availableVersion = s.trim().split("\\.");
        }
        br.close();

        if (currentVersion.length < availableVersion.length) {
            needUpdate++;
        }

        for (int i = 0; i < currentVersion.length; i++) {
            if (Integer.parseInt(currentVersion[i].trim()) < Integer.parseInt(availableVersion[i].trim())) {
                needUpdate++;
            }
        }
        if (needUpdate > 0 && !BETA_VERSION) {
            showUpdateResults(needUpdate > 0);
            logger.info(
                    "jMetrik updates available. Please go to www.ItemAnalysis.com and download the new version.");
        } else {
            logger.info("No updates available. You have the most current version of jMetrik.");
        }

    } catch (MalformedURLException ex) {
        logger.fatal("Could not access update information: MalformedURLException");
    } catch (IOException ex) {
        logger.fatal("Could not access update information: IOException");
    }
}

From source file:com.threerings.getdown.data.Application.java

/**
 * Download a path to a temporary file, returning a {@link File} instance with the path
 * contents.//from  w w  w.  j a v a  2  s  . c  om
 */
protected File downloadFile(String path) throws IOException {
    File target = getLocalPath(path + "_new");

    URL targetURL = null;
    try {
        targetURL = getRemoteURL(path);
    } catch (Exception e) {
        log.warning("Requested to download invalid control file", "appbase", _vappbase, "path", path, "error",
                e);
        throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
    }

    log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");

    // stream the URL into our temporary file
    InputStream fin = null;
    FileOutputStream fout = null;
    try {
        URLConnection uconn = ConnectionUtil.open(targetURL);
        // we have to tell Java not to use caches here, otherwise it will cache any request for
        // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
        // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
        // about it; turning off caches is not a performance concern, because when Getdown asks
        // to download a file, it expects it to come over the wire, not from a cache
        uconn.setUseCaches(false);
        // configure a connect timeout if requested
        int ctimeout = SysProps.connectTimeout();
        if (ctimeout > 0) {
            uconn.setConnectTimeout(ctimeout * 1000);
        }
        fin = uconn.getInputStream();
        fout = new FileOutputStream(target);
        StreamUtil.copy(fin, fout);
    } finally {
        StreamUtil.close(fin);
        StreamUtil.close(fout);
    }

    return target;
}