text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
TextUtilities
</TITLE>

<META NAME="keywords" CONTENT="processing.app.syntax.TextUtilities class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

processing.app.syntax

Class TextUtilities

java.lang.Object
  processing.app.syntax.TextUtilities

public class TextUtilities
extends java.lang.Object

Class with several utility functions used by the text area component.

Constructor Summary

TextUtilities()

Method Summary

static int
findMatchingBracket(javax.swing.text.Document doc,
                    int offset)

          Returns the offset of the bracket matching the one at the
 specified offset of the document, or -1 if the bracket is
 unmatched (or if the character is not a bracket).

static int
findWordEnd(java.lang.String line,
            int pos,
            java.lang.String noWordSep)

          Locates the end of the word at the specified position.

static int
findWordStart(java.lang.String line,
              int pos,
              java.lang.String noWordSep)

          Locates the start of the word at the specified position.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TextUtilities

public TextUtilities()

Method Detail

findMatchingBracket

public static int findMatchingBracket(javax.swing.text.Document doc,
                                      int offset)
                               throws javax.swing.text.BadLocationException

Returns the offset of the bracket matching the one at the
 specified offset of the document, or -1 if the bracket is
 unmatched (or if the character is not a bracket).

Parameters:
doc - The document
offset - The offset

Throws:

javax.swing.text.BadLocationException - If an out-of-bounds access
 was attempted on the document text

findWordStart

public static int findWordStart(java.lang.String line,
                                int pos,
                                java.lang.String noWordSep)

Locates the start of the word at the specified position.

Parameters:
line - The text
pos - The position

findWordEnd

public static int findWordEnd(java.lang.String line,
                              int pos,
                              java.lang.String noWordSep)

Locates the end of the word at the specified position.

Parameters:
line - The text
pos - The position

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text: A demo app to demonstrate an issue related to handling of gestures.

redpajama_set_name: RedPajamaGithub


text:
from tw.api import WidgetsList
from tribal.model import DBSession
from tribal.model.bby import *
from tribal.widgets.components import *

__all__ = ["search_form", "mockup_search_form", "casepack_search_form", "basic_form", "basic_info_widget", "report_form","mockup_report_form"]

def getOptions(obj, order_by_field = "name"):
    def fun():
        return [("", ""), ] + [(str(row.id), str(row)) for row in DBSession.query(obj).filter(obj.active == 0).order_by(getattr(obj, order_by_field)).all()]
    return fun

#===============================================================================
# update by CL.Lam on 2010-11-16
#===============================================================================

class SearchForm(RPACForm):
    fields = [
          RPACText("sku", label_text = "SKU#"),
          RPACSelect("brand_id", label_text = "Brand", options = getOptions(BBYBrand)),
          RPACCalendarPicker("issue_date_from", label_text = "Issue Date(from) "),
          RPACCalendarPicker("issue_date_to", label_text = "Issue Date(to)"),
          RPACSelect("vendor_id", label_text = "Vendor", options = getOptions(BBYVendor)),
          RPACSelect("packaging_format_id", label_text = "Packaging Format", options = getOptions(BBYPackagingFormat)),
          RPACSelect("pd_id", label_text = "PD", options = getOptions(BBYTeammate)),
          RPACSelect("ae_id", label_text = "AE", options = getOptions(BBYTeammate)),
          RPACCalendarPicker("pcr_date_from", label_text = "PCR Receive Date(from) "),
          RPACCalendarPicker("pcr_date_to", label_text = "PCR Receive Date(to) "),
          RPACText("pcr", label_text = "PCR#"),
          RPACSelect("status", label_text = "Status", options = [('', ''), ('NEW', 'New'), ('SUBMIT', 'Submit'), ('COMPLETED', 'Completed')]),
              ]

search_form = SearchForm()

class MockupSearchForm(RPACForm):
    fields = [
          RPACText("sku", label_text = "SKU#"),
          RPACSelect("brand_id", label_text = "Brand", options = getOptions(BBYBrand)),
          RPACCalendarPicker("issue_date_from", label_text = "Issue Date(from) "),
          RPACCalendarPicker("issue_date_to", label_text = "Issue Date(to)"),
          RPACSelect("vendor_id", label_text = "Vendor", options = getOptions(BBYVendor)),
          RPACSelect("packaging_format_id", label_text = "Packaging Format", options = getOptions(BBYPackagingFormat)),
          RPACSelect("pd_id", label_text = "PD", options = getOptions(BBYTeammate)),
          RPACSelect("ae_id", label_text = "AE", options = getOptions(BBYTeammate)),
          RPACSelect("status", label_text = "Status", options = [('', ''), ('NEW', 'New'), ('SENT', 'Sent'), ('CONFIRMED', 'Confirmed'), ('COMPLETED', 'Completed')]),
              ]

mockup_search_form = MockupSearchForm()

class CasepackSearchForm(RPACForm):
    fields = [
          RPACText("sku", label_text = "SKU#"),
          RPACSelect("brand_id", label_text = "Brand", options = getOptions(BBYBrand)),
          RPACCalendarPicker("issue_date_from", label_text = "Issue Date(from) "),
          RPACCalendarPicker("issue_date_to", label_text = "Issue Date(to)"),
          RPACSelect("vendor_id", label_text = "Vendor", options = getOptions(BBYVendor)),
          RPACSelect("packaging_format_id", label_text = "Packaging Format", options = getOptions(BBYPackagingFormat)),
          RPACSelect("pd_id", label_text = "PD", options = getOptions(BBYTeammate)),
          RPACSelect("ae_id", label_text = "AE", options = getOptions(BBYTeammate)),
          RPACSelect("status", label_text = "Status", options = [('', ''), ('NEW', 'New'), ('SENT', 'Sent'), ('COMPLETED', 'Completed')]),
              ]

casepack_search_form = CasepackSearchForm()

class BasicForm(RPACForm):
    fields = [
          RPACText("sku", label_text = "SKU#"),
          RPACSelect("brand_id", label_text = "Brand", options = getOptions(BBYBrand)),
          RPACSelect("vendor_id", label_text = "Vendor", options = getOptions(BBYVendor)),
          RPACSelect("packaging_format_id", label_text = "Packaging Format", options = getOptions(BBYPackagingFormat)),
          RPACText("upc_no", label_text = "UPC"),

          RPACSelect("closure_id", label_text = "Closure", options = getOptions(BBYClosure)),
          RPACSelect("display_mode_id", label_text = "Display Mode", options = getOptions(BBYDisplayMode)),

          RPACText("ioq", label_text = "IOQ"),
          RPACText("aoq", label_text = "AOQ"),
          RPACTextarea("product_description", label_text = "Production Description"),
          RPACSelect("pd_id", label_text = "PD", options = getOptions(BBYTeammate)),
          RPACSelect("ae_id", label_text = "AE", options = getOptions(BBYTeammate)),
              ]

basic_form = BasicForm()

class BasicInfo(Form):
    template = "tribal.templates.bby.basic_info_widget"

#    fields = [
#          RPACText("sku", label_text = "SKU#"),
#          RPACText("brand", label_text = "Brand"),
#          RPACText("vendor", label_text = "Vendor"),
#          RPACText("packaging_format", label_text = "Packaging Format"),
#          RPACText("upc_no", label_text = "UPC"),
#          RPACText("closure", label_text = "Closure"),
#          RPACText("display_mode", label_text = "Display Mode"),
#          RPACText("ioq", label_text = "IOQ"),
#          RPACText("aoq", label_text = "AOQ"),
#          RPACTextarea("product_description", label_text = "Production Description"),
#          RPACText("pd", label_text = "PD", options = []),
#          RPACText("ae", label_text = "AE", options = []),
#              ]

basic_info_widget = BasicInfo()

class ReportForm(RPACForm):
    fields=[
          RPACText("sku", label_text = "SKU#"),
          RPACSelect("brand_id", label_text = "Brand", options = getOptions(BBYBrand)),
          RPACCalendarPicker("issue_date_from", label_text = "Issue Date(from) "),
          RPACCalendarPicker("issue_date_to", label_text = "Issue Date(to)"),
          RPACSelect("vendor_id", label_text = "Vendor", options = getOptions(BBYVendor)),
          RPACSelect("packaging_format_id", label_text = "Packaging Format", options = getOptions(BBYPackagingFormat)),
          RPACSelect("pd_id", label_text = "PD", options = getOptions(BBYTeammate)),
          RPACSelect("ae_id", label_text = "AE", options = getOptions(BBYTeammate)),
          RPACSelect("status", label_text = "Status", options = [('', ''), ('NEW', 'New'), ('SUBMIT', 'Submit'), ('COMPLETED', 'Completed')]),
          RPACSelect("factory_id", label_text = "Factory", options = getOptions(BBYSource)),
          RPACSelect("material_id", label_text = "Material", options = getOptions(BBYMaterial)),
      ]

report_form=ReportForm()

class MockupReportForm(RPACForm):
    fields=[
          RPACText("sku", label_text = "SKU#"),
          RPACSelect("brand_id", label_text = "Brand", options = getOptions(BBYBrand)),
          RPACCalendarPicker("issue_date_from", label_text = "Issue Date(from) "),
          RPACCalendarPicker("issue_date_to", label_text = "Issue Date(to)"),
          RPACSelect("vendor_id", label_text = "Vendor", options = getOptions(BBYVendor)),
          RPACSelect("packaging_format_id", label_text = "Packaging Format", options = getOptions(BBYPackagingFormat)),
          RPACSelect("pd_id", label_text = "PD", options = getOptions(BBYTeammate)),
          RPACSelect("ae_id", label_text = "AE", options = getOptions(BBYTeammate)),
          RPACSelect("status", label_text = "Status", options = [('', ''), ('NEW', 'New'), ('SUBMIT', 'Submit'), ('COMPLETED', 'Completed')]),
          RPACSelect("factory_id", label_text = "Factory", options = getOptions(BBYSource)),
          RPACSelect("material_id", label_text = "Material", options = getOptions(BBYMaterial)),
      ]

