text:
// Copyright (c) 2002 Graz University of Technology. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// 3. The end-user documentation included with the redistribution, if any, must
//    include the following acknowledgment:
//
//    "This product includes software developed by IAIK of Graz University of
//     Technology."
//
//    Alternately, this acknowledgment may appear in the software itself, if and
//    wherever such third-party acknowledgments normally appear.
//
// 4. The names "Graz University of Technology" and "IAIK of Graz University of
//    Technology" must not be used to endorse or promote products derived from this
//    software without prior written permission.
//
// 5. Products derived from this software may not be called "IAIK PKCS Wrapper",
//    nor may "IAIK" appear in their name, without prior written permission of
//    Graz University of Technology.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE LICENSOR BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

package iaik.pkcs.pkcs11.wrapper;

import java.io.File;
import java.io.IOException;

/**
 * This is the default implementation of the PKCS11 interface. It connects to
 * the pkcs11wrapper.dll (or libpkcs11wrapper.so),
 * which is the native part of this library. This file either has to be located
 * in the system path or the location has to be specified as parameter.
 * The strange and awkward looking initialization was chosen to avoid calling
 * System.loadLibrary(String) from a static initialization block,
 * because this would complicate the use in applets.
 *
 * @author Karl Scheibelhofer <Karl.Scheibelhofer@iaik.at>
 * @author Martin Schläffer <schlaeff@sbox.tugraz.at>
 * @invariants (pkcs11ModulePath_ <> null)
 */
public class PKCS11Implementation implements PKCS11 {

	/**
	 * The name of the native part of the wrapper; i.e. the filename without
	 * the extension (e.g. ".DLL" or ".so").
	 */
	private static final String PKCS11_WRAPPER = "pkcs11wrapper";

	/**
	 * Indicates, if the static linking and initialization of the library is already done.
	 */
	protected static boolean linkedAndInitialized_;

	/**
	 * The PKCS#11 module to connect to. This is the PKCS#11 driver of the token;
	 * e.g. pk2priv.dll.
	 */
	protected String pkcs11ModulePath_;

	/**
	 * This method does the initialization of the native library. It is called
	 * exactly once for this class.
	 *
	 * @preconditions
	 * @postconditions
	 */
	protected static synchronized native void initializeLibrary();

	/**
	 * This method does the finalization of the native library. It is called
	 * exactly once for this class. The library uses this method for a clean-up
	 * of any resources.
	 *
	 * @preconditions
	 * @postconditions
	 */
	protected static synchronized native void finalizeLibrary();

	/**
	 * This method ensures that the library is linked to this class and that it
	 * is initialized.
	 *
	 * @preconditions
	 * @postconditions
	 */
	public static synchronized void ensureLinkedAndInitialized() {
		if (!linkedAndInitialized_) {
			/* We do not call loadLibrary in a static initializer to allow better use in
			 * applets. Static initialization blocks have a differrent security context.
			 */
			System.loadLibrary(PKCS11_WRAPPER);
			initializeLibrary();
			linkedAndInitialized_ = true;
		}
	}

	/**
	 * This method ensures that the library is linked to this class and that it
	 * is initialized. For loading the PKCS#11-wrapper native library, System.load
	 * is used with the absolute path to the library including the file name.
	 *
	 * @param pkcs11WrapperPath the absolute path to the PKCS#11-wrapper native library including the filename
	 * @preconditions
	 * @postconditions
	 */
	public static synchronized void ensureLinkedAndInitialized(String pkcs11WrapperPath) {
		if (!linkedAndInitialized_) {
			System.load(new File(pkcs11WrapperPath).getAbsolutePath());
			initializeLibrary();
			linkedAndInitialized_ = true;
		}
	}

	/**
	 * This method does a clean-up in the native module of the wrapper. After
	 * a call to this method, this class cannot be used any longer.
	 * Because there are no means in Java to really unlink the native code
	 * analog to a System.loadLibrary() call, this method also
	 * cannot effectively unload the native part.
	 *
	 * @preconditions
	 * @postconditions
	 */
	public static synchronized void ensureUnlinkedAndFinalized() {
		if (linkedAndInitialized_) {
			finalizeLibrary();
			linkedAndInitialized_ = false;
			// there is nothing like System.unloadLibrary(PKCS11_WRAPPER) so let's trust in GC
		}
	}

	/**
	 * Connects to the PKCS#11 driver given. The filename must contain the
	 * path, if the driver is not in the system's search path.
	 *
	 * @param pkcs11ModulePath the PKCS#11 library path
	 * @exception IOException If linking to the given module failed.
	 * @preconditions (pkcs11ModulePath <> null)
	 * @postconditions
	 */
	PKCS11Implementation(String pkcs11ModulePath)
	    throws IOException
	{
		ensureLinkedAndInitialized();
		connect(pkcs11ModulePath);
		pkcs11ModulePath_ = pkcs11ModulePath;
	}

	/**
	 * Connects to the PKCS#11 driver given using the specified PKCS#11-wrapper native library.
	 * The filename of the PKCS#11 driver must contain the path, if the driver is not in the system's search path.
	 *
	 * @param pkcs11ModulePath the PKCS#11 library path
	 * @param pkcs11WrapperPath the absolute path to the PKCS#11-wrapper native library including the filename
	 * @exception IOException If linking to the given module failed.
	 * @preconditions (pkcs11ModulePath <> null)
	 * @postconditions
	 */
	PKCS11Implementation(String pkcs11ModulePath, String pkcs11WrapperPath)
	    throws IOException
	{
		ensureLinkedAndInitialized(pkcs11WrapperPath);
		connect(pkcs11ModulePath);
		pkcs11ModulePath_ = pkcs11ModulePath;
	}

	/**
	 * Connects this object to the specified PKCS#11 library. This method is for
	 * internal use only.
	 * Declared protected, because incorrect handling may result in errors in the
	 * native part.
	 *
	 * @param pkcs11ModulePath The PKCS#11 library path.
	 * @exception IOException If cenncting the given module failed.
	 * @preconditions (pkcs11ModulePath <> null)
	 * @postconditions
	 */
	protected synchronized native void connect(String pkcs11ModulePath)
	    throws IOException;

	/**
	 * Disconnects the PKCS#11 library from this object. After calling this
	 * method, this object is no longer connected to a native PKCS#11 module
	 * and any subsequent calls to C_ methods will fail. This method is for
	 * internal use only.
	 * Declared protected, because incorrect handling may result in errors in the
	 * native part.
	 *
	 * @preconditions
	 * @postconditions
	 */
	protected synchronized native void disconnect();

	// Implementation of PKCS11 methods delegated to native pkcs11wrapper library

	/* *****************************************************************************
	 * General-purpose
	 ******************************************************************************/

	/**
	 * C_Initialize initializes the Cryptoki library.
	 * (General-purpose)
	 *
	 * @param pInitArgs if pInitArgs is not NULL it gets casted to
	 *         CK_C_INITIALIZE_ARGS_PTR and dereferenced
	 *         (PKCS#11 param: CK_VOID_PTR pInitArgs)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_Initialize(Object pInitArgs, boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_Finalize indicates that an application is done with the
	 * Cryptoki library
	 * (General-purpose)
	 *
	 * @param pReserved is reserved. Should be NULL_PTR
	 *         (PKCS#11 param: CK_VOID_PTR pReserved)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pReserved == null)
	 * @postconditions
	 */
	public native void C_Finalize(Object pReserved)
	    throws PKCS11Exception;

	/**
	 * C_GetInfo returns general information about Cryptoki.
	 * (General-purpose)
	 *
	 * @return the information.
	 *         (PKCS#11 param: CK_INFO_PTR pInfo)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions (result <> null)
	 */
	public native CK_INFO C_GetInfo()
	    throws PKCS11Exception;

	/* *****************************************************************************
	 * Slot and token management
	 ******************************************************************************/

	/**
	 * C_GetSlotList obtains a list of slots in the system.
	 * (Slot and token management)
	 *
	 * @param tokenPresent if true only Slot IDs with a token are returned
	 *         (PKCS#11 param: CK_BBOOL tokenPresent)
	 * @return a long array of slot IDs and number of Slot IDs
	 *         (PKCS#11 param: CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions (result <> null)
	 */
	public native long[] C_GetSlotList(boolean tokenPresent)
	    throws PKCS11Exception;

	/**
	 * C_GetSlotInfo obtains information about a particular slot in
	 * the system.
	 * (Slot and token management)
	 *
	 * @param slotID the ID of the slot
	 *         (PKCS#11 param: CK_SLOT_ID slotID)
	 * @return the slot information
	 *         (PKCS#11 param: CK_SLOT_INFO_PTR pInfo)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions (result <> null)
	 */
	public native CK_SLOT_INFO C_GetSlotInfo(long slotID)
	    throws PKCS11Exception;

	/**
	 * C_GetTokenInfo obtains information about a particular token
	 * in the system.
	 * (Slot and token management)
	 *
	 * @param slotID ID of the token's slot
	 *         (PKCS#11 param: CK_SLOT_ID slotID)
	 * @return the token information
	 *         (PKCS#11 param: CK_TOKEN_INFO_PTR pInfo)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions (result <> null)
	 */
	public native CK_TOKEN_INFO C_GetTokenInfo(long slotID)
	    throws PKCS11Exception;

