Example usage for java.rmi.server UID UID

List of usage examples for java.rmi.server UID UID

Introduction

In this page you can find the example usage for java.rmi.server UID UID.

Prototype

public UID() 

Source Link

Document

Generates a UID that is unique over time with respect to the host that it was generated on.

Usage

From source file:gov.nih.nci.caarray.services.external.v1_0.data.AbstractDataApiUtils.java

/**
 * {@inheritDoc}/*from w ww.j ava 2s .co  m*/
 */
public File downloadMageTabFilesetToTempDir(CaArrayEntityReference experimentRef)
        throws InvalidReferenceException, DataTransferException, IOException {
    String tempDirName = new UID().toString().replace(':', '_');
    File tempDir = new File(System.getProperty("java.io.tmpdir"), tempDirName);
    downloadMageTabFileSetToDir(experimentRef, tempDir);
    return tempDir;
}

From source file:com.zotoh.maedr.device.Device.java

/**
 * @param mgr
 */
protected Device(DeviceManager<?, ?> mgr) {
    tstObjArg("device-mgr", mgr);
    _devMgr = mgr;
    _id = new UID().toString();
}

From source file:net.urlgrey.mythpodcaster.transcode.TranscodingControllerImpl.java

private void encodeOnePassSegmented(TranscodingProfile profile, File inputFile, File outputFile)
        throws Exception {

    LOGGER.info("Starting one-pass segmented vod encoding: inputFile[" + inputFile.getAbsolutePath() + "]");
    File workingDirectory = FileOperations.createTempDir();
    File tempOutputFile = File.createTempFile(new UID().toString(), "tmp");

    try {/*from ww w. j  av a2  s . c  om*/
        final GenericTranscoderConfigurationItem pass1Config = profile.getTranscoderConfigurationItems().get(0);
        ffmpegTranscoder.transcode(workingDirectory, pass1Config, inputFile, tempOutputFile);

        final GenericTranscoderConfigurationItem segmentedVodConfig = profile.getTranscoderConfigurationItems()
                .get(1);
        segmentedVodTranscoder.transcode(workingDirectory, segmentedVodConfig, tempOutputFile, outputFile);
    } catch (Exception e) {
        FileOperations.deleteDir(outputFile.getParentFile());
        throw e;
    } finally {
        FileOperations.deleteDir(workingDirectory);

        if (tempOutputFile.exists()) {
            tempOutputFile.delete();
        }
    }
}

From source file:net.urlgrey.mythpodcaster.transcode.TranscodingControllerImpl.java

private void encodeTwoPassSegmented(TranscodingProfile profile, File inputFile, File outputFile)
        throws Exception {

    LOGGER.info("Starting two-pass segmented vod encoding: inputFile[" + inputFile.getAbsolutePath() + "]");
    File workingDirectory = FileOperations.createTempDir();
    File tempOutputFile = File.createTempFile(new UID().toString(), "tmp");

    try {/*  w ww .  j  a  va  2 s . c o m*/
        final GenericTranscoderConfigurationItem pass1Config = profile.getTranscoderConfigurationItems().get(0);
        ffmpegTranscoder.transcode(workingDirectory, pass1Config, inputFile, tempOutputFile);

        final GenericTranscoderConfigurationItem pass2Config = profile.getTranscoderConfigurationItems().get(1);
        ffmpegTranscoder.transcode(workingDirectory, pass2Config, inputFile, tempOutputFile);

        final GenericTranscoderConfigurationItem segmentedVodConfig = profile.getTranscoderConfigurationItems()
                .get(2);
        segmentedVodTranscoder.transcode(workingDirectory, segmentedVodConfig, tempOutputFile, outputFile);
    } catch (Exception e) {
        FileOperations.deleteDir(outputFile.getParentFile());
        throw e;
    } finally {
        FileOperations.deleteDir(workingDirectory);

        if (tempOutputFile.exists()) {
            tempOutputFile.delete();
        }
    }
}

From source file:com.enonic.vertical.userservices.OrderHandlerController.java