mockup_report_form=MockupReportForm()


text:
require('../../../../../defaultable')(module,
  {
  }, function(module, exports, DEFS, require) {

exports.defaultable_example = DEFS.value || 'Defaultable dependency example';

}) // defaultable


text:
using System;
using Umbraco.Core.Models.Entities;

namespace Umbraco.Core.Models.Membership
{
    /// <summary>
    /// Defines the base contract for <see cref="IMember"/> and <see cref="IUser"/>
    /// </summary>
    public interface IMembershipUser : IEntity
    {
        object ProviderUserKey { get; set; }
        string Username { get; set; }
        string Email { get; set; }

        /// <summary>
        /// Gets or sets the raw password value
        /// </summary>
        string RawPasswordValue { get; set; }

        string PasswordQuestion { get; set; }

        /// <summary>
        /// Gets or sets the raw password answer value
        /// </summary>
        string RawPasswordAnswerValue { get; set; }

        string Comments { get; set; }
        bool IsApproved { get; set; }
        bool IsLockedOut { get; set; }
        DateTime LastLoginDate { get; set; }
        DateTime LastPasswordChangeDate { get; set; }
        DateTime LastLockoutDate { get; set; }

        /// <summary>
        /// Gets or sets the number of failed password attempts.
        /// This is the number of times the password was entered incorrectly upon login.
        /// </summary>
        /// <remarks>
        /// Alias: umbracoMemberFailedPasswordAttempts
        /// Part of the standard properties collection.
        /// </remarks>
        int FailedPasswordAttempts { get; set; }

        //object ProfileId { get; set; }
        //IEnumerable<object> Groups { get; set; }
    }
}


text:
class Trade::PermitMatcher
  attr_accessor :page, :per_page

  def initialize(options)
    initialize_options(options)
    initialize_query
  end

  def results
    @query.limit(@per_page).offset(@per_page * (@page - 1)).to_a
  end

  def total_cnt
    @query.count
  end

  private

  def initialize_options(options)
    @page = options[:page] || 1
    @per_page = 25
    @permit_query = options[:permit_query] &&
      sanitize_permit_query(options[:permit_query])
  end

  def initialize_query
    @query = Trade::Permit.order(:number)
    if @permit_query
      @query = @query.where([
        "UPPER(number) LIKE :number", :number => "#{@permit_query}%"
      ])
    end
  end

  def sanitize_permit_query(query)
    # negative limit does not suppress trailing nulls
    query_parts = query.upcase.strip.split('%', -1).map do |qp|
      if qp.blank?
        '%' # replace the wildcard
      else
        ActiveRecord::Base.connection.quote_string(qp)
      end
    end
    query_parts.join
  end

end


text:
package com.sun.org.omg.SendingContext;

/**
* com/sun/org/omg/SendingContext/CodeBaseHelper.java
* Generated by the IDL-to-Java compiler (portable), version "3.0"
* from rt.idl
* Thursday, May 6, 1999 1:52:08 AM PDT
*/

public final class CodeBaseHelper
{
    private static String  _id = "IDL:omg.org/SendingContext/CodeBase:1.0";

    public CodeBaseHelper()
    {
    }

    public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.SendingContext.CodeBase that)
    {
        org.omg.CORBA.portable.OutputStream out = a.create_output_stream ();
        a.type (type ());
        write (out, that);
        a.read_value (out.create_input_stream (), type ());
    }

    public static com.sun.org.omg.SendingContext.CodeBase extract (org.omg.CORBA.Any a)
    {
        return read (a.create_input_stream ());
    }

    private static org.omg.CORBA.TypeCode __typeCode = null;
    synchronized public static org.omg.CORBA.TypeCode type ()
    {
        if (__typeCode == null)
            {
                __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (com.sun.org.omg.SendingContext.CodeBaseHelper.id (), "CodeBase");
            }
        return __typeCode;
    }

    public static String id ()
    {
        return _id;
    }

    public static com.sun.org.omg.SendingContext.CodeBase read (org.omg.CORBA.portable.InputStream istream)
    {
        return narrow (istream.read_Object (_CodeBaseStub.class));
    }

    public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.SendingContext.CodeBase value)
    {
        ostream.write_Object ((org.omg.CORBA.Object) value);
    }

    public static com.sun.org.omg.SendingContext.CodeBase narrow (org.omg.CORBA.Object obj)
    {
        if (obj == null)
            return null;
        else if (obj instanceof com.sun.org.omg.SendingContext.CodeBase)
            return (com.sun.org.omg.SendingContext.CodeBase)obj;
        else if (!obj._is_a (id ()))
            throw new org.omg.CORBA.BAD_PARAM ();
        else
            {
                org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate ();
                return new com.sun.org.omg.SendingContext._CodeBaseStub (delegate);
            }
    }

}


text:
A collection of useful Jekyll plugins. To use any of these plugins in your application, add the `.rb` file to your `_plugins` directory.

### liquify

[See filter >>](plugins/liquify.rb)

This is a really useful filter. It will parse liquid syntax after the initial render cycle. This is particularly useful if you want to use liquid syntax in front matter. For example, you have a file, landing.md:

```
# _config.yml

year: 2017
```

```
# landing.md

---
title: landing
layout: landing
description: "I want to make this dynamic and inherit the {{ site.year }} from the 'landing' layout"
---

<h1>{{ page.title }}</h1>
<p>{{ page.description | liquify }}</p>
```

### debug
[See filter >>](plugins/debug.rb)

This is a debugging filter that can be used to inspect underlying data. Make sure that you have the `pry` and `rb-readline` gems installed before you use this plugin. You will also need to restart your server after testing the filter.

Use in a few ways:
```
{{ data | debug }}

{% assign new_data = data | debug %}
```

### shuffle
[See filter >>](plugins/shuffle.rb)

This filter takes an array, randomly shuffles it, and returns the shuffled array.

```
{% assign array = "1,2,3,4" | split:"," %}
{% assign shuffled_array = array | shuffle %}

{{ array }}
>> 1234
{{ shuffled_array }}
>> 1342
{{ shuffled_array }}
>> 2341
```


text:
package noisyninja.com.marvelcharacterlibrary;

import junit.framework.Test;
import junit.framework.TestSuite;

import org.junit.runner.RunWith;
import org.junit.runners.AllTests;
import org.junit.runners.Suite;

/**
 * Suite contains all unit tests
 * Created by ir2pid on 18/03/16.
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({
        EndpointMD5Tests.class,
        GsonSerializeDeserializeTests.class
})
public class AllUnitTestSuite {

}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/network/onc/onc_certificate_importer.h"

#include <cert.h>
#include <certdb.h>
#include <keyhi.h>
#include <pk11pub.h>
#include <string>

#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/values.h"
#include "chromeos/network/onc/onc_constants.h"
#include "chromeos/network/onc/onc_test_utils.h"
#include "crypto/nss_util.h"
#include "net/base/cert_type.h"
#include "net/base/crypto_module.h"
#include "net/base/nss_cert_database.h"
#include "net/base/x509_certificate.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace chromeos {
namespace onc {

#if defined(USE_NSS)
// In NSS 3.13, CERTDB_VALID_PEER was renamed CERTDB_TERMINAL_RECORD. So we use
// the new name of the macro.
#if !defined(CERTDB_TERMINAL_RECORD)
#define CERTDB_TERMINAL_RECORD CERTDB_VALID_PEER
#endif

net::CertType GetCertType(net::X509Certificate::OSCertHandle cert) {
  CERTCertTrust trust = {0};
  CERT_GetCertTrust(cert, &trust);

  unsigned all_flags = trust.sslFlags | trust.emailFlags |
      trust.objectSigningFlags;

  if (cert->nickname && (all_flags & CERTDB_USER))
    return net::USER_CERT;
  if ((all_flags & CERTDB_VALID_CA) || CERT_IsCACert(cert, NULL))
    return net::CA_CERT;
  // TODO(mattm): http://crbug.com/128633.
  if (trust.sslFlags & CERTDB_TERMINAL_RECORD)
    return net::SERVER_CERT;
  return net::UNKNOWN_CERT;
}
#else
net::CertType GetCertType(net::X509Certificate::OSCertHandle cert) {
  NOTIMPLEMENTED();
  return net::UNKNOWN_CERT;
}
#endif  // USE_NSS

class ONCCertificateImporterTest : public testing::Test {
 public:
  virtual void SetUp() {
    ASSERT_TRUE(test_nssdb_.is_open());

    slot_ = net::NSSCertDatabase::GetInstance()->GetPublicModule();

    // Don't run the test if the setup failed.
    ASSERT_TRUE(slot_->os_module_handle());

    // Test db should be empty at start of test.
    EXPECT_EQ(0ul, ListCertsInSlot(slot_->os_module_handle()).size());
  }

  virtual void TearDown() {
    EXPECT_TRUE(CleanupSlotContents(slot_->os_module_handle()));
    EXPECT_EQ(0ul, ListCertsInSlot(slot_->os_module_handle()).size());
  }

  virtual ~ONCCertificateImporterTest() {}

 protected:
  void AddCertificateFromFile(std::string filename,
                              net::CertType expected_type,
                              std::string* guid) {
    scoped_ptr<base::DictionaryValue> onc =
        test_utils::ReadTestDictionary(filename);
    base::ListValue* certificates = NULL;
    onc->GetListWithoutPathExpansion(toplevel_config::kCertificates,
                                     &certificates);

    base::DictionaryValue* certificate = NULL;
    certificates->GetDictionary(0, &certificate);
    certificate->GetStringWithoutPathExpansion(certificate::kGUID, guid);

    CertificateImporter importer(true /* allow web trust */);
    EXPECT_EQ(CertificateImporter::IMPORT_OK,
              importer.ParseAndStoreCertificates(*certificates));

    net::CertificateList result_list;
    CertificateImporter::ListCertsWithNickname(*guid, &result_list);
    ASSERT_EQ(1ul, result_list.size());
    EXPECT_EQ(expected_type, GetCertType(result_list[0]->os_cert_handle()));
  }

  scoped_refptr<net::CryptoModule> slot_;

 private:
  net::CertificateList ListCertsInSlot(PK11SlotInfo* slot) {
    net::CertificateList result;
    CERTCertList* cert_list = PK11_ListCertsInSlot(slot);
    for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list);
         !CERT_LIST_END(node, cert_list);
         node = CERT_LIST_NEXT(node)) {
      result.push_back(net::X509Certificate::CreateFromHandle(
          node->cert, net::X509Certificate::OSCertHandles()));
    }
    CERT_DestroyCertList(cert_list);

    // Sort the result so that test comparisons can be deterministic.
    std::sort(result.begin(), result.end(), net::X509Certificate::LessThan());
    return result;
  }

  bool CleanupSlotContents(PK11SlotInfo* slot) {
    bool ok = true;
    net::CertificateList certs = ListCertsInSlot(slot);
    for (size_t i = 0; i < certs.size(); ++i) {
      if (!net::NSSCertDatabase::GetInstance()->DeleteCertAndKey(certs[i]))
        ok = false;
    }
    return ok;
  }

  crypto::ScopedTestNSSDB test_nssdb_;
};