	/**
	 * C_GetMechanismList obtains a list of mechanism types
	 * supported by a token.
	 * (Slot and token management)
	 *
	 * @param slotID ID of the token's slot
	 *         (PKCS#11 param: CK_SLOT_ID slotID)
	 * @return a long array of mechanism types and number of mechanism types
	 *         (PKCS#11 param: CK_MECHANISM_TYPE_PTR pMechanismList,
	 *                         CK_ULONG_PTR pulCount)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions (result <> null)
	 */
	public native long[] C_GetMechanismList(long slotID)
	    throws PKCS11Exception;

	/**
	 * C_GetMechanismInfo obtains information about a particular
	 * mechanism possibly supported by a token.
	 * (Slot and token management)
	 *
	 * @param slotID ID of the token's slot
	 *         (PKCS#11 param: CK_SLOT_ID slotID)
	 * @param type type of mechanism
	 *         (PKCS#11 param: CK_MECHANISM_TYPE type)
	 * @return the mechanism info
	 *         (PKCS#11 param: CK_MECHANISM_INFO_PTR pInfo)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions (result <> null)
	 */
	public native CK_MECHANISM_INFO C_GetMechanismInfo(long slotID, long type)
	    throws PKCS11Exception;

	/**
	 * C_InitToken initializes a token.
	 * (Slot and token management)
	 *
	 * @param slotID ID of the token's slot
	 *         (PKCS#11 param: CK_SLOT_ID slotID)
	 * @param pPin the SO's initial PIN and the length in bytes of the PIN
	 *         (PKCS#11 param: CK_CHAR_PTR pPin, CK_ULONG ulPinLen)
	 * @param pLabel 32-byte token label (blank padded)
	 *         (PKCS#11 param: CK_UTF8CHAR_PTR pLabel)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_InitToken(long slotID, char[] pPin, char[] pLabel, boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_InitPIN initializes the normal user's PIN.
	 * (Slot and token management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pPin the normal user's PIN and the length in bytes of the PIN
	 *         (PKCS#11 param: CK_CHAR_PTR pPin, CK_ULONG ulPinLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_InitPIN(long hSession, char[] pPin, boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_SetPIN modifies the PIN of the user who is logged in.
	 * (Slot and token management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pOldPin the old PIN and the length of the old PIN
	 *         (PKCS#11 param: CK_CHAR_PTR pOldPin, CK_ULONG ulOldLen)
	 * @param pNewPin the new PIN and the length of the new PIN
	 *         (PKCS#11 param: CK_CHAR_PTR pNewPin, CK_ULONG ulNewLen)
	 * @param patchPin if pin should be changed from ASCII to UTF8 encoding in case of incorrect pin
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_SetPIN(long hSession, char[] pOldPin, char[] pNewPin, boolean useUtf8)
	    throws PKCS11Exception;

	/* *****************************************************************************
	 * Session management
	 ******************************************************************************/

	/**
	 * C_OpenSession opens a session between an application and a
	 * token.
	 * (Session management)
	 *
	 * @param slotID the slot's ID
	 *         (PKCS#11 param: CK_SLOT_ID slotID)
	 * @param flags of CK_SESSION_INFO
	 *         (PKCS#11 param: CK_FLAGS flags)
	 * @param pApplication passed to callback
	 *         (PKCS#11 param: CK_VOID_PTR pApplication)
	 * @param Notify the callback function
	 *         (PKCS#11 param: CK_NOTIFY Notify)
	 * @return the session handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE_PTR phSession)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native long C_OpenSession(long slotID,
	                                 long flags,
	                                 Object pApplication,
	                                 CK_NOTIFY Notify)
	    throws PKCS11Exception;

	/**
	 * C_CloseSession closes a session between an application and a
	 * token.
	 * (Session management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_CloseSession(long hSession)
	    throws PKCS11Exception;

	/**
	 * C_CloseAllSessions closes all sessions with a token.
	 * (Session management)
	 *
	 * @param slotID the ID of the token's slot
	 *         (PKCS#11 param: CK_SLOT_ID slotID)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_CloseAllSessions(long slotID)
	    throws PKCS11Exception;

	/**
	 * C_GetSessionInfo obtains information about the session.
	 * (Session management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @return the session info
	 *         (PKCS#11 param: CK_SESSION_INFO_PTR pInfo)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions (result <> null)
	 */
	public native CK_SESSION_INFO C_GetSessionInfo(long hSession)
	    throws PKCS11Exception;

	/**
	 * C_GetOperationState obtains the state of the cryptographic operation
	 * in a session.
	 * (Session management)
	 *
	 * @param hSession session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @return the state and the state length
	 *         (PKCS#11 param: CK_BYTE_PTR pOperationState,
	 *                         CK_ULONG_PTR pulOperationStateLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions (result <> null)
	 */
	public native byte[] C_GetOperationState(long hSession)
	    throws PKCS11Exception;

	/**
	 * C_SetOperationState restores the state of the cryptographic
	 * operation in a session.
	 * (Session management)
	 *
	 * @param hSession session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pOperationState the state and the state length
	 *         (PKCS#11 param: CK_BYTE_PTR pOperationState,
	 *                         CK_ULONG ulOperationStateLen)
	 * @param hEncryptionKey en/decryption key
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hEncryptionKey)
	 * @param hAuthenticationKey sign/verify key
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hAuthenticationKey)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_SetOperationState(long hSession,
	                                       byte[] pOperationState,
	                                       long hEncryptionKey,
	                                       long hAuthenticationKey)
	    throws PKCS11Exception;

	/**
	 * C_Login logs a user into a token.
	 * (Session management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param userType the user type
	 *         (PKCS#11 param: CK_USER_TYPE userType)
	 * @param pPin the user's PIN and the length of the PIN
	 *         (PKCS#11 param: CK_CHAR_PTR pPin, CK_ULONG ulPinLen)
	 * @param patchPin if pin should be changed from ASCII to UTF8 encoding in case of incorrect pin
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_Login(long hSession, long userType, char[] pPin, boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_Logout logs a user out from a token.
	 * (Session management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_Logout(long hSession)
	    throws PKCS11Exception;

	/* *****************************************************************************
	 * Object management
	 ******************************************************************************/