protected void handlerCustom(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        ExtendedMap formItems, UserServicesService userServices, SiteKey siteKey, String operation)
        throws VerticalUserServicesException, VerticalEngineException, RemoteException {

    MultiValueMap queryParams = new MultiValueMap();

    // NB! Operations must be sorted alphabetically!
    String[] operations = new String[] { "cart_add", "cart_checkout", "cart_empty", "cart_remove",
            "cart_update" };
    if (operation != null && Arrays.binarySearch(operations, operation) >= 0) {
        ShoppingCart cart = (ShoppingCart) session.getAttribute("shoppingcart");
        if (cart == null) {
            cart = new ShoppingCart();
            session.setAttribute("shoppingcart", cart);
        }/*from   w  ww .  j av a 2 s  . com*/

        try {
            if ("cart_add".equals(operation)) {
                int productId = formItems.getInt("productid");
                int count = formItems.getInt("count", 1);

                if (count > 0) {
                    User user = securityService.getOldUserObject();
                    String xml = userServices.getContent(user, productId, true, 0, 0, 0);
                    if (xml == null || xml.length() == 0) {
                        String message = "Failed to get product: %0";
                        VerticalUserServicesLogger.warn(this.getClass(), 0, message, productId, null);
                        redirectToErrorPage(request, response, formItems, ERR_FAILED_TO_GET_PRODUCT, null);
                        return;
                    }

                    Document doc = XMLTool.domparse(xml);
                    Element root = doc.getDocumentElement();
                    if (XMLTool.getFirstElement(root) == null) {
                        redirectToErrorPage(request, response, formItems, ERR_FAILED_TO_GET_PRODUCT, null);
                        return;
                    }

                    String productNumber = XMLTool.getElementText(doc, "/contents/content/contentdata/number");
                    String productName = XMLTool.getElementText(doc, "/contents/content/title");
                    String priceStr = XMLTool.getElementText(doc, "/contents/content/contentdata/price");
                    double price;
                    if (priceStr != null) {
                        priceStr = priceStr.replace(',', '.');
                        price = Double.parseDouble(priceStr);
                    } else {
                        price = 0.0D;
                    }

                    String[] keyFilter = new String[] { "count", "handler", "_handler", "op", "_op",
                            "productid", "redirect", "_redirect" };
                    Map<String, String> customValues = new HashMap<String, String>();
                    for (Object o : formItems.keySet()) {
                        String key = (String) o;
                        if (Arrays.binarySearch(keyFilter, key) < 0) {
                            customValues.put(key, formItems.get(key).toString());
                        }
                    }

                    cart.addItem(productId, productNumber, productName, price, count, customValues);
                }
            } else if ("cart_remove".equals(operation)) {
                int productId = formItems.getInt("productid");
                cart.removeItem(productId);
            } else if ("cart_update".equals(operation)) {
                int productId = formItems.getInt("productid");
                int count = formItems.getInt("count", 1);
                if (count > 0) {
                    cart.updateItem(productId, count);
                } else {
                    cart.removeItem(productId);
                }
            } else if ("cart_checkout".equals(operation)) {
                if (cart.isEmpty()) {
                    redirectToErrorPage(request, response, formItems, ERR_SHOPPING_CART_EMPTY, null);
                    return;
                }

                User user = securityService.getOldUserObject();
                String guid = new UID().toString();
                formItems.put("_guid", guid);
                formItems.put("_shoppingcart", cart);

                // customer name
                String customerFirstname = formItems.getString("customer_firstname");
                String customerSurname = formItems.getString("customer_surname");
                StringBuffer customerName = new StringBuffer(customerFirstname);
                if (customerName.length() > 0) {
                    customerName.append(' ');
                }
                customerName.append(customerSurname);

                String xmlData = buildXML(userServices, user, formItems, siteKey, contentTypeKey,
                        customerName.toString(), false);

                ContentKey orderKey = storeNewContent(user, null, xmlData);

                // send mail
                // mail header
                String[] shopManagerEmail = formItems.getStringArray("shopmanager_email");
                //String shopManagerName = formItems.getString("shopmanager_name");
                String sender_email = formItems.getString("mail_sender_email");
                String sender_name = formItems.getString("mail_sender_name");
                String customerEmail = formItems.getString("customer_email");
                String receiver_name = customerFirstname + ' ' + customerSurname;
                String subject = formItems.getString("mail_subject");
                String message = formItems.getString("mail_message");

                // order info
                String orderId = orderKey.toString();
                String orderDate = CalendarUtil.formatCurrentDate();
                String orderStatus = "Submitted";
                String orderReference = formItems.getString("order_reference", "");
                String orderUrl = formItems.getString("showorderurl", "") + "page?id="
                        + formItems.getString("showorderpage", "") + "&key=" + orderKey.toString() + "&guid="
                        + guid;
                subject = RegexpUtil.substituteAll("\\%order_id\\%", orderId, subject);
                message = RegexpUtil.substituteAll("\\%order_id\\%", orderId, message);
                message = RegexpUtil.substituteAll("\\%order_reference\\%", orderReference, message);
                message = RegexpUtil.substituteAll("\\%order_date\\%", orderDate, message);
                message = RegexpUtil.substituteAll("\\%order_status\\%", orderStatus, message);
                message = RegexpUtil.substituteAll("\\%order_url\\%", orderUrl, message);

                // customer info
                String customerRefNo = formItems.getString("customer_refno", "");
                String customerCompany = formItems.getString("customer_company", "");
                String customerTelephone = formItems.getString("customer_telephone", "");
                String customerMobile = formItems.getString("customer_mobile", "");
                String customerFax = formItems.getString("customer_fax", "");
                message = RegexpUtil.substituteAll("\\%customer_firstname\\%", customerFirstname, message);
                message = RegexpUtil.substituteAll("\\%customer_surname\\%", customerSurname, message);
                message = RegexpUtil.substituteAll("\\%customer_email\\%", customerEmail, message);
                message = RegexpUtil.substituteAll("\\%customer_refno\\%", customerRefNo, message);
                message = RegexpUtil.substituteAll("\\%customer_company\\%", customerCompany, message);
                message = RegexpUtil.substituteAll("\\%customer_telephone\\%", customerTelephone, message);
                message = RegexpUtil.substituteAll("\\%customer_mobile\\%", customerMobile, message);
                message = RegexpUtil.substituteAll("\\%customer_fax\\%", customerFax, message);

                // shipping address
                String shippingPostalAddress = formItems.getString("shipping_postaladdress", "");
                String shippingPostalCode = formItems.getString("shipping_postalcode", "");
                String shippingLocation = formItems.getString("shipping_location", "");
                String shippingCountry = formItems.getString("shipping_country", "");
                String shippingState = formItems.getString("shipping_state", "");
                message = RegexpUtil.substituteAll("\\%shipping_postaladdress\\%", shippingPostalAddress,
                        message);
                message = RegexpUtil.substituteAll("\\%shipping_postalcode\\%", shippingPostalCode, message);
                message = RegexpUtil.substituteAll("\\%shipping_location\\%", shippingLocation, message);
                message = RegexpUtil.substituteAll("\\%shipping_country\\%", shippingCountry, message);
                message = RegexpUtil.substituteAll("\\%shipping_state\\%", shippingState, message);

                // billing address
                String billingPostalAddress = formItems.getString("billing_postaladdress", "");
                String billingPostalCode = formItems.getString("billing_postalcode", "");
                String billingLocation = formItems.getString("billing_location", "");
                String billingCountry = formItems.getString("billing_country", "");
                String billingState = formItems.getString("billing_state", "");
                message = RegexpUtil.substituteAll("\\%billing_postaladdress\\%", billingPostalAddress,
                        message);
                message = RegexpUtil.substituteAll("\\%billing_postalcode\\%", billingPostalCode, message);
                message = RegexpUtil.substituteAll("\\%billing_location\\%", billingLocation, message);
                message = RegexpUtil.substituteAll("\\%billing_country\\%", billingCountry, message);
                message = RegexpUtil.substituteAll("\\%billing_state\\%", billingState, message);

                String regexp = "\\%details_(comments|shippingoptions)\\%";
                String substRegexpStart = "\\%details_";
                String substRegexpEnd = "\\%";

                Matcher results = RegexpUtil.match(message, regexp);
                while (results.find()) {
                    String orderDetail = "";
                    StringBuffer substRegexp = new StringBuffer(substRegexpStart);
                    substRegexp.append(results.group(1));
                    substRegexp.append(substRegexpEnd);
                    if ("comments".equals(results.group(1))) {
                        if (formItems.containsKey("details_comments")) {
                            orderDetail = (String) formItems.get("details_comments");
                        } else {
                            orderDetail = "";
                        }
                    } else if ("shippingoptions".equals(results.group(1))) {
                        if (formItems.containsKey("details_shippingoptions")) {
                            orderDetail = (String) formItems.get("details_shippingoptions");
                        } else {
                            orderDetail = "";
                        }
                    }
                    message = RegexpUtil.substituteAll(substRegexp.toString(), orderDetail, message);
                }

                String orderItem = formItems.getString("mail_order_item");
                message = cart.addItemsToMailMessage(message, orderItem);
                message = cart.addTotalToMailMessage(message);

                sendMail(customerEmail, receiver_name, sender_email, sender_name, subject, message);

                if (shopManagerEmail.length > 0) {
                    for (String aShopManagerEmail : shopManagerEmail) {
                        if (StringUtils.isNotEmpty(aShopManagerEmail)) {
                            sendMail(aShopManagerEmail, null, sender_email, sender_name, subject, message);
                        }
                    }
                }

                cart.clear();

                String showOrder = formItems.getString("showorderonredirect", null);
                if ("true".equals(showOrder)) {
                    queryParams.put("key", orderKey.toString());
                    queryParams.put("guid", guid);
                }
            } else if ("cart_empty".equals(operation)) {
                cart.clear();
            }

            redirectToPage(request, response, formItems, queryParams);
        } catch (UnsupportedEncodingException uee) {
            String message = "Un-supported encoding: %t";
            VerticalUserServicesLogger.error(this.getClass(), 0, message, uee);
            redirectToErrorPage(request, response, formItems, ERR_EMAIL_SEND_FAILED, null);
        } catch (MessagingException me) {
            String message = "Failed to send order received mail: %t";
            VerticalUserServicesLogger.error(this.getClass(), 0, message, operation, me);
            redirectToErrorPage(request, response, formItems, ERR_EMAIL_SEND_FAILED, null);
        }
    } else {
        String message = "Unknown operation: %0";
        VerticalUserServicesLogger.errorUserServices(this.getClass(), 0, message, operation, null);
    }
}