TEST_F(ONCCertificateImporterTest, AddClientCertificate) {
  std::string guid;
  AddCertificateFromFile("certificate-client.onc", net::USER_CERT, &guid);

  SECKEYPrivateKeyList* privkey_list =
      PK11_ListPrivKeysInSlot(slot_->os_module_handle(), NULL, NULL);
  EXPECT_TRUE(privkey_list);
  if (privkey_list) {
    SECKEYPrivateKeyListNode* node = PRIVKEY_LIST_HEAD(privkey_list);
    int count = 0;
    while (!PRIVKEY_LIST_END(node, privkey_list)) {
      char* name = PK11_GetPrivateKeyNickname(node->key);
      EXPECT_STREQ(guid.c_str(), name);
      PORT_Free(name);
      count++;
      node = PRIVKEY_LIST_NEXT(node);
    }
    EXPECT_EQ(1, count);
    SECKEY_DestroyPrivateKeyList(privkey_list);
  }

  SECKEYPublicKeyList* pubkey_list =
      PK11_ListPublicKeysInSlot(slot_->os_module_handle(), NULL);
  EXPECT_TRUE(pubkey_list);
  if (pubkey_list) {
    SECKEYPublicKeyListNode* node = PUBKEY_LIST_HEAD(pubkey_list);
    int count = 0;
    while (!PUBKEY_LIST_END(node, pubkey_list)) {
      count++;
      node = PUBKEY_LIST_NEXT(node);
    }
    EXPECT_EQ(1, count);
    SECKEY_DestroyPublicKeyList(pubkey_list);
  }
}

TEST_F(ONCCertificateImporterTest, AddServerCertificate) {
  std::string guid;
  AddCertificateFromFile("certificate-server.onc", net::SERVER_CERT, &guid);

  SECKEYPrivateKeyList* privkey_list =
      PK11_ListPrivKeysInSlot(slot_->os_module_handle(), NULL, NULL);
  EXPECT_FALSE(privkey_list);

  SECKEYPublicKeyList* pubkey_list =
      PK11_ListPublicKeysInSlot(slot_->os_module_handle(), NULL);
  EXPECT_FALSE(pubkey_list);
}

TEST_F(ONCCertificateImporterTest, AddWebAuthorityCertificate) {
  std::string guid;
  AddCertificateFromFile("certificate-web-authority.onc", net::CA_CERT, &guid);

  SECKEYPrivateKeyList* privkey_list =
      PK11_ListPrivKeysInSlot(slot_->os_module_handle(), NULL, NULL);
  EXPECT_FALSE(privkey_list);

  SECKEYPublicKeyList* pubkey_list =
      PK11_ListPublicKeysInSlot(slot_->os_module_handle(), NULL);
  EXPECT_FALSE(pubkey_list);
}

class ONCCertificateImporterTestWithParam :
      public ONCCertificateImporterTest,
      public testing::WithParamInterface<
          std::pair<net::CertType, std::pair<const char*, const char*> > > {
 protected:
  net::CertType GetCertTypeParam() {
    return GetParam().first;
  }

  std::string GetOriginalFilename() {
    return GetParam().second.first;
  }

  std::string GetUpdatedFilename() {
    return GetParam().second.second;
  }
};

TEST_P(ONCCertificateImporterTestWithParam, UpdateCertificate) {
  // First we import a certificate.
  {
    SCOPED_TRACE("Import original certificate");
    std::string guid_original;
    AddCertificateFromFile(GetOriginalFilename(), GetCertTypeParam(),
                           &guid_original);
  }

  // Now we import the same certificate with a different GUID. The cert should
  // be retrievable via the new GUID.
  {
    SCOPED_TRACE("Import updated certificate");
    std::string guid_updated;
    AddCertificateFromFile(GetUpdatedFilename(), GetCertTypeParam(),
                           &guid_updated);
  }
}

TEST_P(ONCCertificateImporterTestWithParam, ReimportCertificate) {
  // Verify that reimporting a client certificate works.
  for (int i = 0; i < 2; ++i) {
    SCOPED_TRACE("Import certificate, iteration " + base::IntToString(i));

    std::string guid_original;
    AddCertificateFromFile(GetOriginalFilename(), GetCertTypeParam(),
                           &guid_original);
  }
}

INSTANTIATE_TEST_CASE_P(
    ONCCertificateImporterTestWithParam,
    ONCCertificateImporterTestWithParam,
    ::testing::Values(
        std::make_pair(net::USER_CERT,
                       std::make_pair("certificate-client.onc",
                                      "certificate-client-update.onc")),
        std::make_pair(net::SERVER_CERT,
                       std::make_pair("certificate-server.onc",
                                      "certificate-server-update.onc")),
        std::make_pair(
            net::CA_CERT,
            std::make_pair("certificate-web-authority.onc",
                           "certificate-web-authority-update.onc"))));

}  // namespace onc
}  // namespace chromeos