	/**
	 * C_CreateObject creates a new object.
	 * (Object management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pTemplate the object's template and number of attributes in
	 *         template
	 *         (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
	 * @return the object's handle
	 *         (PKCS#11 param: CK_OBJECT_HANDLE_PTR phObject)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native long C_CreateObject(long hSession, CK_ATTRIBUTE[] pTemplate, boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_CopyObject copies an object, creating a new object for the
	 * copy.
	 * (Object management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param hObject the object's handle
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hObject)
	 * @param pTemplate the template for the new object and number of attributes
	 *         in template
	 *         (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
	 * @return the handle of the copy
	 *         (PKCS#11 param: CK_OBJECT_HANDLE_PTR phNewObject)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native long C_CopyObject(long hSession, long hObject, CK_ATTRIBUTE[] pTemplate, boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_DestroyObject destroys an object.
	 * (Object management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param hObject the object's handle
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hObject)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_DestroyObject(long hSession, long hObject)
	    throws PKCS11Exception;

	/**
	 * C_GetObjectSize gets the size of an object in bytes.
	 * (Object management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param hObject the object's handle
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hObject)
	 * @return the size of the object
	 *         (PKCS#11 param: CK_ULONG_PTR pulSize)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native long C_GetObjectSize(long hSession, long hObject)
	    throws PKCS11Exception;

	/**
	 * C_GetAttributeValue obtains the value of one or more object
	 * attributes. The template attributes also receive the values.
	 * (Object management)
	 * note: in PKCS#11 pTemplate and the result template are the same
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param hObject the object's handle
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hObject)
	 * @param pTemplate specifies the attributes and number of attributes to get
	 *                  The template attributes also receive the values.
	 *         (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pTemplate <> null)
	 * @postconditions (result <> null)
	 */
	public native void C_GetAttributeValue(long hSession,
	                                       long hObject,
	                                       CK_ATTRIBUTE[] pTemplate,
	                                       boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_SetAttributeValue modifies the value of one or more object
	 * attributes
	 * (Object management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param hObject the object's handle
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hObject)
	 * @param pTemplate specifies the attributes and values to get; number of
	 *         attributes in the template
	 *         (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pTemplate <> null)
	 * @postconditions
	 */
	public native void C_SetAttributeValue(long hSession,
	                                       long hObject,
	                                       CK_ATTRIBUTE[] pTemplate,
	                                       boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_FindObjectsInit initializes a search for token and session
	 * objects that match a template.
	 * (Object management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pTemplate the object's attribute values to match and the number of
	 *         attributes in search template
	 *         (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_FindObjectsInit(long hSession, CK_ATTRIBUTE[] pTemplate, boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_FindObjects continues a search for token and session
	 * objects that match a template, obtaining additional object
	 * handles.
	 * (Object management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param ulMaxObjectCount the max. object handles to get
	 *         (PKCS#11 param: CK_ULONG ulMaxObjectCount)
	 * @return the object's handles and the actual number of objects returned
	 *         (PKCS#11 param: CK_ULONG_PTR pulObjectCount)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions (result <> null)
	 */
	public native long[] C_FindObjects(long hSession, long ulMaxObjectCount)
	    throws PKCS11Exception;

	/**
	 * C_FindObjectsFinal finishes a search for token and session
	 * objects.
	 * (Object management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_FindObjectsFinal(long hSession)
	    throws PKCS11Exception;

	/* *****************************************************************************
	 * Encryption and decryption
	 ******************************************************************************/

	/**
	 * C_EncryptInit initializes an encryption operation.
	 * (Encryption and decryption)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pMechanism the encryption mechanism
	 *         (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
	 * @param hKey the handle of the encryption key
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hKey)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_EncryptInit(long hSession, CK_MECHANISM pMechanism, long hKey, boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_Encrypt encrypts single-part data.
	 * (Encryption and decryption)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pData the data to get encrypted and the data's length
	 *         (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG ulDataLen)
	 * @return the encrypted data and the encrypted data's length
	 *         (PKCS#11 param: CK_BYTE_PTR pEncryptedData,
	 *                         CK_ULONG_PTR pulEncryptedDataLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pData <> null)
	 * @postconditions (result <> null)
	 */
	public native byte[] C_Encrypt(long hSession, byte[] pData)
	    throws PKCS11Exception;

	/**
	 * C_EncryptUpdate continues a multiple-part encryption
	 * operation.
	 * (Encryption and decryption)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pPart the data part to get encrypted and the data part's length
	 *         (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
	 * @return the encrypted data part and the encrypted data part's length
	 *         (PKCS#11 param: CK_BYTE_PTR pEncryptedPart,
	                           CK_ULONG_PTR pulEncryptedPartLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pPart <> null)
	 * @postconditions
	 */
	public native byte[] C_EncryptUpdate(long hSession, byte[] pPart)
	    throws PKCS11Exception;

	/**
	 * C_EncryptFinal finishes a multiple-part encryption
	 * operation.
	 * (Encryption and decryption)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @return the last encrypted data part and the last data part's length
	 *         (PKCS#11 param: CK_BYTE_PTR pLastEncryptedPart,
	                           CK_ULONG_PTR pulLastEncryptedPartLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions (result <> null)
	 */
	public native byte[] C_EncryptFinal(long hSession)
	    throws PKCS11Exception;

	/**
	 * C_DecryptInit initializes a decryption operation.
	 * (Encryption and decryption)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pMechanism the decryption mechanism
	 *         (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
	 * @param hKey the handle of the decryption key
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hKey)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_DecryptInit(long hSession, CK_MECHANISM pMechanism, long hKey, boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_Decrypt decrypts encrypted data in a single part.
	 * (Encryption and decryption)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pEncryptedData the encrypted data to get decrypted and the
	 *         encrypted data's length
	 *         (PKCS#11 param: CK_BYTE_PTR pEncryptedData,
	 *                         CK_ULONG ulEncryptedDataLen)
	 * @return the decrypted data and the data's length
	 *         (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pEncryptedPart <> null)
	 * @postconditions (result <> null)
	 */
	public native byte[] C_Decrypt(long hSession, byte[] pEncryptedData)
	    throws PKCS11Exception;

	/**
	 * C_DecryptUpdate continues a multiple-part decryption
	 * operation.
	 * (Encryption and decryption)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pEncryptedPart the encrypted data part to get decrypted and the
	 *         encrypted data part's length
	 *         (PKCS#11 param: CK_BYTE_PTR pEncryptedPart,
	 *                         CK_ULONG ulEncryptedPartLen)
	 * @return the decrypted data part and the data part's length
	 *         (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pEncryptedPart <> null)
	 * @postconditions
	 */
	public native byte[] C_DecryptUpdate(long hSession, byte[] pEncryptedPart)
	    throws PKCS11Exception;

	/**
	 * C_DecryptFinal finishes a multiple-part decryption
	 * operation.
	 * (Encryption and decryption)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @return the last decrypted data part and the last data part's length
	 *         (PKCS#11 param: CK_BYTE_PTR pLastPart,
	 *                         CK_ULONG_PTR pulLastPartLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions (result <> null)
	 */
	public native byte[] C_DecryptFinal(long hSession)
	    throws PKCS11Exception;

	/* *****************************************************************************
	 * Message digesting
	 ******************************************************************************/

	/**
	 * C_DigestInit initializes a message-digesting operation.
	 * (Message digesting)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pMechanism the digesting mechanism
	 *         (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_DigestInit(long hSession, CK_MECHANISM pMechanism, boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_Digest digests data in a single part.
	 * (Message digesting)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param data the data to get digested and the data's length
	 *         (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG ulDataLen)
	 * @return the message digest and the length of the message digest
	 *         (PKCS#11 param: CK_BYTE_PTR pDigest, CK_ULONG_PTR pulDigestLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (data <> null)
	 * @postconditions (result <> null)
	 */
	public native byte[] C_Digest(long hSession, byte[] data)
	    throws PKCS11Exception;

	/**
	 * C_DigestUpdate continues a multiple-part message-digesting
	 * operation.
	 * (Message digesting)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pPart the data to get digested and the data's length
	 *         (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pPart <> null)
	 * @postconditions
	 */
	public native void C_DigestUpdate(long hSession, byte[] pPart)
	    throws PKCS11Exception;

	/**
	 * C_DigestKey continues a multi-part message-digesting
	 * operation, by digesting the value of a secret key as part of
	 * the data already digested.
	 * (Message digesting)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param hKey the handle of the secret key to be digested
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hKey)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_DigestKey(long hSession, long hKey)
	    throws PKCS11Exception;

	/**
	 * C_DigestFinal finishes a multiple-part message-digesting
	 * operation.
	 * (Message digesting)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @return the message digest and the length of the message digest
	 *         (PKCS#11 param: CK_BYTE_PTR pDigest, CK_ULONG_PTR pulDigestLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions (result <> null)
	 */
	public native byte[] C_DigestFinal(long hSession)
	    throws PKCS11Exception;

	/* *****************************************************************************
	 * Signing and MACing
	 ******************************************************************************/

	/**
	 * C_SignInit initializes a signature (private key encryption)
	 * operation, where the signature is (will be) an appendix to
	 * the data, and plaintext cannot be recovered from the
	 * signature.
	 * (Signing and MACing)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pMechanism the signature mechanism
	 *         (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
	 * @param hKey the handle of the signature key
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hKey)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_SignInit(long hSession, CK_MECHANISM pMechanism, long hKey, boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_Sign signs (encrypts with private key) data in a single
	 * part, where the signature is (will be) an appendix to the
	 * data, and plaintext cannot be recovered from the signature.
	 * (Signing and MACing)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pData the data to sign and the data's length
	 *         (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG ulDataLen)
	 * @return the signature and the signature's length
	 *         (PKCS#11 param: CK_BYTE_PTR pSignature,
	 *                         CK_ULONG_PTR pulSignatureLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pData <> null)
	 * @postconditions (result <> null)
	 */
	public native byte[] C_Sign(long hSession, byte[] pData)
	    throws PKCS11Exception;

	/**
	 * C_SignUpdate continues a multiple-part signature operation,
	 * where the signature is (will be) an appendix to the data,
	 * and plaintext cannot be recovered from the signature.
	 * (Signing and MACing)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pPart the data part to sign and the data part's length
	 *         (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pPart <> null)
	 * @postconditions
	 */
	public native void C_SignUpdate(long hSession, byte[] pPart)
	    throws PKCS11Exception;

	/**
	 * C_SignFinal finishes a multiple-part signature operation,
	 * returning the signature.
	 * (Signing and MACing)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @return the signature and the signature's length
	 *         (PKCS#11 param: CK_BYTE_PTR pSignature,
	 *                         CK_ULONG_PTR pulSignatureLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions (result <> null)
	 */
	public native byte[] C_SignFinal(long hSession)
	    throws PKCS11Exception;

	/**
	 * C_SignRecoverInit initializes a signature operation, where
	 * the data can be recovered from the signature.
	 * (Signing and MACing)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pMechanism the signature mechanism
	 *         (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
	 * @param hKey the handle of the signature key
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hKey)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_SignRecoverInit(long hSession, CK_MECHANISM pMechanism, long hKey, boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_SignRecover signs data in a single operation, where the
	 * data can be recovered from the signature.
	 * (Signing and MACing)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pData the data to sign and the data's length
	 *         (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG ulDataLen)
	 * @return the signature and the signature's length
	 *         (PKCS#11 param: CK_BYTE_PTR pSignature,
	 *                         CK_ULONG_PTR pulSignatureLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pData <> null)
	 * @postconditions (result <> null)
	 */
	public native byte[] C_SignRecover(long hSession, byte[] pData)
	    throws PKCS11Exception;

	/* *****************************************************************************
	 * Verifying signatures and MACs
	 ******************************************************************************/

	/**
	 * C_VerifyInit initializes a verification operation, where the
	 * signature is an appendix to the data, and plaintext cannot
	 * cannot be recovered from the signature (e.g. DSA).
	 * (Signing and MACing)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pMechanism the verification mechanism
	 *         (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
	 * @param hKey the handle of the verification key
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hKey)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_VerifyInit(long hSession, CK_MECHANISM pMechanism, long hKey, boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_Verify verifies a signature in a single-part operation,
	 * where the signature is an appendix to the data, and plaintext
	 * cannot be recovered from the signature.
	 * (Signing and MACing)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pData the signed data and the signed data's length
	 *         (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG ulDataLen)
	 * @param pSignature the signature to verify and the signature's length
	 *         (PKCS#11 param: CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pData <> null) and (pSignature <> null)
	 * @postconditions
	 */
	public native void C_Verify(long hSession, byte[] pData, byte[] pSignature)
	    throws PKCS11Exception;

	/**
	 * C_VerifyUpdate continues a multiple-part verification
	 * operation, where the signature is an appendix to the data,
	 * and plaintext cannot be recovered from the signature.
	 * (Signing and MACing)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pPart the signed data part and the signed data part's length
	 *         (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pPart <> null)
	 * @postconditions
	 */
	public native void C_VerifyUpdate(long hSession, byte[] pPart)
	    throws PKCS11Exception;

	/**
	 * C_VerifyFinal finishes a multiple-part verification
	 * operation, checking the signature.
	 * (Signing and MACing)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pSignature the signature to verify and the signature's length
	 *         (PKCS#11 param: CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pSignature <> null)
	 * @postconditions
	 */
	public native void C_VerifyFinal(long hSession, byte[] pSignature)
	    throws PKCS11Exception;

	/**
	 * C_VerifyRecoverInit initializes a signature verification
	 * operation, where the data is recovered from the signature.
	 * (Signing and MACing)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pMechanism the verification mechanism
	 *         (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
	 * @param hKey the handle of the verification key
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hKey)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_VerifyRecoverInit(long hSession, CK_MECHANISM pMechanism, long hKey, boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_VerifyRecover verifies a signature in a single-part
	 * operation, where the data is recovered from the signature.
	 * (Signing and MACing)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pSignature the signature to verify and the signature's length
	 *         (PKCS#11 param: CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen)
	 * @return the recovered data and the recovered data's length
	 *         (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pSignature <> null)
	 * @postconditions (result <> null)
	 */
	public native byte[] C_VerifyRecover(long hSession, byte[] pSignature)
	    throws PKCS11Exception;

	/* *****************************************************************************
	 * Dual-function cryptographic operations
	 ******************************************************************************/

	/**
	 * C_DigestEncryptUpdate continues a multiple-part digesting
	 * and encryption operation.
	 * (Dual-function cryptographic operations)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pPart the data part to digest and to encrypt and the data's length
	 *         (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
	 * @return the digested and encrypted data part and the data part's length
	 *         (PKCS#11 param: CK_BYTE_PTR pEncryptedPart,
	 *                         CK_ULONG_PTR pulEncryptedPartLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pPart <> null)
	 * @postconditions
	 */
	public native byte[] C_DigestEncryptUpdate(long hSession, byte[] pPart)
	    throws PKCS11Exception;

	/**
	 * C_DecryptDigestUpdate continues a multiple-part decryption and
	 * digesting operation.
	 * (Dual-function cryptographic operations)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pEncryptedPart the encrypted data part to decrypt and to digest
	 *         and encrypted data part's length
	 *         (PKCS#11 param: CK_BYTE_PTR pEncryptedPart,
	 *                         CK_ULONG ulEncryptedPartLen)
	 * @return the decrypted and digested data part and the data part's length
	 *         (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pEncryptedPart <> null)
	 * @postconditions
	 */
	public native byte[] C_DecryptDigestUpdate(long hSession, byte[] pEncryptedPart)
	    throws PKCS11Exception;

	/**
	 * C_SignEncryptUpdate continues a multiple-part signing and
	 * encryption operation.
	 * (Dual-function cryptographic operations)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pPart the data part to sign and to encrypt and the data part's
	 *         length
	 *         (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
	 * @return the signed and encrypted data part and the data part's length
	 *         (PKCS#11 param: CK_BYTE_PTR pEncryptedPart,
	 *                         CK_ULONG_PTR pulEncryptedPartLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pPart <> null)
	 * @postconditions
	 */
	public native byte[] C_SignEncryptUpdate(long hSession, byte[] pPart)
	    throws PKCS11Exception;

	/**
	 * C_DecryptVerifyUpdate continues a multiple-part decryption and
	 * verify operation.
	 * (Dual-function cryptographic operations)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pEncryptedPart the encrypted data part to decrypt and to verify
	 *         and the data part's length
	 *         (PKCS#11 param: CK_BYTE_PTR pEncryptedPart,
	 *                         CK_ULONG ulEncryptedPartLen)
	 * @return the decrypted and verified data part and the data part's length
	 *         (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pEncryptedPart <> null)
	 * @postconditions
	 */
	public native byte[] C_DecryptVerifyUpdate(long hSession, byte[] pEncryptedPart)
	    throws PKCS11Exception;

	/* *****************************************************************************
	 * Key management
	 ******************************************************************************/

	/**
	 * C_GenerateKey generates a secret key, creating a new key
	 * object.
	 * (Key management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pMechanism the key generation mechanism
	 *         (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
	 * @param pTemplate the template for the new key and the number of
	 *         attributes in the template
	 *         (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
	 * @return the handle of the new key
	 *         (PKCS#11 param: CK_OBJECT_HANDLE_PTR phKey)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native long C_GenerateKey(long hSession,
	                                 CK_MECHANISM pMechanism,
	                                 CK_ATTRIBUTE[] pTemplate,
	                                 boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_GenerateKeyPair generates a public-key/private-key pair,
	 * creating new key objects.
	 * (Key management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pMechanism the key generation mechanism
	 *         (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
	 * @param pPublicKeyTemplate the template for the new public key and the
	 *         number of attributes in the template
	 *         (PKCS#11 param: CK_ATTRIBUTE_PTR pPublicKeyTemplate,
	 *                         CK_ULONG ulPublicKeyAttributeCount)
	 * @param pPrivateKeyTemplate the template for the new private key and the
	 *         number of attributes in the template
	 *         (PKCS#11 param: CK_ATTRIBUTE_PTR pPrivateKeyTemplate
	 *                         CK_ULONG ulPrivateKeyAttributeCount)
	 * @return a long array with exactly two elements and the public key handle
	 *         as the first element and the private key handle as the second
	 *         element
	 *         (PKCS#11 param: CK_OBJECT_HANDLE_PTR phPublicKey,
	 *                         CK_OBJECT_HANDLE_PTR phPrivateKey)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pMechanism <> null)
	 * @postconditions (result <> null) and (result.length == 2)
	 */
	public native long[] C_GenerateKeyPair(long hSession,
	                                       CK_MECHANISM pMechanism,
	                                       CK_ATTRIBUTE[] pPublicKeyTemplate,
	                                       CK_ATTRIBUTE[] pPrivateKeyTemplate,
	                                       boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_WrapKey wraps (i.e., encrypts) a key.
	 * (Key management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pMechanism the wrapping mechanism
	 *         (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
	 * @param hWrappingKey the handle of the wrapping key
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hWrappingKey)
	 * @param hKey the handle of the key to be wrapped
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hKey)
	 * @return the wrapped key and the length of the wrapped key
	 *         (PKCS#11 param: CK_BYTE_PTR pWrappedKey,
	 *                         CK_ULONG_PTR pulWrappedKeyLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions (result <> null)
	 */
	public native byte[] C_WrapKey(long hSession,
	                               CK_MECHANISM pMechanism,
	                               long hWrappingKey,
	                               long hKey,
	                               boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_UnwrapKey unwraps (decrypts) a wrapped key, creating a new
	 * key object.
	 * (Key management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pMechanism the unwrapping mechanism
	 *         (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
	 * @param hUnwrappingKey the handle of the unwrapping key
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hUnwrappingKey)
	 * @param pWrappedKey the wrapped key to unwrap and the wrapped key's length
	 *         (PKCS#11 param: CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen)
	 * @param pTemplate the template for the new key and the number of
	 *         attributes in the template
	 *         (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
	 * @return the handle of the unwrapped key
	 *         (PKCS#11 param: CK_OBJECT_HANDLE_PTR phKey)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pWrappedKey <> null)
	 * @postconditions
	 */
	public native long C_UnwrapKey(long hSession,
	                               CK_MECHANISM pMechanism,
	                               long hUnwrappingKey,
	                               byte[] pWrappedKey,
	                               CK_ATTRIBUTE[] pTemplate,
	                               boolean useUtf8)
	    throws PKCS11Exception;

	/**
	 * C_DeriveKey derives a key from a base key, creating a new key
	 * object.
	 * (Key management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pMechanism the key derivation mechanism
	 *         (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
	 * @param hBaseKey the handle of the base key
	 *         (PKCS#11 param: CK_OBJECT_HANDLE hBaseKey)
	 * @param pTemplate the template for the new key and the number of
	 *         attributes in the template
	 *         (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
	 * @return the handle of the derived key
	 *         (PKCS#11 param: CK_OBJECT_HANDLE_PTR phKey)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native long C_DeriveKey(long hSession,
	                               CK_MECHANISM pMechanism,
	                               long hBaseKey,
	                               CK_ATTRIBUTE[] pTemplate,
	                               boolean useUtf8)
	    throws PKCS11Exception;

	/* *****************************************************************************
	 * Random number generation
	 ******************************************************************************/

	/**
	 * C_SeedRandom mixes additional seed material into the token's
	 * random number generator.
	 * (Random number generation)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param pSeed the seed material and the seed material's length
	 *         (PKCS#11 param: CK_BYTE_PTR pSeed, CK_ULONG ulSeedLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pSeed <> null)
	 * @postconditions
	 */
	public native void C_SeedRandom(long hSession, byte[] pSeed)
	    throws PKCS11Exception;

	/**
	 * C_GenerateRandom generates random data.
	 * (Random number generation)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @param randomData receives the random data and the length of RandomData
	 *         is the length of random data to be generated
	 *         (PKCS#11 param: CK_BYTE_PTR pRandomData, CK_ULONG ulRandomLen)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (randomData <> null)
	 * @postconditions
	 */
	public native void C_GenerateRandom(long hSession, byte[] randomData)
	    throws PKCS11Exception;

	/* *****************************************************************************
	 * Parallel function management
	 ******************************************************************************/

	/**
	 * C_GetFunctionStatus is a legacy function; it obtains an
	 * updated status of a function running in parallel with an
	 * application.
	 * (Parallel function management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_GetFunctionStatus(long hSession)
	    throws PKCS11Exception;

	/**
	 * C_CancelFunction is a legacy function; it cancels a function
	 * running in parallel.
	 * (Parallel function management)
	 *
	 * @param hSession the session's handle
	 *         (PKCS#11 param: CK_SESSION_HANDLE hSession)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions
	 * @postconditions
	 */
	public native void C_CancelFunction(long hSession)
	    throws PKCS11Exception;

	/* *****************************************************************************
	 * Functions added in for Cryptoki Version 2.01 or later
	 ******************************************************************************/

	/**
	 * C_WaitForSlotEvent waits for a slot event (token insertion,
	 * removal, etc.) to occur.
	 * (General-purpose)
	 *
	 * @param flags blocking/nonblocking flag
	 *         (PKCS#11 param: CK_FLAGS flags)
	 * @param pReserved reserved. Should be null
	 *         (PKCS#11 param: CK_VOID_PTR pReserved)
	 * @return the slot ID where the event occured
	 *         (PKCS#11 param: CK_SLOT_ID_PTR pSlot)
	 * @exception PKCS11Exception If function returns other value than CKR_OK.
	 * @preconditions (pRserved == null)
	 * @postconditions
	 */
	public native long C_WaitForSlotEvent(long flags, Object pReserved)
	    throws PKCS11Exception;

	/**
	 * Compares this object with the other object.
	 * Returns only true, if both objects refer to the same PKCS#11 library.
	 *
	 * @param otherObject The other PKCS11Implementation.
	 * @return True, if this PKCS11Implementation and the other
	 *         PKCS11Implementation refer to the same PKCS#11 library;
	 *         False, otherwise.
	 * @preconditions
	 * @postconditions
	 */
	public boolean equals(java.lang.Object otherObject) {
		boolean equal;

		if (this == otherObject) {
			equal = true;
		} else if (otherObject instanceof PKCS11Implementation) {
			PKCS11Implementation other = (PKCS11Implementation) otherObject;

			if (this.pkcs11ModulePath_.equals(other.pkcs11ModulePath_)) {
				equal = true;
			} else {
				try {
					File thisLibarayFile = new File(this.pkcs11ModulePath_);
					File otherLibaryFile = new File(other.pkcs11ModulePath_);
					if (thisLibarayFile.getCanonicalPath().equals(
					    otherLibaryFile.getCanonicalPath())) {
						equal = true;
					} else {
						equal = false;
					}
				} catch (IOException ex) {
					ex.printStackTrace();
					equal = false;
				}
			}
		} else {
			equal = false;
		}

		return equal;
	}

	/**
	 * The overriding of this method should ensure that the objects of this class
	 * work correctly in a hashtable.
	 *
	 * @return The hash code of this object.
	 * @preconditions
	 * @postconditions
	 */
	public int hashCode() {
		int hashCode;

		try {
			File thisLibarayFile = new File(this.pkcs11ModulePath_);
			hashCode = thisLibarayFile.getCanonicalPath().hashCode();
		} catch (IOException ex) {
			ex.printStackTrace();
			hashCode = pkcs11ModulePath_.hashCode();
		}

		return hashCode;
	}

	/**
	 * Returns the string representation of this object.
	 *
	 * @return The string representation of object
	 */
	public String toString() {
		StringBuffer buffer = new StringBuffer();

		buffer.append("Module Name: ");
		buffer.append(pkcs11ModulePath_);

		return buffer.toString();
	}

	/**
	 * Calls disconnect() to cleanup the native part of the wrapper. Once this
	 * method is called, this object cannot be used any longer. Any subsequent
	 * call to a C_* method will result in a runtime exception.
	 *
	 * @exception Throwable If finalization fails.
	 */
	public void finalize()
	    throws Throwable
	{
		disconnect();
		super.finalize();
	}

}


text:
package io.ray.streaming.runtime.transfer;

import com.google.common.base.Preconditions;
import io.ray.api.BaseActorHandle;
import io.ray.streaming.runtime.config.StreamingWorkerConfig;
import io.ray.streaming.runtime.config.types.TransferChannelType;
import io.ray.streaming.runtime.transfer.channel.ChannelId;
import io.ray.streaming.runtime.transfer.channel.ChannelRecoverInfo;
import io.ray.streaming.runtime.transfer.channel.ChannelRecoverInfo.ChannelCreationStatus;
import io.ray.streaming.runtime.transfer.channel.ChannelUtils;
import io.ray.streaming.runtime.transfer.channel.OffsetInfo;
import io.ray.streaming.runtime.transfer.message.BarrierMessage;
import io.ray.streaming.runtime.transfer.message.ChannelMessage;
import io.ray.streaming.runtime.transfer.message.DataMessage;
import io.ray.streaming.runtime.util.Platform;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * DataReader is wrapper of streaming c++ DataReader, which read data from channels of upstream
 * workers
 */
public class DataReader {

  private static final Logger LOG = LoggerFactory.getLogger(DataReader.class);

  private long nativeReaderPtr;
  // params set by getBundleNative: bundle data address + size
  private final ByteBuffer getBundleParams = ByteBuffer.allocateDirect(24);
  // We use direct buffer to reduce gc overhead and memory copy.
  private final ByteBuffer bundleData = Platform.wrapDirectBuffer(0, 0);
  private final ByteBuffer bundleMeta = ByteBuffer.allocateDirect(BundleMeta.LENGTH);

  private final Map<String, ChannelCreationStatus> queueCreationStatusMap = new HashMap<>();
  private Queue<ChannelMessage> buf = new LinkedList<>();

  {
    getBundleParams.order(ByteOrder.nativeOrder());
    bundleData.order(ByteOrder.nativeOrder());
    bundleMeta.order(ByteOrder.nativeOrder());
  }

  /**
   * @param inputChannels input channels ids
   * @param fromActors upstream input actors
   * @param workerConfig configuration
   */
  public DataReader(
      List<String> inputChannels,
      List<BaseActorHandle> fromActors,
      Map<String, OffsetInfo> checkpoints,
      StreamingWorkerConfig workerConfig) {
    Preconditions.checkArgument(inputChannels.size() > 0);
    Preconditions.checkArgument(inputChannels.size() == fromActors.size());
    ChannelCreationParametersBuilder initialParameters =
        new ChannelCreationParametersBuilder().buildInputQueueParameters(inputChannels, fromActors);
    byte[][] inputChannelsBytes =
        inputChannels.stream().map(ChannelId::idStrToBytes).toArray(byte[][]::new);

    // get sequence ID and message ID from OffsetInfo
    long[] msgIds = new long[inputChannels.size()];
    for (int i = 0; i < inputChannels.size(); i++) {
      String channelId = inputChannels.get(i);
      if (!checkpoints.containsKey(channelId)) {
        msgIds[i] = 0;
        continue;
      }
      msgIds[i] = checkpoints.get(inputChannels.get(i)).getStreamingMsgId();
    }
    long timerInterval = workerConfig.transferConfig.readerTimerIntervalMs();
    TransferChannelType channelType = workerConfig.transferConfig.channelType();
    boolean isMock = false;
    if (TransferChannelType.MEMORY_CHANNEL == channelType) {
      isMock = true;
    }

    // create native reader
    List<Integer> creationStatus = new ArrayList<>();
    this.nativeReaderPtr =
        createDataReaderNative(
            initialParameters,
            inputChannelsBytes,
            msgIds,
            timerInterval,
            creationStatus,
            ChannelUtils.toNativeConf(workerConfig),
            isMock);
    for (int i = 0; i < inputChannels.size(); ++i) {
      queueCreationStatusMap.put(
          inputChannels.get(i), ChannelCreationStatus.fromInt(creationStatus.get(i)));
    }
    LOG.info(
        "Create DataReader succeed for worker: {}, creation status={}.",
        workerConfig.workerInternalConfig.workerName(),
        queueCreationStatusMap);
  }

  private static native long createDataReaderNative(
      ChannelCreationParametersBuilder initialParameters,
      byte[][] inputChannels,
      long[] msgIds,
      long timerInterval,
      List<Integer> creationStatus,
      byte[] configBytes,
      boolean isMock);

  /**
   * Read message from input channels, if timeout, return null.
   *
   * @param timeoutMillis timeout
   * @return message or null
   */
  public ChannelMessage read(long timeoutMillis) {
    if (buf.isEmpty()) {
      getBundle(timeoutMillis);
      // if bundle not empty. empty message still has data size + seqId + msgId
      if (bundleData.position() < bundleData.limit()) {
        BundleMeta bundleMeta = new BundleMeta(this.bundleMeta);
        String channelID = bundleMeta.getChannelID();
        long timestamp = bundleMeta.getBundleTs();
        // barrier
        if (bundleMeta.getBundleType() == DataBundleType.BARRIER) {
          buf.offer(getBarrier(bundleData, channelID, timestamp));
        } else if (bundleMeta.getBundleType() == DataBundleType.BUNDLE) {
          for (int i = 0; i < bundleMeta.getMessageListSize(); i++) {
            buf.offer(getDataMessage(bundleData, channelID, timestamp));
          }
        }
      }
    }
    if (buf.isEmpty()) {
      return null;
    }
    return buf.poll();
  }

  public ChannelRecoverInfo getQueueRecoverInfo() {
    return new ChannelRecoverInfo(queueCreationStatusMap);
  }

  private String getQueueIdString(ByteBuffer buffer) {
    byte[] bytes = new byte[ChannelId.ID_LENGTH];
    buffer.get(bytes);
    return ChannelId.idBytesToStr(bytes);
  }

  private BarrierMessage getBarrier(ByteBuffer bundleData, String channelID, long timestamp) {
    ByteBuffer offsetsInfoBytes = ByteBuffer.wrap(getOffsetsInfoNative(nativeReaderPtr));
    offsetsInfoBytes.order(ByteOrder.nativeOrder());
    BarrierOffsetInfo offsetInfo = new BarrierOffsetInfo(offsetsInfoBytes);
    DataMessage message = getDataMessage(bundleData, channelID, timestamp);
    BarrierItem barrierItem = new BarrierItem(message, offsetInfo);
    return new BarrierMessage(
        message.getMsgId(),
        message.getTimestamp(),
        message.getChannelId(),
        barrierItem.getData(),
        barrierItem.getGlobalBarrierId(),
        barrierItem.getBarrierOffsetInfo().getQueueOffsetInfo());
  }

  private DataMessage getDataMessage(ByteBuffer bundleData, String channelID, long timestamp) {
    int dataSize = bundleData.getInt();
    // msgId
    long msgId = bundleData.getLong();
    // msgType
    bundleData.getInt();
    // make `data.capacity() == data.remaining()`, because some code used `capacity()`
    // rather than `remaining()`
    int position = bundleData.position();
    int limit = bundleData.limit();
    bundleData.limit(position + dataSize);
    ByteBuffer data = bundleData.slice();
    bundleData.limit(limit);
    bundleData.position(position + dataSize);
    return new DataMessage(data, timestamp, msgId, channelID);
  }

  private void getBundle(long timeoutMillis) {
    getBundleNative(
        nativeReaderPtr,
        timeoutMillis,
        Platform.getAddress(getBundleParams),
        Platform.getAddress(bundleMeta));
    bundleMeta.rewind();
    long bundleAddress = getBundleParams.getLong(0);
    int bundleSize = getBundleParams.getInt(8);
    // This has better performance than NewDirectBuffer or set address/capacity in jni.
    Platform.wrapDirectBuffer(bundleData, bundleAddress, bundleSize);
  }

  /** Stop reader */
  public void stop() {
    stopReaderNative(nativeReaderPtr);
  }

  /** Close reader to release resource */
  public void close() {
    if (nativeReaderPtr == 0) {
      return;
    }
    LOG.info("Closing DataReader.");
    closeReaderNative(nativeReaderPtr);
    nativeReaderPtr = 0;
    LOG.info("Finish closing DataReader.");
  }

  private native void getBundleNative(
      long nativeReaderPtr, long timeoutMillis, long params, long metaAddress);

  private native byte[] getOffsetsInfoNative(long nativeQueueConsumerPtr);

  private native void stopReaderNative(long nativeReaderPtr);

  private native void closeReaderNative(long nativeReaderPtr);

  enum DataBundleType {
    EMPTY(1),
    BARRIER(2),
    BUNDLE(3);

    int code;

    DataBundleType(int code) {
      this.code = code;
    }
  }

  public enum BarrierType {
    GLOBAL_BARRIER(0);
    private int code;

    BarrierType(int code) {
      this.code = code;
    }
  }

  class BundleMeta {

    // kMessageBundleHeaderSize + kUniqueIDSize:
    // magicNum(4b) + bundleTs(8b) + lastMessageId(8b) + messageListSize(4b)
    // + bundleType(4b) + rawBundleSize(4b) + channelID
    static final int LENGTH = 4 + 8 + 8 + 4 + 4 + 4 + ChannelId.ID_LENGTH;
    private int magicNum;
    private long bundleTs;
    private long lastMessageId;
    private int messageListSize;
    private DataBundleType bundleType;
    private String channelID;
    private int rawBundleSize;

    BundleMeta(ByteBuffer buffer) {
      // StreamingMessageBundleMeta Deserialization
      // magicNum
      magicNum = buffer.getInt();
      // messageBundleTs
      bundleTs = buffer.getLong();
      // lastOffsetSeqId
      lastMessageId = buffer.getLong();
      messageListSize = buffer.getInt();
      int typeInt = buffer.getInt();
      if (DataBundleType.BUNDLE.code == typeInt) {
        bundleType = DataBundleType.BUNDLE;
      } else if (DataBundleType.BARRIER.code == typeInt) {
        bundleType = DataBundleType.BARRIER;
      } else {
        bundleType = DataBundleType.EMPTY;
      }
      // rawBundleSize
      rawBundleSize = buffer.getInt();
      channelID = getQueueIdString(buffer);
    }

    public int getMagicNum() {
      return magicNum;
    }

    public long getBundleTs() {
      return bundleTs;
    }

    public long getLastMessageId() {
      return lastMessageId;
    }

    public int getMessageListSize() {
      return messageListSize;
    }

    public DataBundleType getBundleType() {
      return bundleType;
    }

    public String getChannelID() {
      return channelID;
    }

    public int getRawBundleSize() {
      return rawBundleSize;
    }
  }

  class BarrierOffsetInfo {

    private int queueSize;
    private Map<String, OffsetInfo> queueOffsetInfo;

    public BarrierOffsetInfo(ByteBuffer buffer) {
      // deserialization offset
      queueSize = buffer.getInt();
      queueOffsetInfo = new HashMap<>(queueSize);
      for (int i = 0; i < queueSize; ++i) {
        String qid = getQueueIdString(buffer);
        long streamingMsgId = buffer.getLong();
        queueOffsetInfo.put(qid, new OffsetInfo(streamingMsgId));
      }
    }

    public int getQueueSize() {
      return queueSize;
    }

    public Map<String, OffsetInfo> getQueueOffsetInfo() {
      return queueOffsetInfo;
    }
  }

  class BarrierItem {

    BarrierOffsetInfo barrierOffsetInfo;
    private long msgId;
    private BarrierType barrierType;
    private long globalBarrierId;
    private ByteBuffer data;

    public BarrierItem(DataMessage message, BarrierOffsetInfo barrierOffsetInfo) {
      this.barrierOffsetInfo = barrierOffsetInfo;
      msgId = message.getMsgId();
      ByteBuffer buffer = message.body();
      // c++ use native order, so use native order here.
      buffer.order(ByteOrder.nativeOrder());
      int barrierTypeInt = buffer.getInt();
      globalBarrierId = buffer.getLong();
      // dataSize includes: barrier type(32 bit), globalBarrierId, data
      data = buffer.slice();
      data.order(ByteOrder.nativeOrder());
      buffer.position(buffer.limit());
      barrierType = BarrierType.GLOBAL_BARRIER;
    }

    public long getBarrierMsgId() {
      return msgId;
    }

    public BarrierType getBarrierType() {
      return barrierType;
    }

    public long getGlobalBarrierId() {
      return globalBarrierId;
    }

    public ByteBuffer getData() {
      return data;
    }

    public BarrierOffsetInfo getBarrierOffsetInfo() {
      return barrierOffsetInfo;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
class MessageString {
    std::vector<std::string> mMessage;

public:
    MessageString();

    bool Read(Resources &res, const std::string &fileName);
    bool Read(IOBuffer &buffer);

    inline const std::string &At(int n) { return mMessage[n - 1]; }
};


text:
package com.intel.sparkbench.datagen.convert

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.io.Text
import org.apache.spark.SparkContext._
import org.apache.spark.{SparkConf, SparkContext}

object BayesConvert{
  val conf = new Configuration()
  def main(args: Array[String]){
    if (args.length!=1){
      System.err.println("Usage: Convert <input_path>")
      System.exit(1)
    }

    val sparkConf = new SparkConf().setAppName("HiBench Bayes Converter")
    val sc = new SparkContext(sparkConf)

    val input_path =   args(0)  //"hdfs://localhost:54310/HiBench/Bayes/Input"
    val output_vector_name = input_path + "/vectors.txt"
    val parallel = sc.getConf.getInt("spark.default.parallelism", sc.defaultParallelism)

    val data = sc.sequenceFile[Text, Text](input_path).map{case(k, v) => (k.toString, v.toString)}

    data.repartition(parallel)
    val wordcount = data.flatMap{case(key, doc) => doc.split(" ")}
                        .map(word => (word, 1))
                        .reduceByKey(_ + _)
    val wordsum = wordcount.map(_._2).reduce(_ + _)

    val word_dict = wordcount.zipWithIndex()
                             .map{case ((key, count), index) =>
                                  (key, (index, count.toDouble / wordsum))}
                             .collectAsMap()
    val shared_word_dict = sc.broadcast(word_dict)

    // for each document, generate vector based on word freq
    val vector = data.map { case (key, doc) =>
      val doc_vector = doc.split(" ").map(x => shared_word_dict.value(x)) //map to word index: freq
        .groupBy(_._1) // combine freq with same word
        .map { case (k, v) => (k, v.map(_._2).sum)}

      val sorted_doc_vector = doc_vector.toList.sortBy(_._1)
        .map { case (k, v) => "%d:%f".format(k + 1,  // LIBSVM's index starts from 1 !!!
                                             v)} // convert to LIBSVM format

      // key := /classXXX
      // key.substring(6) := XXX
      // label index1:value1 index2:value2 ...
      key.substring(6) + " " + sorted_doc_vector.mkString(" ")
    }
    vector.saveAsTextFile(output_vector_name)
    sc.stop()
  }
}


text:
namespace g{namespace Uno{namespace Platform{struct FrameChangedEventArgs;}}}

namespace g{
namespace Uno{
namespace Platform{

// public sealed class FrameChangedEventArgs :170
// {
uType* FrameChangedEventArgs_typeof();
void FrameChangedEventArgs__ctor_1_fn(FrameChangedEventArgs* __this, ::g::Uno::Rect* newFrame);
void FrameChangedEventArgs__New2_fn(::g::Uno::Rect* newFrame, FrameChangedEventArgs** __retval);
void FrameChangedEventArgs__get_NewFrame_fn(FrameChangedEventArgs* __this, ::g::Uno::Rect* __retval);
void FrameChangedEventArgs__set_NewFrame_fn(FrameChangedEventArgs* __this, ::g::Uno::Rect* value);

struct FrameChangedEventArgs : ::g::Uno::EventArgs
{
    ::g::Uno::Rect _NewFrame;

    void ctor_1(::g::Uno::Rect newFrame);
    ::g::Uno::Rect NewFrame();
    void NewFrame(::g::Uno::Rect value);
    static FrameChangedEventArgs* New2(::g::Uno::Rect newFrame);
};
// }

}}} // ::g::Uno::Platform


text:
.class abstract Lcom/google/common/hash/AbstractStreamingHashFunction;
.super Ljava/lang/Object;
.source "AbstractStreamingHashFunction.java"

# interfaces
.implements Lcom/google/common/hash/HashFunction;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/google/common/hash/AbstractStreamingHashFunction$AbstractStreamingHasher;
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 35
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 69
    return-void
.end method

# virtual methods
.method public hashBytes([B)Lcom/google/common/hash/HashCode;
    .locals 1
    .param p1, "input"    # [B

    .prologue
    .line 49
    invoke-virtual {p0}, Lcom/google/common/hash/AbstractStreamingHashFunction;->newHasher()Lcom/google/common/hash/Hasher;

    move-result-object v0

    invoke-interface {v0, p1}, Lcom/google/common/hash/Hasher;->putBytes([B)Lcom/google/common/hash/Hasher;

    move-result-object v0

    invoke-interface {v0}, Lcom/google/common/hash/Hasher;->hash()Lcom/google/common/hash/HashCode;

    move-result-object v0

    return-object v0
.end method

.method public hashBytes([BII)Lcom/google/common/hash/HashCode;
    .locals 1
    .param p1, "input"    # [B
    .param p2, "off"    # I
    .param p3, "len"    # I

    .prologue
    .line 53
    invoke-virtual {p0}, Lcom/google/common/hash/AbstractStreamingHashFunction;->newHasher()Lcom/google/common/hash/Hasher;

    move-result-object v0

    invoke-interface {v0, p1, p2, p3}, Lcom/google/common/hash/Hasher;->putBytes([BII)Lcom/google/common/hash/Hasher;

    move-result-object v0

    invoke-interface {v0}, Lcom/google/common/hash/Hasher;->hash()Lcom/google/common/hash/HashCode;

    move-result-object v0

    return-object v0
.end method

.method public hashLong(J)Lcom/google/common/hash/HashCode;
    .locals 1
    .param p1, "input"    # J

    .prologue
    .line 45
    invoke-virtual {p0}, Lcom/google/common/hash/AbstractStreamingHashFunction;->newHasher()Lcom/google/common/hash/Hasher;

    move-result-object v0

    invoke-interface {v0, p1, p2}, Lcom/google/common/hash/Hasher;->putLong(J)Lcom/google/common/hash/Hasher;

    move-result-object v0

    invoke-interface {v0}, Lcom/google/common/hash/Hasher;->hash()Lcom/google/common/hash/HashCode;

    move-result-object v0

    return-object v0
.end method

.method public hashString(Ljava/lang/CharSequence;)Lcom/google/common/hash/HashCode;
    .locals 1
    .param p1, "input"    # Ljava/lang/CharSequence;

    .prologue
    .line 37
    invoke-virtual {p0}, Lcom/google/common/hash/AbstractStreamingHashFunction;->newHasher()Lcom/google/common/hash/Hasher;

    move-result-object v0

    invoke-interface {v0, p1}, Lcom/google/common/hash/Hasher;->putString(Ljava/lang/CharSequence;)Lcom/google/common/hash/Hasher;

    move-result-object v0

    invoke-interface {v0}, Lcom/google/common/hash/Hasher;->hash()Lcom/google/common/hash/HashCode;

    move-result-object v0

    return-object v0
.end method

.method public hashString(Ljava/lang/CharSequence;Ljava/nio/charset/Charset;)Lcom/google/common/hash/HashCode;
    .locals 1
    .param p1, "input"    # Ljava/lang/CharSequence;
    .param p2, "charset"    # Ljava/nio/charset/Charset;

    .prologue
    .line 41
    invoke-virtual {p0}, Lcom/google/common/hash/AbstractStreamingHashFunction;->newHasher()Lcom/google/common/hash/Hasher;

    move-result-object v0

    invoke-interface {v0, p1, p2}, Lcom/google/common/hash/Hasher;->putString(Ljava/lang/CharSequence;Ljava/nio/charset/Charset;)Lcom/google/common/hash/Hasher;

    move-result-object v0

    invoke-interface {v0}, Lcom/google/common/hash/Hasher;->hash()Lcom/google/common/hash/HashCode;

    move-result-object v0

    return-object v0
.end method

.method public newHasher(I)Lcom/google/common/hash/Hasher;
    .locals 1
    .param p1, "expectedInputSize"    # I

    .prologue
    .line 57
    if-ltz p1, :cond_0

    const/4 v0, 0x1

    :goto_0
    invoke-static {v0}, Lcom/google/common/base/Preconditions;->checkArgument(Z)V

    .line 58
    invoke-virtual {p0}, Lcom/google/common/hash/AbstractStreamingHashFunction;->newHasher()Lcom/google/common/hash/Hasher;

    move-result-object v0

    return-object v0

    .line 57
    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method


text:
package org.ovirt.mobile.movirt.model.trigger;

import android.content.ContentValues;
import android.net.Uri;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

import org.ovirt.mobile.movirt.R;
import org.ovirt.mobile.movirt.model.base.BaseEntity;
import org.ovirt.mobile.movirt.model.condition.Condition;
import org.ovirt.mobile.movirt.model.condition.ConditionPersister;
import org.ovirt.mobile.movirt.model.mapping.EntityType;
import org.ovirt.mobile.movirt.provider.OVirtContract;
import org.ovirt.mobile.movirt.util.CursorHelper;
import org.ovirt.mobile.movirt.util.HasDisplayResourceId;
import org.ovirt.mobile.movirt.util.JsonUtils;

import static org.ovirt.mobile.movirt.provider.OVirtContract.Trigger.TABLE;

@DatabaseTable(tableName = TABLE)
public class Trigger extends BaseEntity<Integer> implements OVirtContract.Trigger {

    @Override
    public Uri getBaseUri() {
        return CONTENT_URI;
    }

    public enum NotificationType implements HasDisplayResourceId {
        INFO(R.string.notification_type_info),
        CRITICAL(R.string.notification_type_critical);

        private final int displayResource;

        NotificationType(int displayResource) {
            this.displayResource = displayResource;
        }

        @Override
        public int getDisplayResourceId() {
            return displayResource;
        }
    }

    @DatabaseField(columnName = ID, generatedId = true, allowGeneratedIdInsert = true)
    private int id;

    @DatabaseField(columnName = ACCOUNT_ID, canBeNull = true)
    private String accountId;

    @DatabaseField(columnName = CLUSTER_ID, canBeNull = true)
    private String clusterId;

    @DatabaseField(columnName = TARGET_ID, canBeNull = true)
    private String targetId;

    @DatabaseField(columnName = NOTIFICATION, canBeNull = false)
    private NotificationType notificationType;

    @DatabaseField(columnName = CONDITION, canBeNull = false, persisterClass = ConditionPersister.class)
    private Condition condition;

    @DatabaseField(columnName = ENTITY_TYPE, canBeNull = false)
    private EntityType entityType;

    @Override
    public Integer getId() {
        return id;
    }

    @Override
    public void setId(Integer id) {
        this.id = id;
    }

    public String getAccountId() {
        return accountId;
    }

    public void setAccountId(String accountId) {
        this.accountId = accountId;
    }

    public String getClusterId() {
        return clusterId;
    }

    public void setClusterId(String clusterId) {
        this.clusterId = clusterId;
    }

    public String getTargetId() {
        return targetId;
    }

    public void setTargetId(String targetId) {
        this.targetId = targetId;
    }

    public NotificationType getNotificationType() {
        return notificationType;
    }

    public void setNotificationType(NotificationType notificationType) {
        this.notificationType = notificationType;
    }

    public <E extends BaseEntity<?>> Condition<E> getCondition() {
        return condition;
    }

    public <E extends BaseEntity<?>> void setCondition(Condition<E> condition) {
        this.condition = condition;
    }

    public EntityType getEntityType() {
        return entityType;
    }

    public void setEntityType(EntityType entityType) {
        this.entityType = entityType;
    }

    @Override
    public ContentValues toValues() {
        ContentValues contentValues = new ContentValues();
        if (id != 0) {
            contentValues.put(ID, id);
        }
        contentValues.put(ACCOUNT_ID, accountId);
        contentValues.put(CLUSTER_ID, clusterId);
        contentValues.put(TARGET_ID, targetId);
        contentValues.put(NOTIFICATION, notificationType.toString());
        contentValues.put(CONDITION, JsonUtils.objectToString(condition));
        contentValues.put(ENTITY_TYPE, entityType.toString());
        return contentValues;
    }

    @Override
    public void initFromCursorHelper(CursorHelper cursorHelper) {
        setId(cursorHelper.getInt(OVirtContract.Trigger.ID));
        setAccountId(cursorHelper.getString(OVirtContract.Trigger.ACCOUNT_ID));
        setClusterId(cursorHelper.getString(OVirtContract.Trigger.CLUSTER_ID));
        setTargetId(cursorHelper.getString(OVirtContract.Trigger.TARGET_ID));
        setNotificationType(cursorHelper.getEnum(OVirtContract.Trigger.NOTIFICATION, Trigger.NotificationType.class));
        setCondition(cursorHelper.getJson(OVirtContract.Trigger.CONDITION, Condition.class));
        setEntityType(cursorHelper.getEnum(OVirtContract.Trigger.ENTITY_TYPE, EntityType.class));
    }

    @Override
    public String toString() {
        return condition == null ? "" : condition.toString();
    }
}


text:
<?php

namespace Fakerino\DataSource;

use Fakerino\DataSource\File\File;

/**
 * Class FakeFileContainer,
 * is a container that stores File object,
 * it's useful for avoiding multiple construction of a same object.
 *
 * @author Nicola Pietroluongo <nik.longstone@gmail.com>
 */
class FakeFileContainer
{
    /**
     * @var array
     */
    protected static $files = array();

    /**
     * Adds a file to the container.
     *
     * @param string $name
     * @param File   $file
     */
    public static function add($name, File $file)
    {
        self::$files[$name] = $file;
    }

    /**
     * Gets a file from container,
     * or create a new one if not present.
     *
     * @param string $filePath
     *
     * @return File
     */
    public static function get($filePath)
    {
        $fileName = basename($filePath);
        if (!array_key_exists($fileName, static::$files)) {
            try {
                $file = new File($filePath);
            } catch (\Exception $e) {
                $file = false;
            }

            static::$files[$fileName] = $file;
        }

        return static::$files[$fileName];
    }
}


text:
package com.hazelcast.client.impl.protocol.codec.custom;

import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.Generated;
import com.hazelcast.client.impl.protocol.codec.builtin.*;

import static com.hazelcast.client.impl.protocol.codec.builtin.CodecUtil.fastForwardToEndFrame;
import static com.hazelcast.client.impl.protocol.ClientMessage.*;
import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.*;

@Generated("da3e5e9e4be9e523308d1927fd42c8fc")
public final class EvictionConfigHolderCodec {
    private static final int SIZE_FIELD_OFFSET = 0;
    private static final int INITIAL_FRAME_SIZE = SIZE_FIELD_OFFSET + INT_SIZE_IN_BYTES;

    private EvictionConfigHolderCodec() {
    }

    public static void encode(ClientMessage clientMessage, com.hazelcast.client.impl.protocol.task.dynamicconfig.EvictionConfigHolder evictionConfigHolder) {
        clientMessage.add(BEGIN_FRAME.copy());

        ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[INITIAL_FRAME_SIZE]);
        encodeInt(initialFrame.content, SIZE_FIELD_OFFSET, evictionConfigHolder.getSize());
        clientMessage.add(initialFrame);

        StringCodec.encode(clientMessage, evictionConfigHolder.getMaxSizePolicy());
        StringCodec.encode(clientMessage, evictionConfigHolder.getEvictionPolicy());
        CodecUtil.encodeNullable(clientMessage, evictionConfigHolder.getComparatorClassName(), StringCodec::encode);
        CodecUtil.encodeNullable(clientMessage, evictionConfigHolder.getComparator(), DataCodec::encode);

        clientMessage.add(END_FRAME.copy());
    }

    public static com.hazelcast.client.impl.protocol.task.dynamicconfig.EvictionConfigHolder decode(ClientMessage.ForwardFrameIterator iterator) {
        // begin frame
        iterator.next();

        ClientMessage.Frame initialFrame = iterator.next();
        int size = decodeInt(initialFrame.content, SIZE_FIELD_OFFSET);

        java.lang.String maxSizePolicy = StringCodec.decode(iterator);
        java.lang.String evictionPolicy = StringCodec.decode(iterator);
        java.lang.String comparatorClassName = CodecUtil.decodeNullable(iterator, StringCodec::decode);
        com.hazelcast.internal.serialization.Data comparator = CodecUtil.decodeNullable(iterator, DataCodec::decode);

        fastForwardToEndFrame(iterator);

        return new com.hazelcast.client.impl.protocol.task.dynamicconfig.EvictionConfigHolder(size, maxSizePolicy, evictionPolicy, comparatorClassName, comparator);
    }
}


text:
<?php

function auth_user($param=array()) {
       $CI =& get_instance();
       if($CI->session->userdata('ss_log') == '') {
              $CI->session->set_flashdata('info_log', '
 Please login.
');
              redirect(base_url().'Login');
       }

       if( isset($param['ss_emp_level'])) {
              if($CI->session->userdata('ss_emp_level') != $param['ss_emp_level']) {
                     $CI->session->set_flashdata('info', '
 Maaf, hak akses Anda tidak memenuhi syarat untuk akses halaman tersebut.
');
                     if( isset($param['auth_redirect'])) {
                            redirect($param['auth_redirect']);
                     }
                     redirect(base_url().'log');
              }
       }
}

function display($data=null , $break = null){
       if($break == 1){
              echo "
";
                     print_r($data);
              echo  "
";
              die;
       }else{
              echo "
";
                     print_r($data);
              echo  "
";
       }
}

function getMonth($month){
       switch ($month) {
              case '01':
                     $displayMonth ="January";
                     break;
              case '02':
                     $displayMonth ="February";
                     break;
              case '03':
                     $displayMonth ="March";
                     break;
              case '04':
                     $displayMonth ="April";
                     break;
              case '05':
                     $displayMonth ="May";
                     break;
              case '06':
                     $displayMonth ="June";
                     break;
              case '07':
                     $displayMonth ="July";
                     break;
              case '08':
                     $displayMonth ="August";
                     break;
              case '09':
                     $displayMonth ="September";
                     break;
              case '10':
                     $displayMonth ="October";
                     break;
              case '11':
                     $displayMonth ="November";
                     break;
              case '12':
                     $displayMonth ="December";
                     break;
       }
       return $displayMonth;

}


text:
layout: error
title: Error 404
sitemap: false
permalink: /404.html
---

Lo sentimos esta página no existia. [Inicio]({{ site.baseurl }}/).


text:
Make is a tool which is typically used to control the generation of executables and other non-source files of a program from the program's source files. More generally, Make can be used to run a series of instructions depending on what files have changed.

## Makefiles

Makefiles are used to help decide which parts of a large program need to be recompiled. In the vast majority of cases, C or C++ files are compiled.

It can be used beyond programs too, when you need a series of instructions to run depending on what files have changed.

- The default target is the first target.
- `clean` is often used as a target that removes the output of other targets, but it is not a special word in `make`.
- When there are multiple targets for a rule, the commands will be run for each target.
- `$@` is an automatic variable that contains the target name.

### Syntax

A Makefile consists of a set of rules. A rule generally looks like this:

```Makefile
targets: prerequisites
	command
	command
	command
```

- The targets are file names, separated by spaces. Typically, there is only one per rule.
- The commands are a series of steps typically used to make the target(s). These need to start with a tab character, not spaces.
- The prerequisites are also file names, separated by spaces. These files need to exist before the commands for the target are run. These are also called dependencies.