From source file:com.lucid.touchstone.data.EnwikiDocMaker.java

public synchronized DocData makeDocument() throws Exception {
    String[] tuple = parser.next();
    DocData doc = getDocData();// www  .  j  a v a 2  s .  co m
    doc.title = tuple[TITLE];
    doc.date = tuple[DATE];
    doc.body = tuple[BODY];
    doc.id = new UID().toString();

    return doc;
}

From source file:org.commoncrawl.service.listcrawler.HDFSFileIndex.java

public static void main(String[] args) {

    try {/*from   w  w w .  j ava  2s. c  o  m*/
        ByteStream outputStream = new ByteStream(8192);
        Vector<FingerprintAndOffsetTuple> fpInfo = new Vector<FingerprintAndOffsetTuple>();

        // construct 10000 entries with randomin fingerprints 
        for (int i = 0; i < 10000; ++i) {
            MessageDigest digester;
            digester = MessageDigest.getInstance("MD5");
            long time = System.currentTimeMillis();
            digester.update((new UID() + "@" + time + ":" + i).getBytes());
            FingerprintAndOffsetTuple offsetInfo = new FingerprintAndOffsetTuple(
                    URLFingerprint.generate64BitURLFPrint(StringUtils.byteToHexString(digester.digest())),
                    i * 10000);
            fpInfo.add(offsetInfo);
        }
        // clone the vector 
        Vector<FingerprintAndOffsetTuple> fpInfoCloned = new Vector<FingerprintAndOffsetTuple>();
        fpInfoCloned.addAll(fpInfo);
        // now write out the index ... 
        writeIndex(fpInfoCloned, new DataOutputStream(outputStream));
        // spit out some basic stats 
        System.out.println("output buffer size is:" + outputStream.size());

    } catch (Exception e) {
        CacheManager.LOG.error(CCStringUtils.stringifyException(e));
    }
}