text:
package com.amazonaws.services.simplesystemsmanagement.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.simplesystemsmanagement.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * ParametersFilterMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ParametersFilterMarshaller {

    private static final MarshallingInfo<String> KEY_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Key").build();
    private static final MarshallingInfo<List> VALUES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Values").build();

    private static final ParametersFilterMarshaller instance = new ParametersFilterMarshaller();

    public static ParametersFilterMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(ParametersFilter parametersFilter, ProtocolMarshaller protocolMarshaller) {

        if (parametersFilter == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(parametersFilter.getKey(), KEY_BINDING);
            protocolMarshaller.marshall(parametersFilter.getValues(), VALUES_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package net.wouto.modelsync.mongo;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import static com.mongodb.client.model.Filters.eq;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.mongodb.util.JSON;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.wouto.modelsync.mongo.annotations.DBSync;
import net.wouto.modelsync.mongo.callbacks.DeleteCallback;
import net.wouto.modelsync.mongo.callbacks.DocumentWriteCallback;
import net.wouto.modelsync.mongo.callbacks.FindAndUpdateCallback;
import net.wouto.modelsync.mongo.callbacks.LoadMultiCallback;
import net.wouto.modelsync.mongo.callbacks.MultiReadCallback;
import net.wouto.modelsync.mongo.callbacks.ReadCallback;
import net.wouto.modelsync.mongo.callbacks.UpdateCallback;
import net.wouto.modelsync.mongo.query.Query;
import net.wouto.modelsync.mongo.sync.ObjectLoadedCallback;
import net.wouto.modelsync.mongo.update.Update;
import org.apache.commons.lang.ClassUtils;
import org.bson.Document;

public class SimpleCollection {

    private SimpleScheduler scheduler;
    private MongoCollection collection;

    public SimpleCollection(SimpleScheduler scheduler, MongoCollection collection) {
        this.scheduler = scheduler;
        this.collection = collection;
    }

    public UpdateResult updateSync(Query q, Update u) throws Exception {
        return this.collection.updateOne((Document) q.getQuery(), (Document) u.getUpdateQuery());
    }

    public void update(Query q, Update u) {
        this.update(q, u, null);
    }

    public void update(final Query q, final Update u, final UpdateCallback callback) {
        this.scheduler.doWrite(new Runnable() {

            @Override
            public void run() {
                try {
                    UpdateResult wr = SimpleCollection.this.updateSync(q, u);
                    if (callback != null) {
                        callback.onQueryDone(wr, null);
                    }
                } catch (Exception ex) {
                    if (callback != null) {
                        callback.onQueryDone(null, ex);
                    }
                }
            }

        });
    }

    public UpdateResult updateSync(Query q, Update u, boolean upsert, boolean multi) throws Exception {
        UpdateOptions options = new UpdateOptions();
        options.upsert(upsert);
        if (multi) {
            return this.collection.updateMany((Document) q.getQuery(), (Document) u.getUpdateQuery(), options);
        } else {
            return this.collection.updateOne((Document) q.getQuery(), (Document) u.getUpdateQuery(), options);
        }
    }

    public void update(Query q, Update u, boolean upsert, boolean multi) {
        this.update(q, u, upsert, multi, null);
    }

    public void update(final Query q, final Update u, final boolean upsert, final boolean multi, final UpdateCallback callback) {
        this.scheduler.doWrite(new Runnable() {

            @Override
            public void run() {
                try {
                    UpdateResult wr = SimpleCollection.this.updateSync(q, u, upsert, multi);
                    if (callback != null) {
                        callback.onQueryDone(wr, null);
                    }
                } catch (Exception ex) {
                    if (callback != null) {
                        callback.onQueryDone(null, ex);
                    }
                }
            }

        });
    }

    public UpdateResult updateOrInsertSync(String key, Object value, Update set) throws Exception {
        UpdateOptions u = new UpdateOptions();
        u.upsert(true);
        return this.collection.replaceOne(eq(key, value), (Document) set.getUpdateQuery(), u);
    }

    public void updateOrInsert(String key, Object value, Update set) {
        this.updateOrInsert(key, value, set, null);
    }

    public void updateOrInsert(final String key, final Object value, final Update set, final UpdateCallback callback) {
        this.scheduler.doWrite(new Runnable() {

            @Override
            public void run() {
                try {
                    UpdateResult wr = SimpleCollection.this.updateOrInsertSync(key, value, set);
                    if (callback != null) {
                        callback.onQueryDone(wr, null);
                    }
                } catch (Exception ex) {
                    if (callback != null) {
                        callback.onQueryDone(null, ex);
                    }
                }
            }

        });
    }

    public void insertSync(Document obj) throws Exception {
        this.collection.insertOne(obj);
    }

    public void insert(Document obj) {
        this.insert(obj, null);
    }

    public void insert(final Document obj, final DocumentWriteCallback callback) {
        this.scheduler.doWrite(new Runnable() {

            @Override
            public void run() {
                try {
                    SimpleCollection.this.insertSync(obj);
                    if (callback != null) {
                        callback.onQueryDone(obj, null);
                    }
                } catch (Exception ex) {
                    if (callback != null) {
                        callback.onQueryDone(null, ex);
                    }
                }
            }

        });
    }

    public Document findOneSync(Query q) throws Exception {
        MongoCursor cursor = this.collection.find((Document) q.getQuery()).iterator();
        Object o = cursor.next();
        if (o == null) {
            return null;
        }
        return (Document) o;
    }

    public void findOne(final Query q, final ReadCallback callback) {
        this.scheduler.doRead(new Runnable() {

            @Override
            public void run() {
                try {
                    Document d = SimpleCollection.this.findOneSync(q);
                    if (callback != null) {
                        callback.onQueryDone(d, null);
                    }
                } catch (Exception ex) {
                    if (callback != null) {
                        callback.onQueryDone(null, ex);
                    }
                }
            }

        });
    }

    public MongoCursor findSync(Query q) throws Exception {
        return this.collection.find((Document) q.getQuery()).iterator();
    }

    public void find(final Query q, final MultiReadCallback callback) {
        this.scheduler.doRead(new Runnable() {

            @Override
            public void run() {
                try {
                    MongoCursor c = SimpleCollection.this.findSync(q);
                    List<Document> data = new ArrayList();
                    while (c.hasNext()) {
                        data.add((Document) c.next());
                    }
                    if (callback != null) {
                        callback.onQueryDone(data.toArray(new Document[data.size()]), null);
                    }
                } catch (Exception ex) {
                    if (callback != null) {
                        callback.onQueryDone(null, ex);
                    }
                }
            }

        });
    }

    public Document findOneAndRemoveSync(Query q) throws Exception {
        Object o = this.collection.findOneAndDelete((Document) q.getQuery());
        if (o == null) {
            return null;
        }
        return (Document) o;
    }

    public void findAndRemove(final Query q, final ReadCallback callback) {
        this.scheduler.doWrite(new Runnable() {

            @Override
            public void run() {
                try {
                    Document obj = SimpleCollection.this.findOneAndRemoveSync(q);
                    if (callback != null) {
                        callback.onQueryDone(obj, null);
                    }
                } catch (Exception ex) {
                    if (callback != null) {
                        callback.onQueryDone(null, ex);
                    }
                }
            }

        });
    }

    public DeleteResult removeSync(Query q) throws Exception {
        return this.collection.deleteMany((Document) q.getQuery());
    }

    public void remove(Query q) {
        this.remove(q, null);
    }

    public void remove(final Query q, final DeleteCallback callback) {
        this.scheduler.doWrite(new Runnable() {

            @Override
            public void run() {
                try {
                    DeleteResult wr = SimpleCollection.this.removeSync(q);
                    if (callback != null) {
                        callback.onQueryDone(wr, null);
                    }
                } catch (Exception ex) {
                    if (callback != null) {
                        callback.onQueryDone(null, ex);
                    }
                }
            }

        });
    }

    public <T> T[] loadAllSync(Class<T> c) throws Exception {
        Constructor constructor = c.getDeclaredConstructor();
        boolean cAccess = constructor.isAccessible();
        if (!cAccess) {
            constructor.setAccessible(true);
        }
        MongoCursor cursor = this.findSync(Query.empty);
        ArrayList<T> data = new ArrayList();
        while (cursor.hasNext()) {
            Document obj = (Document) JSON.parse(((Document) cursor.next()).toJson());
            T instance = (T) constructor.newInstance();
            SimpleCollection.this.fromDBObject(instance, obj);
            data.add(instance);
        }
        constructor.setAccessible(cAccess);
        return (T[]) data.toArray((T[]) Array.newInstance(c, data.size()));
    }

    public <T> void loadAll(final Class<T> c, final LoadMultiCallback callback) {
        this.scheduler.doRead(new Runnable() {
            @Override
            public void run() {
                try {
                    T[] t = SimpleCollection.this.loadAllSync(c);
                    if (callback != null) {
                        callback.onQueryDone(t, null);
                    }
                } catch (Exception ex) {
                    if (callback != null) {
                        callback.onQueryDone(null, ex);
                    }
                }
            }
        });
    }

    private static Collection<Field> getAnnotationFields(Class<?> clazz, Class<? extends Annotation> a) {
        List<Field> fields = new ArrayList();
        while (clazz != null && clazz != Object.class) {
            Field[] fs = clazz.getDeclaredFields();
            for (Field f : fs) {
                if (f.isAnnotationPresent(a)) {
                    fields.add(f);
                }
            }
            clazz = clazz.getSuperclass();
        }
        return fields;
    }

    private static final Set<Class<?>> primitives = new HashSet<Class<?>>() {
        {
            add(Boolean.class);
            add(Character.class);
            add(Byte.class);
            add(Short.class);
            add(Integer.class);
            add(Long.class);
            add(Float.class);
            add(Double.class);
            add(Object.class);
            add(String.class);
        }
    };

    private static Class<?> getCollectionType(Field f) {
        return (Class<?>) ((ParameterizedType) f.getGenericType()).getActualTypeArguments()[0];
    }

    private static Class<?> getArrayType(Field f) {
        return f.getType().getComponentType();
    }

    private static boolean isSerializeAble(Field f) {
        Class<?> type = f.getType();
        if (type.isArray()) {
            type = type.getComponentType();
        }
        if (Collection.class.isAssignableFrom(f.getType())) {
            type = getCollectionType(f);
        }
        if (isPrimitive(type)) {
            return true;
        }
        return (!getAnnotationFields(type, DBSync.class).isEmpty());
    }

    private static boolean isPrimitive(Class<?> type) {
        if (type.isPrimitive()) {
            return true;
        }
        for (Class<?> p : primitives) {
            if (type.isAssignableFrom(p)) {
                return true;
            }
        }
        return false;
    }

    public static <T> Document asDBObject(T instance) {
        Document b = new Document();
        Collection<Field> fieldMap = getAnnotationFields(instance.getClass(), DBSync.class);
        for (Field f : fieldMap) {
            try {
                DBSync saveData = f.getAnnotation(DBSync.class);
                if (saveData == null) {
                    continue;
                }
                if (!isSerializeAble(f)) {
                    continue;
                }
                boolean hadAccess = f.isAccessible();
                if (!hadAccess) {
                    f.setAccessible(true);
                }
                String fieldName = f.getName();
                if (!saveData.value().isEmpty()) {
                    fieldName = saveData.value();
                }
                if (f.getType().isArray()) { // array
                    Object[] arrayData = (Object[]) f.get(instance);
                    Class<?> arrayType = getArrayType(f);
                    if (isPrimitive(arrayType)) {
                        b.put(fieldName, f.get(instance));
                        f.setAccessible(hadAccess);
                        continue;
                    } else {
                        ArrayList list = new ArrayList();
                        for (Object arrayObject : arrayData) {
                            list.add(asDBObject(arrayObject));
                        }
                        b.put(fieldName, list);
                        f.setAccessible(hadAccess);
                        continue;
                    }
                } else if (Collection.class.isAssignableFrom(f.getType())) { // Collection
                    Collection collectionData = (Collection) f.get(instance);
                    Class<?> collectionType = getCollectionType(f);
                    if (isPrimitive(collectionType)) {
                        b.put(fieldName, f.get(instance));
                        f.setAccessible(hadAccess);
                        continue;
                    } else {
                        ArrayList list = new ArrayList();
                        for (Object collectionObject : collectionData) {
                            Document collectionDBObject = asDBObject(collectionType.cast(collectionObject));
                            list.add(collectionDBObject);
                        }
                        b.put(fieldName, list);
                        f.setAccessible(hadAccess);
                        continue;
                    }
                } else if (!isPrimitive(f.getType())) {
                    Document data = asDBObject(f.get(instance));
                    b.put(fieldName, data);
                    f.setAccessible(hadAccess);
                    continue;
                }
                Object o = f.get(instance);
                f.setAccessible(hadAccess);
                b.put(fieldName, o);
            } catch (IllegalAccessException | IllegalArgumentException ex) {
                ex.printStackTrace();
            }
        }
        return b;
    }

    public final <T> void save(T instance) {
        Document obj = asDBObject(instance);
        Collection<Field> fields = getAnnotationFields(instance.getClass(), DBSync.class);
        String key = null;
        Object value = null;
        for (Field f : fields) {
            if (f.getAnnotation(DBSync.class).index()) {
                key = f.getName();
                value = obj.get(f.getName());
                break;
            }
        }
        if (key == null && value == null) {
            System.out.println("Cannot save object: " + instance.getClass().getName());
            return;
        }
        Update update = new Update(obj);
        this.updateOrInsert(key, value, update, new UpdateCallback() {

            @Override
            public void onQueryDone(UpdateResult result, Exception err) {
                if (err != null) {
                    err.printStackTrace();
                }
            }

        });
    }

    private <T> T instantiate(Class<T> cls) throws Exception {
        final Constructor<T> constr = (Constructor<T>) cls.getConstructors()[0];
        boolean a = constr.isAccessible();
        if (!a) {
            constr.setAccessible(true);
        }
        final List<Object> params = new ArrayList();
        for (Class<?> pType : constr.getParameterTypes()) {
            if (pType.isPrimitive() || primitives.contains(pType)) {
                if (pType.isPrimitive()) {
                    pType = ClassUtils.primitiveToWrapper(pType);
                }
                if (pType == Integer.class ||
                        pType == Long.class ||
                        pType == Short.class ||
                        pType == Byte.class) {
                    params.add(pType.cast(0));
                } else if (pType == Character.class) {
                    params.add('\0');
                } else if (pType == Boolean.class) {
                    params.add(false);
                } else if (pType == Float.class || pType == Double.class) {
                    params.add(pType.cast(0.0));
                } else if (pType == Object.class || pType == String.class) {
                    params.add(null);
                }
            } else {
                params.add(null);
            }
        }
        final T instance = constr.newInstance(params.toArray());
        constr.setAccessible(a);
        return instance;
    }

    public <T> T fromDBObject(Class<T> type, Document data) {
        try {
            T obj = (T) instantiate(type);
            return fromDBObject(obj, data);
        } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
            Logger.getLogger(SimpleCollection.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(SimpleCollection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public <T> T fromDBObject(T instance, Document data) {
        Collection<Field> fields = getAnnotationFields(instance.getClass(), DBSync.class);
        for (Field f : fields) {
            DBSync load = f.getAnnotation(DBSync.class);
            if (load == null) {
                continue;
            }
            String varName = f.getName();
            if (!load.value().isEmpty()) {
                varName = load.value();
            }
            if (!data.containsKey(varName)) {
                continue;
            }
            boolean accessible = f.isAccessible();
            if (!accessible) {
                f.setAccessible(true);
            }
            if (f.getType().isArray()) { // array
                // unsupported? ;s - reflection doesn't allow this
                /*
                Class<?> arrayType = getArrayType(f);
                if (isPrimitive(arrayType)) {
                    try {
                        f.set(instance, data.get(varName));
                    } catch (IllegalArgumentException | IllegalAccessException ex) {
                        Logger.getLogger(SimpleCollection.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    f.setAccessible(accessible);
                    continue;
                }
                ArrayList arrayData = (ArrayList) data.get(varName);
                Collection arrayResult = new ArrayList();
                for (Object arrayObject : arrayData) {
                    Document arrayObjectDB = (Document) arrayObject;
                    Object arrayObjectOutput = fromDBObject(arrayType, arrayObjectDB);
                    arrayResult.add(arrayObjectOutput);
                }
                try {
                    f.set(instance, arrayResult.toArray((f.getType().cast(Array.newInstance(f.getType(), arrayResult.size()))));
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                    Logger.getLogger(SimpleCollection.class.getName()).log(Level.SEVERE, null, ex);
                }
                f.setAccessible(accessible); */
                continue;
            } else if (Collection.class.isAssignableFrom(f.getType())) { // collection
                Class<?> collectionType = getCollectionType(f);
                if (isPrimitive(collectionType)) {
                    try {
                        f.set(instance, data.get(varName));
                    } catch (IllegalArgumentException | IllegalAccessException ex) {
                        Logger.getLogger(SimpleCollection.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    f.setAccessible(accessible);
                    continue;
                }
                ArrayList collectionData = (ArrayList) data.get(varName);
                Collection collectionResult = new ArrayList();
                for (Object collectionObject : collectionData) {
                    Document collectionObjectDB = (Document) collectionObject;
                    Object collectionObjectOutput = fromDBObject(collectionType, collectionObjectDB);
                    collectionResult.add(collectionObjectOutput);
                }
                try {
                    f.set(instance, collectionResult);
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                    Logger.getLogger(SimpleCollection.class.getName()).log(Level.SEVERE, null, ex);
                }
                f.setAccessible(accessible);
                continue;
            } else if (!isPrimitive(f.getType())) {
                Object o = fromDBObject(f.getType(), (Document) data.get(varName));
                try {
                    f.set(instance, o);
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                    Logger.getLogger(SimpleCollection.class.getName()).log(Level.SEVERE, null, ex);
                }
                f.setAccessible(accessible);
                continue;
            }
            Object o = data.get(varName);
            try {
                f.set(instance, o);
            } catch (IllegalAccessException | IllegalArgumentException ex) {
                Logger.getLogger(SimpleCollection.class.getName()).log(Level.SEVERE, null, ex);
            }
            f.setAccessible(accessible);
        }
        return instance;
    }

    public final <T> void load(T instance) {
        this.load(instance, null);
    }

    public final <T> void load(final T instance, final ObjectLoadedCallback callback) {
        Field[] fields = instance.getClass().getDeclaredFields();
        Query q = new Query();
        final Class<?> cast = instance.getClass();
        boolean exc = true;
        for (Field f : fields) {
            try {
                if (!f.isAnnotationPresent(DBSync.class)) {
                    continue;
                }
                DBSync saveData = f.getAnnotation(DBSync.class);
                boolean access = f.isAccessible();
                if (!access) {
                    f.setAccessible(access);
                }
                String varName = f.getName();
                if (!saveData.value().isEmpty()) {
                    varName = saveData.value();
                }
                if (saveData.index()) {
                    Object value = f.get(instance);
                    if (varName != null && value != null) {
                        q.append(Query.equals(varName, value));
                        exc = false;
                    }
                }
                f.setAccessible(access);
            } catch (IllegalAccessException | IllegalArgumentException ex) {
                ex.printStackTrace();
            }
        }
        if (exc) {
            System.out.println("No indexes set to query instance of " + instance.getClass().getName());
            callback.onObjectLoaded(cast.cast(instance));
            return;
        }
        this.findOne(q, new ReadCallback() {

            @Override
            public void onQueryDone(Document result, Exception err) {
                if (err != null) {
                    err.printStackTrace();
                } else if (result != null) {
                    SimpleCollection.this.fromDBObject(instance, result);
                    callback.onObjectLoaded(cast.cast(instance));
                } else {
                    System.out.println("Failed loading data for " + instance.getClass().getName());
                }
            }

        });
    }

    public Document findAndUpdateSync(Query q, Update u) {
        Document result = (Document) this.collection.findOneAndUpdate((Document) q.getQuery(), (Document) u.getUpdateQuery());
        return result;
    }

    public void findAndUpdate(final Query q, final Update u, final FindAndUpdateCallback callback) {
        this.scheduler.doWrite(new Runnable() {

            @Override
            public void run() {
                try {
                    Document d = SimpleCollection.this.findAndUpdateSync(q, u);
                    if (callback != null) {
                        callback.onQueryDone(d, null);
                    }
                } catch (Exception ex) {
                    if (callback != null) {
                        callback.onQueryDone(null, ex);
                    }
                }
            }

        });
    }

    public MongoCollection getHandle() {
        return this.collection;
    }

}


text:
package ImageManipulator;

import javax.microedition.lcdui.Image;

import net.rim.device.api.math.Fixed32;
import net.rim.device.api.math.VecMath;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.XYDimension;

/**
 * Class for Rotating, Mirroring, and Scaling Bitmaps
 *
 * Supports:
 *

 *
Transformations by angle around 0,0 and mirroring in X and/or Y axis.

 *
Transformation by arbitrary transformation matrix.

 *
Scaling applied independently of any transformation.

 *
Scaling separately in X and Y axis

 *
Results can be painted to a new Bitmap, or directly on any Graphics
 * context

 *

 *
 * @version 1.6 (December 2009)
 */
public class ImageManipulator {

	/**
	 * This bitmap scaling option marks that scaling should proceed without
	 * preserving aspect ratio. The source bitmap is fit to the dimensions of
	 * the destination bitmap. Copied from 5.0 Bitmap API.
	 *
	 *

	 * http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/system/Bitmap.html
	 *

	 *
	 * @since 1.1
	 */
	public static final int SCALE_STRETCH = 0;
	/**
	 * This bitmap scaling option marks that scaling is done with preserving the
	 * aspect ratio. The source bitmap fills the destination bitmap completely
	 * and outstanding parts of the source bitmap are not copied to the
	 * destination bitmap. Copied from 5.0 Bitmap API.
	 *
	 *

	 * http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/system/Bitmap.html
	 *

	 *
	 * @since 1.1
	 */
	public static final int SCALE_TO_FILL = 1;
	/**
	 * This bitmap scaling option marks that scaling is done with preserving the
	 * aspect ratio. The source bitmap is fit to the dimensions of the
	 * destination bitmap and a part of destination bitmap remains unchanged.
	 * Copied from 5.0 Bitmap API.
	 *
	 *

	 * http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/system/Bitmap.html
	 *

	 *
	 * @since 1.1
	 */
	public static final int SCALE_TO_FIT = 2;
	/**
	 * Used for compatibility with 5.0. Has no effect, but the values are
	 * checked.
	 *
	 * @since 1.1
	 */
	public static final int FILTER_LANCZOS = 0;
	/**
	 * Used for compatibility with 5.0. Has no effect, but the values are
	 * checked.
	 *
	 * @since 1.1
	 */
	public static final int FILTER_BOX = 1;
	/**
	 * Used for compatibility with 5.0. Has no effect, but the values are
	 * checked.
	 *
	 * @since 1.1
	 */
	public static final int FILTER_BILINEAR = 2;

	// The image to alter
	private Bitmap bitmap;

	// The graphics context to use
	// if one is not provided, a bitmap will be

	/**
	 * Constants for Matrix locations within a single dimensional array
	 *
	 *

	 * | UX  UY  UZ |
	 * | VX  VY  VZ |
	 * | WX  WY  WZ |
	 *

	 *
	 * @since 1.3
	 */
	public static final int UX = 0;
	/**
	 * Constants for Matrix locations within a single dimensional array
	 *
	 *

	 * | UX  UY  UZ |
	 * | VX  VY  VZ |
	 * | WX  WY  WZ |
	 *

	 *
	 * @since 1.3
	 */
	public static final int UY = 3;
	/**
	 * Constants for Matrix locations within a single dimensional array
	 *
	 *

	 * | UX  UY  UZ |
	 * | VX  VY  VZ |
	 * | WX  WY  WZ |
	 *

	 *
	 * @since 1.3
	 */
	public static final int UZ = 6;
	/**
	 * Constants for Matrix locations within a single dimensional array
	 *
	 *

	 * | UX  UY  UZ |
	 * | VX  VY  VZ |
	 * | WX  WY  WZ |
	 *

	 *
	 * @since 1.3
	 */
	public static final int VX = 1;
	/**
	 * Constants for Matrix locations within a single dimensional array
	 *
	 *

	 * | UX  UY  UZ |
	 * | VX  VY  VZ |
	 * | WX  WY  WZ |
	 *

	 *
	 * @since 1.3
	 */
	public static final int VY = 4;
	/**
	 * Constants for Matrix locations within a single dimensional array
	 *
	 *

	 * | UX  UY  UZ |
	 * | VX  VY  VZ |
	 * | WX  WY  WZ |
	 *

	 *
	 * @since 1.3
	 */
	public static final int VZ = 7;
	/**
	 * Constants for Matrix locations within a single dimensional array
	 *
	 *

	 * | UX  UY  UZ |
	 * | VX  VY  VZ |
	 * | WX  WY  WZ |
	 *

	 *
	 * @since 1.3
	 */
	public static final int WX = 2;
	/**
	 * Constants for Matrix locations within a single dimensional array
	 *
	 *

	 * | UX  UY  UZ |
	 * | VX  VY  VZ |
	 * | WX  WY  WZ |
	 *

	 *
	 * @since 1.3
	 */
	public static final int WY = 5;
	/**
	 * Constants for Matrix locations within a single dimensional array
	 *
	 *

	 * | UX  UY  UZ |
	 * | VX  VY  VZ |
	 * | WX  WY  WZ |
	 *

	 *
	 * @since 1.3
	 */
	public static final int WZ = 8;

	/*
	 * the transform matrix, initialized to identity
	 */
	private int[] transformMatrix = VecMath.IDENTITY_3X3;
	// set scale in X axis
	private int scaleX = Fixed32.ONE;
	// set scale in Y axis
	private int scaleY = Fixed32.ONE;

	// track separate texture origin for non-orthogonal rotations
	private int textureX;
	private int textureY;

	// track whether the rotation a multiple of 90 degrees
	private boolean orthogonal;

	// actual scale factor when applied to pixels
	private int resultantScaleX = Fixed32.ONE;
	private int resultantScaleY = Fixed32.ONE;

	// Initialize the X and Y point arrays
	// These define the resultant image points
	private int[] bitmapXPts = { 0, 0, 0, 0 };
	private int[] bitmapYPts = { 0, 0, 0, 0 };

	// Store the resulting dimensions of the transformation
	private XYDimension transformedRegion = new XYDimension();

	// Flag whether the transformation has been applied
	private boolean transformationApplied;

	// Constant for drawing in "15.16 fixed point format"
	private static final int SHIFT16 = 1 << 16;

	// Set the background color default white
	private int backgroundColor = Color.WHITE;

	// Set default alpha to transparent
	private int backgroundAlpha = 0;

	// static object for use in the static methods
	private static ImageManipulator imageManipulator;

	/**
	 * Scale the provided bitmap
	 *
	 * @param bitmap
	 *            the bitmap to scale
	 * @param scale
	 *            the new scale factor in Fixed32
	 * @return the scaled bitmap
	 * @since 1.1
	 */
	public static Bitmap scale(Bitmap bitmap, int scale) {
		if (imageManipulator == null) {
			imageManipulator = new ImageManipulator(bitmap);
		} else {
			imageManipulator.setBitmap(bitmap);
		}
		imageManipulator.resetTransform();
		imageManipulator.setScale(scale);
		return imageManipulator.transformAndPaintBitmap();
	}

	/**
	 * Rotate the provided Bitmap
	 *
	 * @param bitmap
	 *            the bitmap to rotate
	 * @param angle
	 *            the angle in degrees to rotate, counterclockwise around the
	 *            top left corner.
	 * @return the rotated bitmap
	 * @since 1.1
	 */
	public static Bitmap rotate(Bitmap bitmap, int angle) {
		if (imageManipulator == null) {
			imageManipulator = new ImageManipulator(bitmap);
		} else {
			imageManipulator.setBitmap(bitmap);
		}
		imageManipulator.resetTransform();
		imageManipulator.transformByAngle(angle, false, false);
		return imageManipulator.transformAndPaintBitmap();
	}

	public ImageManipulator(Bitmap image) {
		bitmap = image;
	}

	/**
	 * Reset the transformation to the identity: No rotation and Scale is 1.0
	 *
	 * @since 1.1
	 */
	public void resetTransform() {
		transformByMatrix(Fixed32.ONE, 0, 0, Fixed32.ONE);
		orthogonal = true;
		setScale(Fixed32.ONE);
		transformationApplied = false;
	}

	/**
	 * Setup the given transformation matrix, given the cosine and sine values,
	 * and mirroring options
	 *
	 * @param matrix
	 *            the transform matrix, must be of size 4
	 * @param cos
	 *            cosine of the angle in radians
	 * @param sin
	 *            sine of the angle in radians
	 * @param mirrorX
	 *            to mirror in the X axis
	 * @param mirrorY
	 *            to mirror in the Y axis
	 */
	private void setTransform(int[] matrix, int cos, int sin, boolean mirrorX, boolean mirrorY) {
		// default, non mirrored transformation
		matrix[UX] = cos;
		matrix[UY] = -sin;
		matrix[VX] = sin;
		matrix[VY] = cos;
		if (mirrorY) {
			matrix[UX] = -cos;
			matrix[UY] = sin;
		}
		if (mirrorX) {
			matrix[VX] = -sin;
			matrix[VY] = -cos;
		}
	}

	/**
	 * Rotate the image about an angle and/or mirror about an axis
	 *
	 * @param angle
	 *            the angle in degrees, postive rotates counterclockwise
	 * @param mirrorX
	 *            true to mirror in the X axis
	 * @param mirrorY
	 *            true to mirror in the Y axis
	 */
	public void transformByAngle(int angle, boolean mirrorX, boolean mirrorY) {
		if (angle % 90 == 0) {
			orthogonal = true;
		} else {
			orthogonal = false;
		}
		angle = Fixed32.toFP(angle);
		int cos = Fixed32.cosd(angle);
		int sin = Fixed32.sind(angle);
		setTransform(transformMatrix, cos, sin, mirrorX, mirrorY);
		transformationApplied = false;
	}

	/**
	 * Rotate the image using a custom transformation matrix. The matrix takes
	 * the form:
	 *
	 *

	 * | ux  uy 0 |
	 * | vx  vy 0 |
	 * | 0   0  1 |
	 *

	 *
	 * Where, the identity (matrix that does no rotation) is:
	 *
	 *

	 * | 1  0  0 |
	 * | 0  1  0 |
	 * | 0  0  1 |
	 *

	 *
	 * @param ux
	 *            in Fixed32 format (15.16)
	 * @param uy
	 *            in Fixed32 format (15.16)
	 * @param vx
	 *            in Fixed32 format (15.16)
	 * @param vy
	 *            in Fixed32 format (15.16)
	 */
	public void transformByMatrix(int ux, int uy, int vx, int vy) {
		transformMatrix[UX] = ux;
		transformMatrix[UY] = uy;
		transformMatrix[VX] = vx;
		transformMatrix[VY] = vy;
		orthogonal = false; // not completely accurate
		transformationApplied = false;
	}

	/**
	 * Applies the transformation matrix and scaling to the region defined by
	 * the bitmap. Uses the parameters given in the setter methods and applies
	 * to the internal region.
	 *
	 * Called by the transformAndPaintBitmap methods before painting.
	 */
	public void applyTransformation() {

		// Check if this is necessary
		if (transformationApplied) {
			return;
		}

		int bitmapRight = Fixed32.toFP(bitmap.getWidth());
		int bitmapBottom = Fixed32.toFP(bitmap.getHeight());

		// scale the image size as requested
		bitmapRight = Fixed32.mul(bitmapRight, scaleX);
		bitmapBottom = Fixed32.mul(bitmapBottom, scaleY);

		// init matrix
		bitmapXPts[0] = 0;
		bitmapYPts[0] = 0;

		bitmapXPts[1] = 0;
		bitmapYPts[1] = bitmapBottom;

		bitmapXPts[2] = bitmapRight;
		bitmapYPts[2] = bitmapBottom;

		bitmapXPts[3] = bitmapRight;
		bitmapYPts[3] = 0;

		long rotation;
		for (int i = 0; i < 4; i++) {
			rotation = VecMath.multiplyPoint(transformMatrix, 0, bitmapXPts[i], bitmapYPts[i]);
			bitmapXPts[i] = (int) rotation;
			bitmapYPts[i] = (int) (rotation >>> 32);
		}

		// calculate the new boundaries (as rotation can require a
		// larger bitmap to hold the image)
		int minX = 0;
		int minY = 0;
		int maxX = 0;
		int maxY = 0;

		for (int i = 1; i < 4; i++) {
			if (bitmapXPts[i] < minX) {
				minX = bitmapXPts[i];
			} else if (bitmapXPts[i] > maxX) {
				maxX = bitmapXPts[i];
			}

			if (bitmapYPts[i] < minY) {
				minY = bitmapYPts[i];
			} else if (bitmapYPts[i] > maxY) {
				maxY = bitmapYPts[i];
			}
		}

		// shift the new boundaries to be anchored in the top left at
		// 0,0 and restore to int coordinates.
		for (int i = 0; i < 4; i++) {
			bitmapXPts[i] = Fixed32.toInt(bitmapXPts[i] - minX);
			bitmapYPts[i] = Fixed32.toInt(bitmapYPts[i] - minY);
		}

		/**
		 * When creating a non-orthogonal rotation, the resultant path may not
		 * be properly rectangular after rotation. This avoids misalignment of
		 * the texture and path by slightly spreading the texture over the
		 * space, making it a bit larger.
		 */
		if (!orthogonal) {
			// New texture origin outside the original region
			textureX = Fixed32.toFP(-2);
			textureY = Fixed32.toFP(-2);

			// rotate the texture origin just as the region was rotated
			rotation = VecMath.multiplyPoint(transformMatrix, 0, textureX, textureY);
			textureX = (int) rotation;
			textureY = (int) (rotation >>> 32);

			// adjust the texture origin to the same point space as the region
			textureX = Fixed32.toInt(textureX - minX);
			textureY = Fixed32.toInt(textureY - minY);

			// scale the texture so that it is 2 pixels larger than the region
			// on all sides
			resultantScaleX = Fixed32.div((bitmapRight + Fixed32.toFP(4)), Fixed32.toFP(bitmap.getWidth()));
			resultantScaleY = Fixed32.div((bitmapBottom + Fixed32.toFP(4)), Fixed32.toFP(bitmap.getHeight()));

		} else {
			// orthogonal roations can use exact coordinates since the region is
			// perfectly formed
			textureX = bitmapXPts[0];
			textureY = bitmapYPts[0];
			resultantScaleX = scaleX;
			resultantScaleY = scaleY;
		}
		// set the resulting dimensions of a bitmap containing this rotation
		transformedRegion.set(Fixed32.toRoundedInt(maxX - minX) + 1, Fixed32.toRoundedInt(maxY - minY) + 1);
		transformationApplied = true;
	}

	/**
	 * Get the background color.
	 *
	 * @return integer in the format 0xAARRGGBB.
	 * @since 1.5
	 */
	public int getBackgroundColor() {
		return backgroundColor;
	}

	/**
	 * Set the background color. Takes an integer in the format 0xAARRGGBB,
	 * where AA is the alpha value.
	 *
	 * @param backgroundColor
	 * @since 1.5
	 */
	public void setBackgroundColor(int backgroundColor) {
		this.backgroundColor = backgroundColor;
	}

	/**
	 * Set the background alpha value.
	 *
	 * @param backgroundAlpha
	 *            0-255, 0 is transparent.
	 */
	public void setBackgroundAlpha(int backgroundAlpha) {
		this.backgroundAlpha = backgroundAlpha;
	}

	/**
	 * Get the background alpha
	 *
	 * @return alpha setting of the background (0-255).
	 */
	public int getBackgroundAlpha() {
		return backgroundAlpha;
	}

	/**
	 * Paint the transformed Bitmap using the given Graphics context. Paints the
	 * area transparent before painting the bitmap.
	 *
	 * @param g
	 *            the {@link Graphics} context to use - from a screen or bitmap,
	 *            etc.
	 */
	private void paintTransformedBitmap(Graphics g) {
		paintTransformedBitmap(g, textureX, textureY);
	}

	/**
	 * Paint the transformed Bitmap using the given Graphics context. Paints the
	 * area transparent before painting the bitmap.
	 *
	 * @param g
	 *            the {@link Graphics} context to use - from a screen or bitmap,
	 *            etc.
	 * @param textureOriginX
	 *            x value in the original bitmap to start drawing from
	 * @param textureOriginY
	 *            y value in the original bitmap to start drawing from
	 * @since 1.1
	 */
	private void paintTransformedBitmap(Graphics g, int textureOriginX, int textureOriginY) {
		// Make the drawing space transparent first before painting
		g.setGlobalAlpha(getBackgroundAlpha());
		g.setBackgroundColor(getBackgroundColor());
		g.clear();
		g.setGlobalAlpha(255);
		/**
		 * Keep the precision of our transformation and Scale the drawing as
		 * well. Scale is applied as though a matrix of the form
		 *
		 *

		 * | ScaleX  0     0|
		 * | 0    ScaleY   0|
		 * | 0       0     1|
		 *

		 *
		 * is multiplied by the Transformation matrix
		 **/

		int dux = Fixed32.div(transformMatrix[UX], resultantScaleX);
		int dvx = Fixed32.div(transformMatrix[VX], resultantScaleY);
		int duy = Fixed32.div(transformMatrix[UY], resultantScaleX);
		int dvy = Fixed32.div(transformMatrix[VY], resultantScaleY);

    // Needed for alpha changes in 6.0 with Graphics.clear()
    g.setColor(Graphics.WHITE);
		g.drawFilledPath(bitmapXPts, bitmapYPts, null, null);

		g.drawTexturedPath(bitmapXPts, bitmapYPts, null, null, textureOriginX, textureOriginY, dux, dvx, duy, dvy, bitmap);
	}

	/**
	 * Apply the transformation and paint on the given Graphics context
	 *
	 * @param g
	 *            the {@link Graphics} context to use - from a screen or bitmap,
	 *            etc.
	 */
	public void transformAndPaintBitmap(Graphics g) {
		applyTransformation();
		paintTransformedBitmap(g);
	}

	/**
	 * Apply the transformation, paint to a new {@link Bitmap} and return it
	 *
	 * @return The transformed {@link Bitmap} of the required size to display
	 *         the entire transformed (rotated, scaled) image, with an alpha
	 *         channel so that the space around the bitmap is transparent.
	 */
	public Bitmap transformAndPaintBitmap() {

		applyTransformation();

		// create the new bitmap
		Bitmap transformedBitmap = new Bitmap(bitmap.getType(), transformedRegion.width, transformedRegion.height);
		transformedBitmap.createAlpha(Bitmap.ALPHA_BITDEPTH_8BPP);
		Graphics graphics = new Graphics(transformedBitmap);
		paintTransformedBitmap(graphics);
		return transformedBitmap;
	}

	/**
	 * Scale the internal bitmap into the provided Bitmap. Alternate
	 * implementation of method from 5.0 Bitmap API.
	 *
	 *

	 * {@link http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/system/Bitmap.html}
	 *

	 *
	 * @param dst
	 *            the {@link Bitmap} to paint on, scale comes from this.
	 * @param filterType
	 *            has no real effect, but must be one of:
	 *

	 *
{@link #FILTER_LANCZOS}

	 *
{@link #FILTER_BOX}

	 *
{@link #FILTER_BILINEAR}

	 *

	 *
	 * @since 1.1
	 */
	public void scaleInto(Bitmap dst, int filterType) {
		scaleInto(0, 0, bitmap.getWidth(), bitmap.getHeight(), dst, 0, 0, dst.getWidth(), dst.getHeight(), filterType);
	}

	/**
	 * Scale the internal bitmap into the provided Bitmap, using the provided
	 * Aspect Ratio rules. Alternate implementation of method from 5.0 Bitmap
	 * API.
	 *
	 *

	 * {@link http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/system/Bitmap.html}
	 *

	 *
	 * @param dst
	 *            the {@link Bitmap} to paint on, scale comes from this.
	 * @param filterType
	 *            has no real effect, but must be one of:
	 *

	 *
{@link #FILTER_LANCZOS}

	 *
{@link #FILTER_BOX}

	 *
{@link #FILTER_BILINEAR}

	 *

	 * @param iAspectRatioOption
	 *            one of:
	 *

	 *
{@link #SCALE_STRETCH}

	 *
{@link #SCALE_TO_FILL}

	 *
{@link #SCALE_TO_FIT}

	 *

	 * @since 1.1
	 */
	public void scaleInto(Bitmap dst, int filterType, int iAspectRatioOption) {

		// Maintain same interface as 5.0 API
		if (iAspectRatioOption < 0 || iAspectRatioOption > 2) {
			throw new IllegalArgumentException("Invalid aspect ratio parameter");
		}

		int dstWidth = Fixed32.toFP(dst.getWidth());
		int srcWidth = Fixed32.toFP(bitmap.getWidth());
		int dstHeight = Fixed32.toFP(dst.getHeight());
		int srcHeight = Fixed32.toFP(bitmap.getHeight());

		// Find the scale values in each axis to compare
		int scaleHoriz = Fixed32.div(dstWidth, srcWidth);
		int scaleVert = Fixed32.div(dstHeight, srcHeight);

		switch (iAspectRatioOption) {
		case SCALE_STRETCH:
			scaleInto(0, 0, bitmap.getWidth(), bitmap.getHeight(), dst, 0, 0, dst.getWidth(), dst.getHeight(), filterType);
			break;
		case SCALE_TO_FILL:
			/*
			 * Destination should be completely filled by source, with some
			 * source not being painted if necessary. Also centers the painting.
			 */
			int srcShiftX;
			int srcShiftY;

			if (scaleVert > scaleHoriz) {
				// source height fills the destination
				int srcRegionWidth = Fixed32.div(dstWidth, scaleVert);
				srcShiftX = Fixed32.toRoundedInt(Fixed32.mul((srcWidth - srcRegionWidth) >> 1, scaleVert));
				scaleInto(srcShiftX, 0, Fixed32.toRoundedInt(srcRegionWidth), bitmap.getHeight(), dst, 0, 0, dst.getWidth(), dst.getHeight(),
						filterType);
			} else if (scaleHoriz > scaleVert) {
				// source width fills destination
				int srcRegionHeight = Fixed32.div(dstHeight, scaleHoriz);
				srcShiftY = Fixed32.toRoundedInt(Fixed32.mul((srcHeight - srcRegionHeight) >> 1, scaleVert));
				scaleInto(0, srcShiftY, bitmap.getWidth(), Fixed32.toRoundedInt(srcRegionHeight), dst, 0, 0, dst.getWidth(), dst.getHeight(),
						filterType);
			} else {
				// Both bitmaps have the same aspect ratio
				scaleInto(0, 0, bitmap.getWidth(), bitmap.getHeight(), dst, 0, 0, dst.getWidth(), dst.getHeight(), filterType);
			}
			break;
		case SCALE_TO_FIT:
			/*
			 * Source should be completely contained by destination, with some
			 * destination not being painted if necessary. Also centers the
			 * painting.
			 */
			int dstShiftX;
			int dstShiftY;

			if (scaleVert < scaleHoriz) {
				// source is fitted vertically with blank sides
				int scaledWidth = Fixed32.mul(scaleVert, srcWidth);
				dstShiftX = Fixed32.toInt((dstWidth - scaledWidth) >> 1);
				scaleInto(0, 0, bitmap.getWidth(), bitmap.getHeight(), dst, dstShiftX, 0, Fixed32.toRoundedInt(scaledWidth), dst.getHeight(),
						filterType);
			} else if (scaleHoriz < scaleVert) {
				// source fits horizontally with blank top and bottom
				int scaledHeight = Fixed32.mul(scaleHoriz, srcHeight);
				dstShiftY = Fixed32.toInt((dstHeight - scaledHeight) >> 1);
				scaleInto(0, 0, bitmap.getWidth(), bitmap.getHeight(), dst, 0, dstShiftY, dst.getWidth(), Fixed32.toRoundedInt(scaledHeight),
						filterType);
			} else {
				// Both bitmaps have the same aspect ratio
				scaleInto(0, 0, bitmap.getWidth(), bitmap.getHeight(), dst, 0, 0, dst.getWidth(), dst.getHeight(), filterType);
			}
			break;

		}

	}

	/**
	 * Scale the internal bitmap into the provided Bitmap. Alternate
	 * implementation of method from 5.0 Bitmap API.
	 *
	 *

	 * {@link http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/system/Bitmap.html}
	 *

	 *
	 *
	 * @param srcLeft
	 *            X coordinate of the top left corner of the area to be copied
	 *            from the source bitmap.
	 * @param srcTop
	 *            Y coordinate of the top left corner of the area to be copied
	 *            from the source bitmap.
	 * @param srcWidth
	 *            Width of the area to be copied from the source bitmap.
	 * @param srcHeight
	 *            Height of the area to be copied from the source bitmap.
	 * @param dst
	 *            the {@link Bitmap} to paint on, scale comes from this.
	 * @param dstLeft
	 *            X coordinate of the top left corner of the area to be copied
	 *            to the destination bitmap.
	 * @param dstTop
	 *            Y coordinate of the top left corner of the area to be copied
	 *            to the destination bitmap.
	 * @param dstWidth
	 *            Width of the area to be copied from the source bitmap.
	 * @param dstHeight
	 *            Height of the area to be copied to the destination bitmap.
	 * @param filterType
	 *            has no real effect, but must be one of:
	 *

	 *
{@link #FILTER_LANCZOS}

	 *
{@link #FILTER_BOX}

	 *
{@link #FILTER_BILINEAR}

	 *

	 * @throws NullPointerException
	 *             Thrown if 'dst' is null.
	 * @throws IllegalArgumentException
	 *             Thrown if the destination bitmap is read-only.
	 * @throws IllegalArgumentException
	 *             Thrown if illegal filter type is specified.
	 * @since 1.1
	 */
	public void scaleInto(int srcLeft, int srcTop, int srcWidth, int srcHeight, Bitmap dst, int dstLeft, int dstTop, int dstWidth, int dstHeight,
			int filterType) {

		// Maintain same interface as 5.0 API
		if (dst == null) {
			throw new NullPointerException("Destination bitmap can not be set to NULL");
		}
		if (!dst.isWritable()) {
			throw new IllegalArgumentException("Destination bitmap should not be read-only");
		}
		if (filterType < 0 || filterType > 2) {
			throw new IllegalArgumentException("Invalid filter type");
		}

		// make sure we're starting with no rotation.
		resetTransform();

		// set the region to be drawn on
		bitmapXPts = new int[] { dstLeft, dstLeft, dstLeft + dstWidth, dstLeft + dstWidth };
		bitmapYPts = new int[] { dstTop, dstTop + dstHeight, dstTop + dstHeight, dstTop };

		// Calculate the new scale based on the region sizes
		resultantScaleX = Fixed32.div(Fixed32.toFP(dstWidth), Fixed32.toFP(srcWidth));
		resultantScaleY = Fixed32.div(Fixed32.toFP(dstHeight), Fixed32.toFP(srcHeight));

		Graphics graphics = new Graphics(dst);
		paintTransformedBitmap(graphics, dstLeft - srcLeft, dstTop - srcTop);
	}

	/**
	 * Round the value to the nearest int
	 *
	 * @param value
	 * @return rounded value
	 * @since 1.1
	 */
	public static int round(double value) {
		if (value < 0) {
			int roundedDown = (int) value;
			if (value != (roundedDown - 0.5f)) {
				return (int) (value - 0.5f);
			} // Special case to match java.lang.Math round functionality. Same
			// rounding as positive float when value is negative exact half
			// (eg. -x.5)

		}
		return (int) (value + 0.5f);
	}

	/**
	 * Convert a double value to a Fixed32 integer
	 *
	 * @param value
	 * @return the value as an integer in Fixed32 format (16.16);
	 * @since 1.3
	 */
	public static int toFP(double value) {
		return round(value * SHIFT16);
	}

	/**
	 * Utility to convert a RIM API Bitmap into a J2ME LCDUI Image. This assists
	 * in using this library within a MIDP application, where the
	 * drawTexturedPath method is not available.
	 *
	 * @param bitmap
	 *            the source Bitmap
	 * @return the Image object based on the Bitmap data
	 * @since 1.2
	 */
	public static Image convert(Bitmap bitmap) {
		int[] data = new int[bitmap.getWidth() * bitmap.getHeight()];
		bitmap.getARGB(data, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
		return Image.createRGBImage(data, bitmap.getWidth(), bitmap.getHeight(), true);
	}

	/**
	 * Return the unmodified bitmap
	 *
	 * @return the original, unmodified bitmap provided in the constructor or
	 *         through setBitmap(Bitmap)
	 */
	public Bitmap getOriginalBitmap() {
		return bitmap;
	}

	/**
	 * Set a new bitmap to be transformed
	 *
	 * @param bitmap
	 */
	public void setBitmap(Bitmap bitmap) {
		this.bitmap = bitmap;
		transformationApplied = false;
	}

	/**
	 * The Scale factor in the X dimension
	 *
	 * @return the scale as a Fixed32 integer (16.16)
	 */
	public double getScaleX() {
		return scaleX;
	}

	/**
	 * Set the X dimension scale independently
	 *
	 * @param scaleX
	 *            as a Fixed32 integer (16.16)
	 */
	public void setScaleX(int scaleX) {
		this.scaleX = scaleX;
		transformationApplied = false;
	}

	/**
	 * The Scale factor in the Y dimension
	 *
	 * @return the scale as a Fixed32 integer (16.16)
	 */
	public int getScaleY() {
		return scaleY;
	}

	/**
	 * Set the Y dimension scale independently
	 *
	 * @param scaleY
	 *            as a Fixed32 integer (16.16)
	 */
	public void setScaleY(int scaleY) {
		this.scaleY = scaleY;
		transformationApplied = false;
	}

	/**
	 * Set the X and Y scales together
	 *
	 * @param scale
	 *            as a Fixed32 integer (16.16)
	 */
	public void setScale(int scale) {
		this.setScaleX(scale);
		this.setScaleY(scale);
	}
}