From source file:jade.domain.DFDBKB.java

/**
 * Returns a global unique identifier//from   ww w .j av a2 s  .  co m
 */
protected String getGUID() {
    UID uid = new UID();
    return localIPAddress + ":" + uid;
}

From source file:de.dfki.km.leech.parser.wikipedia.WikipediaDumpParser.java

protected void parseInfoBox(String strText, Metadata metadata, ContentHandler handler) throws SAXException {

    // att-value paare mit | getrennt. Innerhalb eines values gibt es auch Zeilenumbrche (mit '<br />') - dies gilt als Aufzhlung
    // |Single1 |Datum1 , Besetzung1a Besetzung1b, Sonstiges1Titel |Sonstiges1Inhalt , Coverversion3 |Jahr3
    // | 1Option = 3
    // | 1Option Name = Demos
    // | 1Option Link = Demos
    // | 1Option Color =

    // als erstes schneiden wir mal die Infobox raus. (?m) ist multiline und (?s) ist dotall ('.' matcht auch line breaks)
    int iStartInfoBox = -1;
    int iEndInfoBox = -1;
    MatchResult infoMatch = StringUtils.findFirst("\\{\\{\\s*Infobox", strText);
    if (infoMatch != null) {
        iStartInfoBox = infoMatch.start();
        iEndInfoBox = StringUtils.findMatchingBracket(iStartInfoBox, strText) + 1;
    } else//from   ww  w .  j  a v a2 s. c om
        return;

    if (strText.length() < 3 || strText.length() < iEndInfoBox || iEndInfoBox <= 0
            || (iStartInfoBox + 2) > iEndInfoBox)
        return;

    String strInfoBox = "";

    strInfoBox = strText.substring(iStartInfoBox + 2, iEndInfoBox);
    if (strInfoBox.length() < 5)
        return;

    String strCleanedInfoBox = m_wikiModel.render(new PlainTextConverter(),
            strInfoBox.replaceAll("<br />", "&lt;br /&gt;"));

    // da wir hier eigentlich relationierte Datenstze haben, machen wir auch einzelne, separierte Dokumente draus

    // System.out.println(strCleanedInfoBox);
    // System.out.println(strCleanedInfoBox.substring(0, strCleanedInfoBox.indexOf("\n")).trim());

    // erste Zeile bezeichnet die InfoBox
    int iIndex = strCleanedInfoBox.indexOf("|");
    if (iIndex == -1)
        iIndex = strCleanedInfoBox.indexOf("\n");
    if (iIndex == -1)
        return;
    String strInfoBoxName = strCleanedInfoBox.substring(7, iIndex).trim();
    metadata.add(infobox, strInfoBoxName);

    String[] straCleanedInfoBoxSplit = strCleanedInfoBox.split("\\s*\\|\\s*");

    HashMap<String, MultiValueHashMap<String, String>> hsSubDocId2AttValuePairsOfSubDoc = new HashMap<String, MultiValueHashMap<String, String>>();

    for (String strAttValuePair : straCleanedInfoBoxSplit) {

        // System.out.println("\nattValPair unsplittet " + strAttValuePair);
        // die Dinger sind mit einem '=' getrennt
        String[] straAtt2Value = strAttValuePair.split("=");

        if (straAtt2Value.length == 0 || straAtt2Value[0] == null)
            continue;
        if (straAtt2Value.length < 2 || straAtt2Value[1] == null)
            continue;

        String strAttName = straAtt2Value[0].trim();
        String strAttValues = straAtt2Value[1];
        if (StringUtils.nullOrWhitespace(strAttValues))
            continue;
        // Innerhalb eines values gibt es auch Zeilenumbrche (mit '<br />' bzw. '&lt;br /&gt;') - dies gilt als Aufzhlung
        String[] straAttValues = strAttValues.split(Pattern.quote("&lt;br /&gt;"));
        // XXX wir werfen zusatzangaben in Klammern erst mal weg - man knnte sie auch als attnameAddInfo in einem extra Attribut speichern -
        // allerdings mu man dann wieder aufpassen, ob nicht ein subDocument entstehen mu (Bsp. mehrere Genre-entries mit jeweiliger
        // Jahreszahl)

        // der Attributname entscheidet nun, ob ein Dokument ausgelagert werden soll oder nicht. Ist darin eine Zahl enthalten, dann entfernen
        // wir diese und gruppieren alle att-value-paare mit dieser Zahl in einen extra Datensatz (MultiValueHashMap)
        Matcher numberMatcher = Pattern.compile("([\\D]*)(\\d+)([\\D]*)").matcher(strAttName);

        if (!numberMatcher.find()) {
            // wir haben keine Zahl im AttNamen - wir tragen diesen Wert einfach in die Metadaten ein.
            for (String strAttValue : straAttValues) {
                String strCleanedAttValue = cleanAttValue(strAttName, strAttValue);
                if (strCleanedAttValue != null)
                    metadata.add(strAttName, strCleanedAttValue);
            }
        } else {
            // wir haben eine Zahl im Namen - wir tragen den Wert in einem SubDocument unter der Id <zahl> ein
            String strPrefix = numberMatcher.group(1);
            String strNumber = numberMatcher.group(2);
            String strSuffix = numberMatcher.group(3);

            String strDataSetId = strPrefix + strNumber;
            String strFinalAttName = strPrefix + strSuffix;

            // wenn wir noch mehr Zahlen haben, dann haben wir geloost - und tragen es einfach ein
            if (numberMatcher.find()) {
                for (String strAttValue : straAttValues) {
                    String strCleanedAttValue = cleanAttValue(strFinalAttName, strAttValue);
                    if (strCleanedAttValue != null)
                        metadata.add(strFinalAttName, strCleanedAttValue);
                }
            }

            // System.out.println("prefix " + strPrefix);
            // System.out.println("num " + strDataSetId);
            // System.out.println("suffix " + strSuffix);
            MultiValueHashMap<String, String> hsAttname2ValueOfSubDoc = hsSubDocId2AttValuePairsOfSubDoc
                    .get(strDataSetId);
            if (hsAttname2ValueOfSubDoc == null) {
                hsAttname2ValueOfSubDoc = new MultiValueHashMap<String, String>();
                hsSubDocId2AttValuePairsOfSubDoc.put(strDataSetId, hsAttname2ValueOfSubDoc);
            }

            for (String strAttValue : straAttValues)
                hsAttname2ValueOfSubDoc.add(strFinalAttName, strAttValue.replaceAll("\\(.*?\\)", "").trim());

        }
    }

    String strPageId = new UID().toString();
    metadata.add(LeechMetadata.id, strPageId);

    // we have to use the same metadata Object
    Metadata metadataBackup4ParentPage = TikaUtils.copyMetadata(metadata);

    for (MultiValueHashMap<String, String> hsAttValuePairsOfSubDoc : hsSubDocId2AttValuePairsOfSubDoc
            .values()) {

        TikaUtils.clearMetadata(metadata);

        // die Referenz zu meinem parent
        metadata.add(LeechMetadata.parentId, strPageId);
        metadata.add(infobox, strInfoBoxName);
        String strChildId = new UID().toString();
        metadata.add(LeechMetadata.id, strChildId);
        // zum rckreferenzieren geben wir dem parent auch noch unsere id
        metadataBackup4ParentPage.add(LeechMetadata.childId, strChildId);

        for (Entry<String, String> attName2Value4SubDoc : hsAttValuePairsOfSubDoc.entryList()) {
            String strAttName = attName2Value4SubDoc.getKey();
            String strAttValue = attName2Value4SubDoc.getValue();

            String strCleanedAttValue = cleanAttValue(strAttName, strAttValue);
            if (strCleanedAttValue != null)
                metadata.add(strAttName, strCleanedAttValue);
        }

        metadata.add(Metadata.CONTENT_TYPE, "application/wikipedia-meta+xml");

        // so erreichen wir, da im bergeordneten ContentHandler mehrere Docs ankommen :)
        XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
        xhtml.startDocument();
        xhtml.endDocument();

    }

    TikaUtils.clearMetadata(metadata);
    TikaUtils.copyMetadataFromTo(metadataBackup4ParentPage, metadata);

}

From source file:org.commoncrawl.service.listcrawler.CacheManager.java

/********************************************************************************************************/

public static void main(String[] args) {

    final EventLoop eventLoop = new EventLoop();
    eventLoop.start();//from   w w  w. j  ava 2s .  co  m

    final CacheManager manager = new CacheManager(eventLoop);
    // delete active log if it exists ... 
    manager.getActiveLogFilePath().delete();
    try {
        manager.initialize(INIT_FLAG_SKIP_CACHE_WRITER_INIT | INIT_FLAG_SKIP_HDFS_WRITER_INIT);
    } catch (IOException e1) {
        LOG.error(CCStringUtils.stringifyException(e1));
        return;
    }

    MessageDigest digester;
    try {
        digester = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e1) {
        LOG.error(CCStringUtils.stringifyException(e1));
        return;
    }

    final byte[] randomBytes = new byte[1 << 15];
    LOG.info("Building Random Digest");
    for (int i = 0; i < randomBytes.length; i += 16) {
        long time = System.nanoTime();
        digester.update((new UID() + "@" + time).getBytes());
        System.arraycopy(digester.digest(), 0, randomBytes, i, 16);
    }

    final Semaphore semaphore = new Semaphore(0);

    if (args[0].equals("populate")) {

        manager.startCacheWriterThread();
        manager.startHDFSFlusherThread();

        try {

            LOG.info("Done Building Random Digest");

            LOG.info("Writing Items To Disk");
            for (int i = 0; i < 1000000; ++i) {

                if (i % 1000 == 0) {
                    LOG.info("Wrote:" + i + " entries");
                }

                final CacheItem item1 = new CacheItem();
                item1.setUrl(manager.normalizeURL("http://www.domain.com/foobar/" + i));
                item1.setContent(new Buffer(randomBytes));
                item1.setUrlFingerprint(URLFingerprint.generate64BitURLFPrint(item1.getUrl()));
                manager.cacheItem(item1, null);
                Thread.sleep(1);

                if (i != 0 && i % 10000 == 0) {
                    LOG.info("Hit 10000 items.. sleeping for 20 seconds");
                    Thread.sleep(20 * 1000);
                }
            }

            Thread.sleep(30000);

            for (int i = 0; i < 1000000; ++i) {

                final String url = new String("http://www.domain.com/foobar/" + i);
                manager.checkCacheForItem(url, new CacheItemCheckCallback() {

                    @Override
                    public void cacheItemAvailable(String url, CacheItem item) {
                        Assert.assertTrue(item.getUrl().equals(url));
                        String itemIndex = url.substring("http://www.domain.com/foobar/".length());
                        int itemNumber = Integer.parseInt(itemIndex);
                        if (itemNumber == 999999) {
                            semaphore.release();
                        }
                    }

                    @Override
                    public void cacheItemNotFound(String url) {
                        Assert.assertTrue(false);
                    }
                });
            }
        } catch (IOException e) {
            LOG.error(CCStringUtils.stringifyException(e));
        } catch (InterruptedException e2) {

        }
    } else if (args[0].equals("read")) {

        try {
            final CacheItem item1 = new CacheItem();
            item1.setUrl(manager.normalizeURL("http://www.domain.com/barz/"));
            item1.setUrlFingerprint(URLFingerprint.generate64BitURLFPrint(item1.getUrl()));
            item1.setContent(new Buffer(randomBytes));
            manager.cacheItem(item1, null);

            // queue up cache load requests .... 
            for (int i = 0; i < 10000; ++i) {

                final String url = new String("http://www.domain.com/foobar/" + i);

                eventLoop.setTimer(new Timer(1, false, new Timer.Callback() {

                    @Override
                    public void timerFired(Timer timer) {
                        manager.checkCacheForItem(url, new CacheItemCheckCallback() {

                            @Override
                            public void cacheItemAvailable(String url, CacheItem item) {
                                LOG.info("FOUND Item for URL:" + url + " ContentSize:"
                                        + item.getContent().getCount());
                            }

                            @Override
                            public void cacheItemNotFound(String url) {
                                LOG.info("DIDNOT Find Item for URL:" + url);
                            }

                        });
                    }
                }));
            }

            eventLoop.setTimer(new Timer(1, false, new Timer.Callback() {

                @Override
                public void timerFired(Timer timer) {
                    manager.checkCacheForItem(item1.getUrl(), new CacheItemCheckCallback() {

                        @Override
                        public void cacheItemAvailable(String url, CacheItem item) {
                            LOG.info("FOUND Item for URL:" + url + " ContentSize:"
                                    + item.getContent().getCount());
                        }

                        @Override
                        public void cacheItemNotFound(String url) {
                            LOG.info("DIDNOT Find Item for URL:" + url);
                        }

                    });
                }

            }));
        } catch (IOException e) {
            LOG.error(CCStringUtils.stringifyException(e));
        }
    }
    semaphore.acquireUninterruptibly();

}