RPCCLIENT(1) User Commands RPCCLIENT(1) NAME rpcclient - tool for executing client side MS-RPC functions SYNOPSIS rpcclient [-A authfile] [-c <command string>] [-d debuglevel] [-h] [-l logdir] [-N] [-s <smb config file>] [-U username[%password]] [-W workgroup] [-I destinationIP] {server} DESCRIPTION This tool is part of the samba(7) suite. rpcclient is a utility initially developed to test MS-RPC functionality in Samba itself. It has undergone several stages of development and stability. Many system administrators have now written scripts around it to manage Windows NT clients from their UNIX workstation. OPTIONS server NetBIOS name of Server to which to connect. The server can be any SMB/CIFS server. The name is resolved using the name resolve order line from smb.conf(5). -c|--command=<command string> Execute semicolon separated commands (listed below) -I|--dest-ip IP-address IP address is the address of the server to connect to. It should be specified in standard "a.b.c.d" notation. Normally the client would attempt to locate a named SMB/CIFS server by looking it up via the NetBIOS name resolution mechanism described above in the name resolve order parameter above. Using this parameter will force the client to assume that the server is on the machine with the specified IP address and the NetBIOS name component of the resource being connected to will be ignored. There is no default for this parameter. If not supplied, it will be determined automatically by the client as described above. -p|--port port This number is the TCP port number that will be used when making connections to the server. The standard (well-known) TCP port number for an SMB/CIFS server is 139, which is the default. -d|--debuglevel=level level is an integer from 0 to 10. The default value if this parameter is not specified is 0. The higher this value, the more detail will be logged to the log files about the activities of the server. At level 0, only critical errors and serious warnings will be logged. Level 1 is a reasonable level for day-to-day running - it generates a small amount of information about operations carried out. Levels above 1 will generate considerable amounts of log data, and should only be used when investigating a problem. Levels above 3 are designed for use only by developers and generate HUGE amounts of log data, most of which is extremely cryptic. Note that specifying this parameter here will override the smb.conf.5.html# parameter in the smb.conf file. -V|--version Prints the program version number. -s|--configfile <configuration file> The file specified contains the configuration details required by the server. The information in this file includes server-specific information such as what printcap file to use, as well as descriptions of all the services that the server is to provide. See smb.conf for more information. The default configuration file name is determined at compile time. -l|--log-basename=logdirectory Base directory name for log/debug files. The extension ".progname" will be appended (e.g. log.smbclient, log.smbd, etc...). The log file is never removed by the client. -N|--no-pass If specified, this parameter suppresses the normal password prompt from the client to the user. This is useful when accessing a service that does not require a password. Unless a password is specified on the command line or this parameter is specified, the client will request a password. If a password is specified on the command line and this option is also defined the password on the command line will be silently ingnored and no password will be used. -k|--kerberos Try to authenticate with kerberos. Only useful in an Active Directory environment. -C|--use-ccache Try to use the credentials cached by winbind. -A|--authentication-file=filename This option allows you to specify a file from which to read the username and password used in the connection. The format of the file is username = <value> password = <value> domain = <value> Make certain that the permissions on the file restrict access from unwanted users. -U|--user=username[%password] Sets the SMB username or username and password. If %password is not specified, the user will be prompted. The client will first check the USER environment variable, then the LOGNAME variable and if either exists, the string is uppercased. If these environmental variables are not found, the username GUEST is used. A third option is to use a credentials file which contains the plaintext of the username and password. This option is mainly provided for scripts where the admin does not wish to pass the credentials on the command line or via environment variables. If this method is used, make certain that the permissions on the file restrict access from unwanted users. See the -A for more details. Be cautious about including passwords in scripts. Also, on many systems the command line of a running process may be seen via the ps command. To be safe always allow rpcclient to prompt for a password and type it in directly. -n|--netbiosname <primary NetBIOS name> This option allows you to override the NetBIOS name that Samba uses for itself. This is identical to setting the smb.conf.5.html# parameter in the smb.conf file. However, a command line setting will take precedence over settings in smb.conf. -i|--scope <scope> This specifies a NetBIOS scope that nmblookup will use to communicate with when generating NetBIOS names. For details on the use of NetBIOS scopes, see rfc1001.txt and rfc1002.txt. NetBIOS scopes are very rarely used, only set this parameter if you are the system administrator in charge of all the NetBIOS systems you communicate with. -W|--workgroup=domain Set the SMB domain of the username. This overrides the default domain which is the domain defined in smb.conf. If the domain specified is the same as the servers NetBIOS name, it causes the client to log on using the servers local SAM (as opposed to the Domain SAM). -O|--socket-options socket options TCP socket options to set on the client socket. See the socket options parameter in the smb.conf manual page for the list of valid options. -h|--help Print a summary of command line options. COMMANDS LSARPC lsaquery Query info policy lookupsids Resolve a list of SIDs to usernames. lookupnames Resolve a list of usernames to SIDs. enumtrusts Enumerate trusted domains enumprivs Enumerate privileges getdispname Get the privilege name lsaenumsid Enumerate the LSA SIDS lsaenumprivsaccount Enumerate the privileges of an SID lsaenumacctrights Enumerate the rights of an SID lsaenumacctwithright Enumerate accounts with a right lsaaddacctrights Add rights to an account lsaremoveacctrights Remove rights from an account lsalookupprivvalue Get a privilege value given its name lsaquerysecobj Query LSA security object LSARPC-DS dsroledominfo Get Primary Domain Information DFS dfsexist Query DFS support dfsadd Add a DFS share dfsremove Remove a DFS share dfsgetinfo Query DFS share info dfsenum Enumerate dfs shares REG shutdown Remote Shutdown abortshutdown Abort Shutdown SRVSVC srvinfo Server query info netshareenum Enumerate shares netfileenum Enumerate open files netremotetod Fetch remote time of day SAMR queryuser Query user info querygroup Query group info queryusergroups Query user groups querygroupmem Query group membership queryaliasmem Query alias membership querydispinfo Query display info querydominfo Query domain info enumdomusers Enumerate domain users enumdomgroups Enumerate domain groups enumalsgroups Enumerate alias groups createdomuser Create domain user samlookupnames Look up names samlookuprids Look up names deletedomuser Delete domain user samquerysecobj Query SAMR security object getdompwinfo Retrieve domain password info lookupdomain Look up domain SPOOLSS adddriver <arch> <config> [<version>] Execute an AddPrinterDriver() RPC to install the printer driver information on the server. Note that the driver files should already exist in the directory returned by getdriverdir. Possible values for arch are the same as those for the getdriverdir command. The config parameter is defined as follows: Long Printer Name:\ Driver File Name:\ Data File Name:\ Config File Name:\ Help File Name:\ Language Monitor Name:\ Default Data Type:\ Comma Separated list of Files Any empty fields should be enter as the string "NULL". Samba does not need to support the concept of Print Monitors since these only apply to local printers whose driver can make use of a bi-directional link for communication. This field should be "NULL". On a remote NT print server, the Print Monitor for a driver must already be installed prior to adding the driver or else the RPC will fail. The version parameter lets you specify the printer driver version number. If omitted, the default driver version for the specified architecture will be used. This option can be used to upload Windows 2000 (version 3) printer drivers. addprinter <printername> <sharename> <drivername> <port> Add a printer on the remote server. This printer will be automatically shared. Be aware that the printer driver must already be installed on the server (see adddriver) and the portmust be a valid port name (see enumports. deldriver <driver> Delete the specified printer driver for all architectures. This does not delete the actual driver files from the server, only the entry from the server´s list of drivers. deldriverex <driver> [architecture] [version] Delete the specified printer driver including driver files. You can limit this action to a specific architecture and a specific version. If no architecure is given, all driver files of that driver will be deleted. enumdata Enumerate all printer setting data stored on the server. On Windows NT clients, these values are stored in the registry, while Samba servers store them in the printers TDB. This command corresponds to the MS Platform SDK GetPrinterData() function (* This command is currently unimplemented). enumdataex Enumerate printer data for a key enumjobs <printer> List the jobs and status of a given printer. This command corresponds to the MS Platform SDK EnumJobs() function enumkey Enumerate printer keys enumports [level] Executes an EnumPorts() call using the specified info level. Currently only info levels 1 and 2 are supported. enumdrivers [level] Execute an EnumPrinterDrivers() call. This lists the various installed printer drivers for all architectures. Refer to the MS Platform SDK documentation for more details of the various flags and calling options. Currently supported info levels are 1, 2, and 3. enumprinters [level] Execute an EnumPrinters() call. This lists the various installed and share printers. Refer to the MS Platform SDK documentation for more details of the various flags and calling options. Currently supported info levels are 1, 2 and 5. getdata <printername> <valuename;> Retrieve the data for a given printer setting. See the enumdata command for more information. This command corresponds to the GetPrinterData() MS Platform SDK function. getdataex Get printer driver data with keyname getdriver <printername> Retrieve the printer driver information (such as driver file, config file, dependent files, etc...) for the given printer. This command corresponds to the GetPrinterDriver() MS Platform SDK function. Currently info level 1, 2, and 3 are supported. getdriverdir <arch> Execute a GetPrinterDriverDirectory() RPC to retrieve the SMB share name and subdirectory for storing printer driver files for a given architecture. Possible values for arch are "Windows 4.0" (for Windows 95/98), "Windows NT x86", "Windows NT PowerPC", "Windows Alpha_AXP", and "Windows NT R4000". getprinter <printername> Retrieve the current printer information. This command corresponds to the GetPrinter() MS Platform SDK function. getprintprocdir Get print processor directory openprinter <printername> Execute an OpenPrinterEx() and ClosePrinter() RPC against a given printer. setdriver <printername> <drivername> Execute a SetPrinter() command to update the printer driver associated with an installed printer. The printer driver must already be correctly installed on the print server. See also the enumprinters and enumdrivers commands for obtaining a list of of installed printers and drivers. addform Add form setform Set form getform Get form deleteform Delete form enumforms Enumerate form setprinter Set printer comment setprinterdata Set REG_SZ printer data setprintername <printername> <newprintername> Set printer name rffpcnex Rffpcnex test NETLOGON logonctrl2 Logon Control 2 logonctrl Logon Control samsync Sam Synchronisation samdeltas Query Sam Deltas samlogon Sam Logon GENERAL COMMANDS debuglevel Set the current debug level used to log information. help (?) Print a listing of all known commands or extended help on a particular command. quit (exit) Exit rpcclient. BUGS rpcclient is designed as a developer testing tool and may not be robust in certain areas (such as command line parsing). It has been known to generate a core dump upon failures when invalid parameters where passed to the interpreter. From Luke Leighton´s original rpcclient man page: WARNING! The MSRPC over SMB code has been developed from examining Network traces. No documentation is available from the original creators (Microsoft) on how MSRPC over SMB works, or how the individual MSRPC services work. Microsoft´s implementation of these services has been demonstrated (and reported) to be... a bit flaky in places. The development of Samba´s implementation is also a bit rough, and as more of the services are understood, it can even result in versions of smbd(8) and rpcclient(1) that are incompatible for some commands or services. Additionally, the developers are sending reports to Microsoft, and problems found or reported to Microsoft are fixed in Service Packs, which may result in incompatibilities. VERSION This man page is correct for version 3 of the Samba suite. AUTHOR The original Samba software and related utilities were created by Andrew Tridgell. Samba is now developed by the Samba Team as an Open Source project similar to the way the Linux kernel is developed. The original rpcclient man page was written by Matthew Geddes, Luke Kenneth Casson Leighton, and rewritten by Gerald Carter. The conversion to DocBook for Samba 2.2 was done by Gerald Carter. The conversion to DocBook XML 4.2 for Samba 3.0 was done by Alexander Bokovoy. Samba 3.6 06/22/2012 RPCCLIENT(1)


First name is required
First name is invalid
Last name is required
Last name is invalid
Email address is required
Email address is invalid
Document number is required
Document number is invalid
Could not verify for '{{ctrl.firstName}} {{ctrl.lastName}}'


Testing is an integral part of enterprise software development. This chapter focuses on the value-add of the IoC principle to unit testing and on the benefits of Spring Framework integration testing. (A thorough treatment of testing in the enterprise is beyond the scope of this chapter.)
Dependency Injection should make your code less dependent on the
container than it would be with traditional Java EE development. The POJOs
that make up your application should be testable in JUnit or TestNG tests,
with objects simply instantiated using the new
operator, without Spring or any other container. You
can use mock objects (in conjunction
with other valuable testing techniques) to test your code in isolation. If
you follow the architecture recommendations for Spring, the resulting
clean layering and componentization of your codebase will facilitate
easier unit testing. For example, you can test service layer objects by
stubbing or mocking DAO or Repository interfaces, without needing to
access persistent data while running unit tests.
True unit tests typically run extremely quickly, as there is no runtime infrastructure to set up. Emphasizing true unit tests as part of your development methodology will boost your productivity. You may not need this section of the testing chapter to help you write effective unit tests for your IoC-based applications. For certain unit testing scenarios, however, the Spring Framework provides the following mock objects and testing support classes.
The org.springframework.mock.jndi
package
contains an implementation of the JNDI SPI, which you can use to set
up a simple JNDI environment for test suites or stand-alone
applications. If, for example, JDBC DataSource
s
get bound to the same JNDI names in test code as within a Java EE
container, you can reuse both application code and configuration in
testing scenarios without modification.
The org.springframework.mock.web
package
contains a comprehensive set of Servlet API mock objects, targeted at
usage with Spring's Web MVC framework, which are useful for testing
web contexts and controllers. These mock objects are generally more
convenient to use than dynamic mock objects such as EasyMock or existing Servlet API
mock objects such as MockObjects.
The org.springframework.test.util
package
contains ReflectionTestUtils
, which is a
collection of reflection-based utility methods. Developers use these
methods in unit and integration testing scenarios in which they need
to set a non-public
field or invoke a
non-public
setter method when testing application
code involving, for example:
ORM frameworks such as JPA and Hibernate that condone
private
or protected
field
access as opposed to public
setter methods for
properties in a domain entity.
Spring's support for annotations such as
@Autowired
and
@Resource,
which provides
dependency injection for private
or
protected
fields, setter methods, and
configuration methods
The org.springframework.test.web
package
contains ModelAndViewAssert
, which you can use
in combination with JUnit 4+, TestNG, and so on for unit tests dealing
with Spring MVC ModelAndView
objects.
| Unit testing Spring MVC Controllers | |
|---|---|
To test your Spring MVC |
It is important to be able to perform some integration testing without requiring deployment to your application server or connecting to other enterprise infrastructure. This will enable you to test things such as:
The correct wiring of your Spring IoC container contexts.
Data access using JDBC or an ORM tool. This would include such things as the correctness of SQL statements, Hibernate queries, JPA entity mappings, etc.
The Spring Framework provides first class support for
integration testing in
the spring-test
module.
The name of the actual jar file might include the release
version and might also be in the
long org.springframework.test
form,
depending on where you got it from (see
the section on Dependency
Management for an explanation). This library includes
the org.springframework.test
package, which
contains valuable classes for integration testing with a Spring
container. This testing does not rely on an application server
or other deployment environment. Such tests are slower to run
than unit tests but much faster than the equivalent Cactus
tests or remote tests that rely on deployment to an application
server.
In Spring 2.5 and later, unit and integration testing support is provided in the form of the annotation-driven Spring TestContext Framework. The TestContext Framework is agnostic of the actual testing framework in use, thus allowing instrumentation of tests in various environments including JUnit, TestNG, and so on.
| Legacy JUnit 3.8 class hierarchy is deprecated | |
|---|---|
As of Spring 3.0, the legacy JUnit 3.8 base class hierarchy (for
example,
|
Spring's integration testing support has the following goals:
Spring IoC container caching between test execution.
Transaction management appropriate to integration testing.
Spring-specific support classes that are useful in writing integration tests.
The next few sections describe each goal and provide links to implementation and configuration details.
The Spring TestContext Framework provides consistent loading of
Spring ApplicationContext
s and caching of those
contexts. Support for the caching of loaded contexts is important,
because startup time can become an issue - not because of the overhead
of Spring itself, but because the objects instantiated by the Spring
container take time to instantiate. For example, a project with 50 to
100 Hibernate mapping files might take 10 to 20 seconds to load the
mapping files, and incurring that cost before running every test in
every test fixture leads to slower overall test runs that could reduce
productivity.
Test classes provide an array containing the resource locations
of XML configuration metadata - typically in the classpath - that is
used to configure the application. These locations are the same as or
similar to the list of configuration locations specified in
web.xml
or other deployment configuration
files.
By default, once loaded, the configured
ApplicationContext
is reused for each
test. Thus the setup cost is incurred only once (per test fixture),
and subsequent test execution is much faster. In the unlikely case
that a test corrupts the application context and requires reloading --
for example, by changing a bean definition or the state of an
application object-- a Spring testing support mechanism causes the
test fixture to reload the configurations and rebuilds the application
context before executing the next test.
See context management and caching with the TestContext Framework.
When the TestContext framework loads your application context,
it can optionally configure instances of your test classes via
Dependency Injection. This provides a convenient mechanism for setting
up test fixtures using preconfigured beans from your application
context. A strong benefit here is that you can reuse application
contexts across various testing scenarios (e.g., for configuring
Spring-managed object graphs, transactional proxies,
DataSource
s, etc.), thus avoiding the need to
duplicate complex test fixture set up for individual test
cases.
As an example, consider the scenario where we have a class,
HibernateTitleDao
, that performs data access
logic for say, the Title
domain object. We want
to write integration tests that test all of the following
areas:
The Spring configuration: basically, is everything related
to the configuration of the
HibernateTitleDao
bean correct and
present?
The Hibernate mapping file configuration: is everything mapped correctly and are the correct lazy-loading settings in place?
The logic of the HibernateTitleDao
:
does the configured instance of this class perform as
anticipated?
See: dependency injection of test fixtures with the TestContext Framework.
One common issue in tests that access a real database is their affect on the state of the persistence store. Even when you're using a development database, changes to the state may affect future tests. Also, many operations - such as inserting or modifying persistent data - cannot be performed (or verified) outside a transaction.
The TestContext framework addresses this issue. By default, the
framework will create and roll back a transaction for each test. You
simply write code that can assume the existence of a transaction. If
you call transactionally proxied objects in your tests, they will
behave correctly, according to their transactional semantics. In
addition, if test methods delete the contents of selected tables while
running within a transaction, the transaction will roll back by
default, and the database will return to its state prior to execution
of the test. Transactional support is provided to your test class via
a PlatformTransactionManager
bean defined in
the test's application context.
If you want a transaction to commit - unusual, but occasionally
useful when you want a particular test to populate or modify the
database - the TestContext framework can be instructed to cause the
transaction to commit instead of roll back via the @TransactionConfiguration
and @Rollback
annotations.
See transaction management with the TestContext Framework.
The Spring TestContext Framework provides several
abstract
support classes that simplify the writing
of integration tests. These base test classes provide well-defined
hooks into the testing framework as well as convenient instance
variables and methods, which enable you to access:
The ApplicationContext
, for performing
explicit bean lookups or testing the state of the context as a
whole.
A SimpleJdbcTemplate
, for querying to
confirm state. For example, you use an ORM tool to query before
and after testing application code that creates an object and
persists it,
to verify that the data appears in the database. (Spring ensures
that the query runs in the scope of the same transaction.) You
need to tell your ORM tool to 'flush' its changes, by using, for
example, the flush()
method on
Hibernate's Session
interface.
In addition, you may want to create your own custom, application-wide superclass with instance variables and methods specific to your project.
See support classes for the TestContext Framework.
The org.springframework.test.jdbc
package
contains SimpleJdbcTestUtils
, which is a
Java-5-based collection of JDBC related utility functions intended to
simplify standard database testing scenarios. Note that AbstractTransactionalJUnit38SpringContextTests
,
AbstractTransactionalJUnit4SpringContextTests
,
and AbstractTransactionalTestNGSpringContextTests
provide convenience methods which delegate to
SimpleJdbcTestUtils
internally.
The Spring Framework provides the following set of Spring-specific annotations that you can use in your unit and integration tests in conjunction with the TestContext framework. Refer to the respective JavaDoc for further information, including default attribute values, attribute aliases, and so on.
@ContextConfiguration
Defines class-level metadata that is used to determine how to
load and configure an
ApplicationContext
. Specifically,
@ContextConfiguration
defines the
application context resource locations
to load as
well as the ContextLoader
strategy to
use for loading the context.
@ContextConfiguration(locations={"example/test-context.xml"}, loader=CustomContextLoader.class) public class CustomConfiguredApplicationContextTests { // class body... }
| Note | |
|---|---|
|
@DirtiesContext
Indicates that the underlying Spring
ApplicationContext
has been
dirtied (modified)as
follows during the execution of a test and should be closed,
regardless of whether the test passed:
After the current test class, when declared on a class
with class mode set to AFTER_CLASS
, which is
the default class mode.
After each test method in the current test class, when
declared on a class with class mode set to
AFTER_EACH_TEST_METHOD.
After the current test, when declared on a method.
Use this annotation if a test has modified the context (for example, by replacing a bean definition). Subsequent tests are supplied a new context.
| Limitations of @DirtiesContext with JUnit 3.8 | |
|---|---|
In a JUnit 3.8 environment
|
You can use @DirtiesContext
as
a class-level and method-level annotation within the same class.
In
such scenarios, the
ApplicationContext
is marked as
dirty after any such annotated method as well
as after the entire class. If the ClassMode
is set to AFTER_EACH_TEST_METHOD
, the context is
marked dirty after each test method in the class.
@DirtiesContext public class ContextDirtyingTests { // some tests that result in the Spring container being dirtied }
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) public class ContextDirtyingTests { // some tests that result in the Spring container being dirtied }
@DirtiesContext @Test public void testProcessWhichDirtiesAppCtx() { // some logic that results in the Spring container being dirtied }
When an application context is marked dirty, it is removed from the testing framework's cache and closed; thus the underlying Spring container is rebuilt for any subsequent test that requires a context with the same set of resource locations.
@TestExecutionListeners
Defines class-level metadata for configuring which
TestExecutionListener
s should be
registered with a TestContextManager
.
Typically, @TestExecutionListeners
are used in conjunction with
@ContextConfiguration
.
@ContextConfiguration @TestExecutionListeners({CustomTestExecutionListener.class, AnotherTestExecutionListener.class}) public class CustomTestExecutionListenerTests { // class body... }
@TestExecutionListeners
supports inherited listeners by default. See
the JavaDoc for an example and further details.
@TransactionConfiguration
Defines class-level metadata for configuring transactional
tests. Specifically, the bean name of the
PlatformTransactionManager
that is to
be used to drive transactions can be explicitly configured if the
bean name of the desired PlatformTransactionManager is not
"transactionManager". In addition, you can change the
defaultRollback
flag to false
.
Typically, @TransactionConfiguration
is used in conjunction with
@ContextConfiguration
.
@ContextConfiguration @TransactionConfiguration(transactionManager="txMgr", defaultRollback=false) public class CustomConfiguredTransactionalTests { // class body... }
@Rollback
Indicates whether the transaction for the annotated test
method should be rolled back after the test
method has completed. If true
, the transaction is
rolled back; otherwise, the transaction is committed. Use
@Rollback
to override the default
rollback flag configured at the class level.
@Rollback(false) @Test public void testProcessWithoutRollback() { // ... }
@BeforeTransaction
Indicates that the annotated public void
method should be executed before a transaction
is started for test methods configured to run within a transaction
through the @Transactional
annotation.
@BeforeTransaction public void beforeTransaction() { // logic to be executed before a transaction is started }
@AfterTransaction
Indicates that the annotated public void
method should be executed after a transaction
has ended for test methods configured to run within a transaction
through the @Transactional
annotation.
@AfterTransaction public void afterTransaction() { // logic to be executed after a transaction has ended }
@NotTransactional
The presence of this annotation indicates that the annotated test method must not execute in a transactional context.
@NotTransactional @Test public void testProcessWithoutTransaction() { // ... }
| @NotTransactional is deprecated | |
|---|---|
As of Spring 3.0,
|
The following annotations are only supported when used in conjunction with JUnit (that is., with the SpringJUnit4ClassRunner or the JUnit 3.8.2 and JUnit 4.5+ support classes.
@IfProfileValue
Indicates that the annotated test is enabled for a specific
testing environment. If the configured
ProfileValueSource
returns a matching
value
for the provided name
,
the test is enabled. This annotation can be applied to an entire
class or to individual methods. Class-level usage overrides
method-level usage.
@IfProfileValue(name="java.vendor", value="Sun Microsystems Inc.") @Test public void testProcessWhichRunsOnlyOnSunJvm() { // some logic that should run only on Java VMs from Sun Microsystems }
Alternatively, you can configure
@IfProfileValue
with a list of
values
(with OR semantics)
to achieve TestNG-like support for test groups
in a JUnit environment. Consider the following example:
@IfProfileValue(name="test-groups", values={"unit-tests", "integration-tests"}) @Test public void testProcessWhichRunsForUnitOrIntegrationTestGroups() { // some logic that should run only for unit and integration test groups }
@ProfileValueSourceConfiguration
Class-level annotation that specifies what type of
ProfileValueSource
to use when retrieving
profile values configured through the
@IfProfileValue
annotation. If
@ProfileValueSourceConfiguration
is
not declared for a test,
SystemProfileValueSource
is used by
default.
@ProfileValueSourceConfiguration(CustomProfileValueSource.class) public class CustomProfileValueSourceTests { // class body... }
@ExpectedException
Indicates that the annotated test method is expected to throw an exception during execution. The type of the expected exception is provided in the annotation, and if an instance of the exception is thrown during the test method execution then the test passes. Likewise if an instance of the exception is not thrown during the test method execution then the test fails.
@ExpectedException(SomeBusinessException.class) public void testProcessRainyDayScenario() { // some logic that should result in an Exception being thrown }
Using Spring's
@ExpectedException
annotation in
conjunction with JUnit 4's
@Test(expected=...)
configuration
would lead to an unresolvable conflict. Developers must therefore
choose one or the other when integrating with JUnit 4, in which case
it is generally preferable to use the explicit JUnit 4
configuration.
@Timed
Indicates that the annotated test method must finish execution in a specified time period (in milliseconds). If the text execution time exceeds the specified time period, the test fails.
The time period includes execution of the test method itself,
any repetitions of the test (see
@Repeat
), as well as any
set up or tear down of the
test fixture.
@Timed(millis=1000) public void testProcessWithOneSecondTimeout() { // some logic that should not take longer than 1 second to execute }
Spring's @Timed
annotation has
different semantics than JUnit 4's
@Test(timeout=...)
support.
Specifically, due to the manner in which JUnit 4 handles test
execution timeouts (that is, by executing the test method in a
separate Thread
),
@Test(timeout=...)
applies to
each iteration in the case of repetitions and
preemptively fails the test if the test takes too long. Spring's
@Timed
, on the other hand, times the
total test execution time (including all
repetitions) and does not preemptively fail the test but rather
waits for the test to complete before failing.
@Repeat
Indicates that the annotated test method must be executed repeatedly. The number of times that the test method is to be executed is specified in the annotation.
The scope of execution to be repeated includes execution of the test method itself as well as any set up or tear down of the test fixture.
@Repeat(10) @Test public void testProcessRepeatedly() { // ... }
The following non-test-specific annotations are supported with standard semantics for all configurations of the Spring TestContext Framework.
@Autowired
@Qualifier
@Resource
(javax.annotation) if JSR-250 is present
@Inject
(javax.inject) if JSR-330 is present
@Named
(javax.inject) if JSR-330 is present
@Provider
(javax.inject) if JSR-330 is present
@PersistenceContext
(javax.persistence) if JPA is present
@PersistenceUnit
(javax.persistence) if JPA is present
@Required
@Transactional
The Spring TestContext
Framework (located in the
org.springframework.test.context
package) provides
generic, annotation-driven unit and integration testing support that is
agnostic of the testing framework in use, whether JUnit 3.8.2, JUnit
4.5+, TestNG 5.10, and so on. The TestContext framework also places a
great deal of importance on convention over
configuration with reasonable defaults that can be overridden
through annotation-based configuration.
In addition to generic testing infrastructure, the TestContext
framework provides explicit support for JUnit 3.8.2, JUnit 4.5+, and
TestNG 5.10 in the form of abstract
support classes.
For JUnit 4.5+, the framework also provides a custom
Runner
that allows one to write test
classes that are not required to extend a particular class
hierarchy.
The following section provides an overview of the internals of the TestContext framework. If you are only interested in using the framework and not necessarily interested in extending it with your own custom listeners, feel free to go directly to the configuration (context management, dependency injection, transaction management), support classes, and annotation support sections.
The core of the framework consists of the
TestContext
and
TestContextManager
classes and the
TestExecutionListener
interface. A
TestContextManager
is created on a per-test
basis. The TestContextManager
in turn manages a
TestContext
that holds the context of the
current test. The TestContextManager
also
updates the state of the TestContext
as the
test progresses and delegates to
TestExecutionListener
s, which
instrument the actual test execution, by providing dependency
injection, managing transactions, and so on. Consult the JavaDoc and
the Spring test suite for further information and examples of various
configurations.
TestContext
: Encapsulates the context
in which a test is executed, agnostic of the actual testing
framework in use.
TestContextManager
: The main entry
point into the Spring TestContext Framework,
which manages a single TestContext
and
signals events to all registered
TestExecutionListener
s at
well-defined test execution points: test instance preparation,
prior to any before methods of a particular
testing framework, and after any after
methods of a particular testing framework.
TestExecutionListener
:
Defines a listener API for reacting to test
execution events published by the
TestContextManager
with which the listener
is registered.
Spring provides three
TestExecutionListener
implementations that are configured by default:
DependencyInjectionTestExecutionListener
,
DirtiesContextTestExecutionListener
, and
TransactionalTestExecutionListener
.
Respectively, they support dependency injection of the test
instance, handling of the
@DirtiesContext
annotation, and
transactional test execution with default rollback
semantics.
The following three sections explain how to configure the
TestContext
framework through annotations and
provide working examples of how to write unit and integration tests
with the framework.
Each TestContext
provides context
management and caching support for the test instance for which it is
responsible. Test instances do not automatically receive access to the
configured ApplicationContext
. However, if a
test class implements the
ApplicationContextAware
interface, a
reference to the ApplicationContext
is supplied
to the test instance, if the
DependencyInjectionTestExecutionListener
is
configured, which is the default.
AbstractJUnit38SpringContextTests
,
AbstractJUnit4SpringContextTests
, and
AbstractTestNGSpringContextTests
already
implement ApplicationContextAware
and
therefore provide this functionality out-of-the-box.
| @Autowired ApplicationContext | |
|---|---|
As an alternative to implementing the
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class MyTest { @Autowired private ApplicationContext applicationContext; // class body... } |
In contrast to the now deprecated JUnit 3.8 legacy class
hierarchy, test classes that use the TestContext framework do not need
to override any protected
instance methods to
configure their application context. Rather, configuration is achieved
merely by declaring the
@ContextConfiguration
annotation at the
class level. If your test class does not explicitly declare
application context resource locations
, the
configured ContextLoader
determines how
and whether to load a context from a default set of locations. For
example, GenericXmlContextLoader
, which is the
default ContextLoader
, generates a
default location based on the name of the test class. If your class is
named com.example.MyTest
,
GenericXmlContextLoader
loads your application
context from
"classpath:/com/example/MyTest-context.xml"
.
package com.example; @RunWith(SpringJUnit4ClassRunner.class) // ApplicationContext will be loaded from "classpath:/com/example/MyTest-context.xml" @ContextConfiguration public class MyTest { // class body... }
If the default location does not suit your needs, you can
configure explicitly the locations
attribute of
@ContextConfiguration
with an array
that contains the resource locations of XML configuration metadata
(assuming an XML-capable ContextLoader
has been configured) - typically in the classpath
- used to configure the application. (See the following code example.)
This location will be the same, or nearly the same, as the list of
configuration locations specified in web.xml
or
other deployment configuration. Alternatively, you can implement and
configure your own custom
ContextLoader
.
@RunWith(SpringJUnit4ClassRunner.class) // ApplicationContext will be loaded from "/applicationContext.xml" and "/applicationContext-test.xml" // in the root of the classpath @ContextConfiguration({"/applicationContext.xml", "/applicationContext-test.xml"}) public class MyTest { // class body... }
@ContextConfiguration
supports an
alias for the locations
attribute through the
standard value
attribute. Thus, if you do not need
to configure a custom ContextLoader
,
you can omit the declaration of the locations
attribute name and declare the resource locations by using the
shorthand format demonstrated in the following example.
@ContextConfiguration
also supports a
boolean inheritLocations
attribute that denotes
whether resource locations from superclasses should be
inherited. The default value is
true
, which means that an annotated class inherits
the resource locations defined by an annotated superclass.
Specifically, the resource locations for an annotated class are
appended to the list of resource locations defined by an annotated
superclass. Thus, subclasses have the option of
extending the list of resource locations. In the
following example, the
ApplicationContext
for
ExtendedTest
is loaded from "/base-context.xml"
and "/extended-context.xml", in that
order. Beans defined in "/extended-context.xml" may therefore override
those defined in "/base-context.xml".
@RunWith(SpringJUnit4ClassRunner.class) // ApplicationContext will be loaded from "/base-context.xml" in the root of the classpath @ContextConfiguration("/base-context.xml") public class BaseTest { // class body... } // ApplicationContext will be loaded from "/base-context.xml" and "/extended-context.xml" // in the root of the classpath @ContextConfiguration("/extended-context.xml") public class ExtendedTest extends BaseTest { // class body... }
If inheritLocations
is set to
false
, the resource locations for the annotated
class shadows and effectively replaces any resource locations defined
by a superclass.
By default, once loaded, the configured
ApplicationContext
is reused for each
test. Thus the setup cost is incurred only once (per test fixture),
and subsequent test execution is much faster. In the unlikely case
that a test dirties (modifies)
the application context, requiring reloading -- for example, by
changing a bean definition or the state of an application object --
you can annotate your test method with
@DirtiesContext
(assuming
DirtiesContextTestExecutionListener
has been
configured, which is the default) to cause the test fixture to reload
the configurations and rebuild the application context before
executing the next test.
When you configure the
DependencyInjectionTestExecutionListener
--
which is configured by default through the
@TestExecutionListeners
annotation--
the dependencies of your test instances are
injected from beans in the application context
you configured through
@ContextConfiguration
by setter
injection, field injection, or both, depending on which annotations
you choose and whether you place them on setter methods or fields. For
consistency with the annotation support introduced in Spring 2.5, you
can use Spring's @Autowired
annotation
or the @Resource
annotation from JSR
250. The semantics for both are consistent throughout the Spring
Framework. For example, if you prefer autowiring by
type, annotate your setter methods or fields with
@Autowired
. If you prefer to have your
dependencies injected by name, annotate your
setter methods or fields with
@Resource
.
| Tip | |
|---|---|
The TestContext framework does not instrument the manner in
which a test instance is instantiated. Thus the use of
|
Because @Autowired
performs autowiring by
type, if you have multiple bean definitions of the
same type, you cannot rely on this approach for those particular
beans. In that case, you can use
@Resource
for injection by
name. Alternatively, if your test class has access to its
ApplicationContext
, you can perform an explicit
lookup by using (for example) a call to
applicationContext.getBean("titleDao")
. A
third option is to use @Autowired
in
conjunction with @Qualifier
.
If you do not want dependency injection applied to your test
instances, simply do not annotate fields or setter methods with
@Autowired
or
@Resource
. Alternatively, you can
disable dependency injection altogether by explicitly configuring your
class with @TestExecutionListeners
and
omitting
DependencyInjectionTestExecutionListener.class
from
the list of listeners.
Consider the scenario of a class,
HibernateTitleDao
, as outlined in the Goals section. (We will look at
the application context configuration after all sample code listings.)
A JUnit 4-based implementation of the test class itself uses
@Autowired
for field injection.
| Note | |
|---|---|
The dependency injection behavior in the following code listings is not in any way specific to JUnit 4. The same DI techniques can be used in conjunction with any testing framework. The following examples make calls to static assertion methods
such as |
@RunWith(SpringJUnit4ClassRunner.class) // specifies the Spring configuration to load for this test fixture @ContextConfiguration("daos.xml") public final class HibernateTitleDaoTests { // this instance will be dependency injected by type @Autowired private HibernateTitleDao titleDao; public void testLoadTitle() throws Exception { Title title = this.titleDao.loadTitle(new Long(10)); assertNotNull(title); } }
Alternatively, you can configure the class to use
@Autowired
for setter injection.
@RunWith(SpringJUnit4ClassRunner.class) // specifies the Spring configuration to load for this test fixture @ContextConfiguration("daos.xml") public final class HibernateTitleDaoTests { // this instance will be dependency injected by type private HibernateTitleDao titleDao; @Autowired public void setTitleDao(HibernateTitleDao titleDao) { this.titleDao = titleDao; } public void testLoadTitle() throws Exception { Title title = this.titleDao.loadTitle(new Long(10)); assertNotNull(title); } }
Here is an example of @Resource
for field injection.
@RunWith(SpringJUnit4ClassRunner.class) // specifies the Spring configuration to load for this test fixture @ContextConfiguration("daos.xml") public final class HibernateTitleDaoTests { // this instance will be dependency injected by name @Resource private HibernateTitleDao titleDao; public void testLoadTitle() throws Exception { Title title = this.titleDao.loadTitle(new Long(10)); assertNotNull(title); } }
Here is an example of @Resource
for setter injection.
@RunWith(SpringJUnit4ClassRunner.class) // specifies the Spring configuration to load for this test fixture @ContextConfiguration("daos.xml") public final class HibernateTitleDaoTests { // this instance will be dependency injected by name private HibernateTitleDao titleDao; @Resource public void setTitleDao(HibernateTitleDao titleDao) { this.titleDao = titleDao; } public void testLoadTitle() throws Exception { Title title = this.titleDao.loadTitle(new Long(10)); assertNotNull(title); } }
The preceding code listings use the same XML context file
referenced by the @ContextConfiguration
annotation (that is, daos.xml
), which looks like
this:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- this bean will be injected into the HibernateTitleDaoTests class --> <bean id="titleDao" class="com.foo.dao.hibernate.HibernateTitleDao"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- dependencies elided for clarity --> </bean> </beans>
| Note | |
|---|---|
If you are extending from a Spring-provided test base class
that happens to use // ... @Autowired @Override public void setDataSource(@Qualifier("myDataSource") DataSource dataSource) { super.setDataSource(dataSource); } // ... The specified qualifier value indicates the specific
Alternatively, consider using the
// ... @Resource("myDataSource") @Override public void setDataSource(DataSource dataSource) { super.setDataSource(dataSource); } // ... |
In the TestContext framework, transactions are managed by the
TransactionalTestExecutionListener
, which is
configured through the
@TestExecutionListeners
annotation by
default, even if you do not explicitly declare
@TestExecutionListeners
on your test
class. To enable support for transactions, however, you must provide a
PlatformTransactionManager
bean in the
application context loaded by
@ContextConfiguration
semantics. In
addition, you must declare
@Transactional
either at the class or
method level.
For class-level transaction configuration (that is, setting the
bean name for the transaction manager and the default rollback flag),
see the @TransactionConfiguration
entry
in the annotation
support section.
If transactions are not enabled for the entire test class, you
can annotate methods explicitly with
@Transactional
. To control whether a
transaction should commit for a particular test method, you can use
the @Rollback
annotation to override
the class-level default rollback setting.
AbstractTransactionalJUnit38SpringContextTests
,
AbstractTransactionalJUnit4SpringContextTests
,
and AbstractTransactionalTestNGSpringContextTests
are preconfigured for transactional support at the class level.
Occasionally you need to execute certain code before or after a
transactional test method but outside the transactional context, for
example, to verify the initial database state prior to execution of
your test or to verify expected transactional commit behavior after
test execution (for example, if the test was configured not to roll
back the transaction).
TransactionalTestExecutionListener
supports the
@BeforeTransaction
and
@AfterTransaction
annotations exactly
for such scenarios. Simply annotate any public void
method in your test class with one of these annotations, and the
TransactionalTestExecutionListener
ensures that
your before transaction method or after
transaction method is executed at the appropriate
time.
| Tip | |
|---|---|
Any before methods (for example, methods
annotated with JUnit 4's @Before) and any after
methods (such as methods annotated with JUnit 4's @After)
are executed within a transaction.
In addition, methods annotated with
|
The following JUnit 4 based example displays a fictitious integration testing scenario highlighting several transaction-related annotations. Consult the annotation support section of the reference manual for further information and configuration examples.
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @TransactionConfiguration(transactionManager="txMgr", defaultRollback=false) @Transactional public class FictitiousTransactionalTest { @BeforeTransaction public void verifyInitialDatabaseState() { // logic to verify the initial state before a transaction is started } @Before public void setUpTestDataWithinTransaction() { // set up test data within the transaction } @Test // overrides the class-level defaultRollback setting @Rollback(true) public void modifyDatabaseWithinTransaction() { // logic which uses the test data and modifies database state } @After public void tearDownWithinTransaction() { // execute "tear down" logic within the transaction } @AfterTransaction public void verifyFinalDatabaseState() { // logic to verify the final state after transaction has rolled back } }
| Avoid false positives when testing ORM code | |
|---|---|
When you test code involving an ORM framework such as JPA or Hibernate, flush the underlying session within test methods which update the state of the session. Failing to flush the ORM framework's underlying session can produce false positives: your test may pass, but the same code throws an exception in a live, production environment. In the following Hibernate-based example test case, one method demonstrates a false positive and the other method correctly exposes the results of flushing the session. // ... @Autowired private SessionFactory sessionFactory; @Test // no expected exception! public void falsePositive() { updateEntityInHibernateSession(); // False positive: an exception will be thrown once the session is // finally flushed (i.e., in production code) } @Test(expected = GenericJDBCException.class) public void updateWithSessionFlush() { updateEntityInHibernateSession(); // Manual flush is required to avoid false positive in test sessionFactory.getCurrentSession().flush(); } // ... |
The
org.springframework.test.context.junit38
package
provides support classes for JUnit 3.8 based test cases.
AbstractJUnit38SpringContextTests
:
Abstract TestCase
that integrates the
Spring TestContext Framework with explicit
ApplicationContext
testing support in a
JUnit 3.8 environment. When you extend the
AbstractJUnit38SpringContextTests
class,
you need access to the following protected
instance variables:
applicationContext
: Perform
explicit bean lookups or test the state of the context as a
whole.
AbstractTransactionalJUnit38SpringContextTests
:
Abstract transactional extension of
AbstractJUnit38SpringContextTests
that
also adds some convenience functionality for JDBC access.
Expects a javax.sql.DataSource
bean and a
PlatformTransactionManager
bean
to be defined in the ApplicationContext
.
When you extend the
AbstractTransactionalJUnit38SpringContextTests
class, you will have access to the following
protected
instance variables:
applicationContext
: Inherited from
the AbstractJUnit38SpringContextTests
superclass. Use this variable to perform explicit bean
lookups or to test the state of the context as a
whole.
simpleJdbcTemplate
: Useful for
querying to confirm state. For example, use an ORM tool to
query before and after testing application code that creates
an object and persists it, to
verify that the data appears in the database. (Spring
ensures that the query runs in the scope of the same
transaction.) You need to tell your ORM tool to 'flush' its
changes for this to work correctly by, for example, using
the flush()
method on Hibernate's
Session
interface.
The org.springframework.test.context.junit4
package provides support classes for JUnit 4.5+ based test
cases.
AbstractJUnit4SpringContextTests
:
Abstract base test class that integrates the Spring
TestContext Framework with explicit
ApplicationContext
testing support in a
JUnit 4.5+ environment.
When you extend
AbstractJUnit4SpringContextTests
, you can
access the following protected
instance
variable:
applicationContext
: Perform
explicit bean lookups or test the state of the context as a
whole.
AbstractTransactionalJUnit4SpringContextTests
:
Abstract transactional extension of
AbstractJUnit4SpringContextTests
that
also adds some convenience functionality for JDBC access.
Expects a javax.sql.DataSource
bean and a
PlatformTransactionManager
bean
to be defined in the ApplicationContext
.
When you extend
AbstractTransactionalJUnit4SpringContextTests
you can access the following protected
instance variables:
applicationContext
: Inherited from
the AbstractJUnit4SpringContextTests
superclass. Perform explicit bean lookups or test the state
of the context as a whole.
simpleJdbcTemplate
: Useful for
querying to confirm state. For example, use an ORM tool to
query before and after testing application code that creates
an object and persists it, to verify that the data appears
in the database. (Spring
ensures that the query runs in the scope of the same
transaction.) You need to tell your ORM tool to 'flush' its
changes for this to work correctly by, for example, using
the flush()
method on Hibernate's
Session
interface.
| Tip | |
|---|---|
These classes are a convenience for extension. If you do not
want your test classes to be tied to a Spring-specific class
hierarchy -- for example, if you want to extend directly the class
you are testing -- you can configure your own custom test classes
by using
|
The Spring TestContext Framework offers
full integration with JUnit 4.5+ through a custom runner (tested on
JUnit 4.5, 4.6, and 4.7). By annotating test classes with
@RunWith(SpringJUnit4ClassRunner.class)
,
developers can implement standard JUnit 4.5+ unit and integration
tests and simultaneously reap the benefits of the TestContext
framework such as support for loading application contexts,
dependency injection of test instances, transactional test method
execution, and so on. The following code listing displays the minimal
requirements for configuring a test class to run with the custom Spring
Runner. @TestExecutionListeners
is
configured with an empty list in order to disable the default listeners,
which otherwise would require an ApplicationContext to be configured
through @ContextConfiguration
.
@RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners({}) public class SimpleTest { @Test public void testMethod() { // execute test logic... } }
The org.springframework.test.context.testng
package provides support classes for TestNG based test cases.
AbstractTestNGSpringContextTests
:
Abstract base test class that integrates the Spring
TestContext Framework with explicit
ApplicationContext
testing support in a
TestNG environment.
When you extend
AbstractTestNGSpringContextTests
you can
access the following protected
instance
variable:
applicationContext
: Perform
explicit bean lookups or test the state of the context as a
whole.
AbstractTransactionalTestNGSpringContextTests
:
Abstract transactional extension of
AbstractTestNGSpringContextTests
that
adds some convenience functionality for JDBC access. Expects a
javax.sql.DataSource
bean and a
PlatformTransactionManager
bean
to be defined in the ApplicationContext
.
When you extend
AbstractTransactionalTestNGSpringContextTests,
you can access the following protected
instance variables:
applicationContext
: Inherited from
the AbstractTestNGSpringContextTests
superclass. Perform explicit bean lookups or test the state
of the context as a whole.
simpleJdbcTemplate
: Useful for
querying to confirm state. For example, use an ORM tool to
query before and after testing application code that creates
an object and persists it, to verify that the data appears
in the database. (Spring ensures that the query runs in the
scope of the same transaction.) You need to tell your ORM
tool to 'flush' its changes for this to work correctly by,
for example, using the flush()
method on Hibernate's Session
interface.
| Tip | |
|---|---|
These classes are a convenience for extension. If you do not
want your test classes to be tied to a Spring-specific class
hierarchy--for example, if you want to directly extend the class
you are testing--you can configure your own custom test classes by
using |
The PetClinic application, available from the samples repository,
illustrates several features of the Spring
TestContext Framework in a JUnit 4.5+ environment. Most test
functionality is included in the
AbstractClinicTests
, for which a partial listing
is shown below:
import static org.junit.Assert.assertEquals; // import ... @ContextConfiguration public abstract class AbstractClinicTests extends AbstractTransactionalJUnit4SpringContextTests { @Autowired protected Clinic clinic; @Test public void getVets() { Collection<Vet> vets = this.clinic.getVets(); assertEquals("JDBC query must show the same number of vets", super.countRowsInTable("VETS"), vets.size()); Vet v1 = EntityUtils.getById(vets, Vet.class, 2); assertEquals("Leary", v1.getLastName()); assertEquals(1, v1.getNrOfSpecialties()); assertEquals("radiology", (v1.getSpecialties().get(0)).getName()); // ... } // ... }
Notes:
This test case extends the
AbstractTransactionalJUnit4SpringContextTests
class, from which it inherits configuration for Dependency Injection
(through the
DependencyInjectionTestExecutionListener
) and
transactional behavior (through the
TransactionalTestExecutionListener
).
The clinic
instance variable - the
application object being tested - is set by Dependency Injection
through @Autowired
semantics.
The testGetVets()
method illustrates
how you can use the inherited
countRowsInTable()
method to easily verify
the number of rows in a given table, thus testing correct behavior
of the application code being tested. This allows for stronger tests
and lessens dependency on the exact test data. For example, you can
add additional rows in the database without breaking tests.
Like many integration tests that use a database, most of the
tests in AbstractClinicTests
depend on a
minimum amount of data already in the database before the test cases
run. You might, however, choose to populate the database in your
test cases also - again, within the same transaction.
The PetClinic application supports three data access technologies:
JDBC, Hibernate, and JPA. By declaring
@ContextConfiguration
without any
specific resource locations, the
AbstractClinicTests
class will have its
application context loaded from the default location,
AbstractClinicTests-context.xml
, which declares a
common DataSource
. Subclasses specify additional
context locations that must declare a
PlatformTransactionManager
and a concrete
implementation of Clinic
.
For example, the Hibernate implementation of the PetClinic tests
contains the following implementation. For this example,
HibernateClinicTests
does not contain a single
line of code: we only need to declare
@ContextConfiguration
, and the tests are
inherited from AbstractClinicTests
. Because
@ContextConfiguration
is declared without
any specific resource locations, the Spring TestContext
Framework loads an application context from all the beans
defined in AbstractClinicTests-context.xml
(that is,
the inherited locations) and
HibernateClinicTests-context.xml
, with
HibernateClinicTests-context.xml
possibly overriding
beans defined in
AbstractClinicTests-context.xml
.
@ContextConfiguration public class HibernateClinicTests extends AbstractClinicTests { }
As you can see in the PetClinic application, the Spring
configuration is split across multiple files. As
is typical of large-scale applications, configuration locations are
often specified in a common base class for all application-specific
integration tests. Such a base class may also add useful instance
variables--populated by Dependency Injection, naturally--such as a
HibernateTemplate
, in the case of an application
using Hibernate.
As far as possible, you should have exactly the same Spring
configuration files in your integration tests as in the deployed
environment. One likely point of difference concerns database connection
pooling and transaction infrastructure. If you are deploying to a
full-blown application server, you will probably use its connection pool
(available through JNDI) and JTA implementation. Thus in production you
will use a JndiObjectFactoryBean
/
<jee:jndi-lookup>
for the
DataSource
and
JtaTransactionManager
. JNDI and JTA will not be
available in out-of-container integration tests, so you should use a
combination like the Commons DBCP BasicDataSource
and DataSourceTransactionManager
or
HibernateTransactionManager
for them. You can
factor out this variant behavior into a single XML file, having the
choice between application server and a 'local' configuration separated
from all other configuration, which will not vary between the test and
production environments. In addition, it is advisable to use properties
files for connection settings: see the PetClinic application for an
example.
Consult the following resources for more information about testing:
JUnit: The Spring Framework's unit and integration test suite, written with JUnit 3.8.2 and JUnit 4.7 as the testing framework.
TestNG: A testing framework inspired by JUnit 3.8 with added support for Java 5 annotations, test groups, data-driven testing, distributed testing, and so on.
MockObjects.com: Web site dedicated to mock objects, a technique for improving the design of code within test-driven development.
"Mock Objects": Article in Wikipedia.
EasyMock: Used extensively by the Spring Framework in its test suite.
JMock: Library that supports test-driven development of Java code with mock objects.
DbUnit: JUnit extension (also usable with Ant and Maven) targeted for database-driven projects that, among other things, puts your database into a known state between test runs.
Grinder: Java load testing framework.


Making Repositories
To put your project up on GitHub, you'll need to create a repository for it to live in. You can store a variety of projects in GitHub repositories, including open source projects. With open source projects, you can share code to make better, more reliable software. You can create public repositories for an open source project. When creating your public repository, make sure to include a license file that determines how you want your project to be shared with others. For more information on open source, specifically how to create and grow an open source project, we've created Open Source Guides that will help you foster a healthy open source community by recommending best practices for creating and maintaining repositories for your open source project. You can also take a free GitHub Learning Lab course on maintaining open source communities.
1) First what your going to want to do is open up GitHub and Log In
2) In the upper-right corner of any page, use the drop-down menu, and select New repository.
3) Type a short, memorable name for your repository. For example, "hello-world".
4) Optionally, add a description of your repository. For example, "My first repository on GitHub."
5) Choose a repository visbility. For more information, see "About repository visibility."
6) Select Initialize this repository with a README.
7) Click Create repository.
Congratulations! You've successfully created your first repository, and initialized it with a README file.


Hello Dev Bootcamp!
To keep in mind
lalala
lalala
Websites to visit
Barcelona
Amsterdam
Why I Meditate
lalala
Why I Travel
lalala
Home
Wireframe
Cultural 1
Technical 1
Cultural 2
Technical 2
Keep cool
Don't lose focus
Make it happen
Don't look back


Terraria Steam Key giveaway! - Better Battlelog Forums #125662
Sitemap
Post edited 1 x times, last by
BrainFooLong
Administrator
Topicstarter
BrainFooLong
Administrator
Hi,
i have a free Terraria steam key, for all interested people, make a post here.

I will really appreciate one key for playing with my friend! Thank you a lot!
seems nice game...you can send me?
I have Bioshoch 2 and Minerva´s Den on steam.
i would love to have one too :)
Always loved playing it at my friends house ^_^
Could I get the Terraria Key? I'd love to give it to my friend as a birthday present :D
Topicstarter
BrainFooLong
Administrator
Thanks for all posts. Key giveaway has ended.
Congrats to the winner "Happydeath".
I've randomly picked a name from the posts, so, good luck next time.


Drag this link to your bookmarks bar: SVJimmy
Click it to download any SVG as a PNG. Try it on this page!
SVJimmy is the raster cousin to SVG Crowbar.
View source on GitHub. Released under the BSD License. Copyright 2021 Mike Bostock.


Parameters - Song Structure Type
Seeds are a fun and quick way to generate songs but sometimes you want more control of the output.
In the "Parameters" and "Domains" tab in the "Song Settings" dialog, you can find a lot of ways to control the generated song!
Do you want to change the scale type or time signature of the song? No problem! Just change the "Minor Scale Likelihood" or "Major Scale Likelihood".
Change one of them to zero to guarantee the other one. Modify "4/4 Time Signature Likelihood" and so on to change the time signature.
Let's play with some parameters!
- Generate a new, fresh song
- Change the "Verse Chorus Bridge Likelihood Multiplier" (in the "Parameters" tab) to something really high (like 99999) and listen to the song.
- Change the "Strict Build Likelihood Multiplier" to something really high instead and set the one you changed before to zero. Listen to the song.
If everything went as expected, the songs should have different structures.
- Now try to set either "Minor Scale Likelihood" or "Major Scale Likelihood" to zero to change the scale of the song. Listen to the song!
The songs should have the same structure,
motifs and rythms but the scale is different.
There are a lot of parameters to try! Experiment and have fun :)


So among the reasons I’m no Facebook fan is my desire to control and own the words I publish and share on the internet. I’m a supporter of the IndieWeb, but, then again, I can build and host my own websites, so it’s easy to be.
Here’s a tool that makes owning your content a bit more accessible: [micro.blog][]. I backed the Kickstarter and am playing around with the service.


eat
shop
walk
Who are we?
IZZI
Hi, I'm a foodie and love to find peaceful places in the city!
DAISY
Hi, I love spending my weekends out and about wandering round London!
BARB
Hi, bottomless brunches and picnics in the park are my form of a perfect weekend!
Get in touch!
Have a submission to make? Please send in any suggestions for this site here.
What would you like to suggest?
Type of suggestion
Eat
Shop
Walk
Description of your suggestion
Submit


Bowfinger (1999) 3 1/2 stars out of 4. Starring Steve Martin, Eddie Murphy, Heather Graham and Christine Baranski. Written by Martin. Directed by Frank Oz.
We movie critics usually are an impassive lot. We sit at screening after screening, detached, perhaps jotting a note or two. In public, we hardly ever react to what is being shown - be it good or bad.
However, there are exceptions.
The latest is "Bowfinger," a hilarious comedy about the magic of movie making. Bowfinger could be the grandson - or distant cousin - to Tim Burton's "Ed Wood." Both overflow with an affectionate, loopy love of filmmaking. Both forego cynicism and condescension about the process.
"Bowfinger" also hits the Marx. While lacking the anarchy of an outing with Groucho, Chico and Harpo, Bowfinger - at 97 minutes - is reminiscent of the frenetic pace of the early Marx Bros. films such as "Horse Feathers" and "Duck Soup."
"Bowfinger" offers more laughs than any other film this year. It is express-train comedy, written by and starring Steve Martin.
Martin plays Bobby Bowfinger, a producer-director on the edge of the industry, whose shanty office is a ramshackle dump miles from the glitter and glamour of Hollywood.
Bowfinger is desperate to hit the big time and feels that "Chubby Rain," a science fiction action flick written by his accountant, Afrim, is his ticket. The only hitch is he doesn't have a big-name star.
No problem. Gathering his motley crew of filmmakers, he sets out to trick the biggest action star in the business, Kit Ramsey (Eddie Murphy), and, without his knowledge, make him the star of his ultra-low budget flick.
Bowfinger does this by having people spy on Ramsey and fashioning his scenes around the locales at which Ramsey is scheduled to appear.
It's hijinks hilarity as the already-paranoid Ramsey - he turned down a script because it contained about 1,400 K's, which, when divided by three, equals about 445 KKKs - is driven to higher heights of paranoia by these strange people, some of whom act like aliens, who continually accost him.
To fill in the long shots, Bowfinger hires Jiff, a not-too-bright, but earnest young man without much acting ability whose only attribute is a resemblance to Kit Ramsey. The reason for that resemblance is made clear later in the movie.
Martin's script hardly allows you time to catch your breath between laughs. Scenes continually top each other.
For instance, Bowfinger says he's going to get the best crew available, and the camera cuts to his van picking up a group of illegal aliens coming across the border. The joke is topped at the end of the movie when these men - who could not speak English nor who knew one end of a clapboard from another - all have cell phones and are talking industry lingo.
The strong supporting cast also is responsible for much of "Bowfinger's" jocularity.
Heather Graham is Daisy, a wannabe starlet who will do anything to get more screen time in Bowfinger's movie. She is smarter than she lets on, at one point telling one of her paramours, "I may be from Ohio, but I'm not from Ohio." She knows the score and who to score with to get her way.
The always-reliable Christine Baranski plays Carol, the over-the-hill diva, for all she's worth. She dominates most of her scenes with a comic abandon.
Murphy is the funniest he has been in years. Forget "Dr. Dolittle" and "The Nutty Professor." This is the Eddie Murphy of "Trading Places," of the first "48 HRS." As Kit, he's a profane, spoiled, motor-mouthed nutcase. As Jiff, he's vulnerable, sweet and shy. And Murphy draws a clear demarcation between the two.
Martin is in top form. Not since "All of Me" has he shined so brightly in a comedic role. His Bobby Bowfinger is a quick-thinking con artist whose only goal is to complete his dream movie. To do so, he will lie, cheat, connive, steal. If Groucho Marx were to play a down-and-out movie producer, he would be Bobby Bowfinger.
"Bowfinger" is a 97-minute laugh-a-thon. Your sides will hurt when the film fades out. It is a comedy event not to be missed.
Bob Bloom is the film critic at the Journal and Courier in Lafayette, IN. He can be reached by e-mail at<EMAIL_ADDRESS>or at<EMAIL_ADDRESS>The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


{% extends 'layout.server.view.html' %} {% block content %}
Template 'Something broke and it may or may not be our fault. Try back later. In the mean time, entertain yourself by watching the following pretty DDOS attacks against the US: #CyberWar' {{error}}{% endblock %}


{# Copyright (C) 2011 University of Southampton #} {% extends "base_nav.html" %} {% load url from future %} {%block title %}PROVServer: OAuth Help{% endblock %} {% block header %}
The Provenance Server's API provides a RESTfull web service for storage and access of provenance bundles in JSON format as specified here for the W3C's Provenance Data Model. Via the API, any client can manipulate bundles stored on a server and explore and retrieve information from other clients.
The PROV-JSON API supports OAuth protocol for authentication and authorization. The API supports the common web server application flow for using the protocol. In it's core the OAuth would be registering an application with the web service and when needed to access you redirect the browser to a given URL, parse the token from the response and use it to for accessing the resource. For a more detail information of the flow of the protocol and the security framework we suggest to read the official OAuth Guide. This guide will explain how to use the protocol for authentication and authorization of the PROV-JSON web service.
The first thing in order to register an App is to create an account, if you have not done so already. This will give you access to the PROV-JSON webUI where you can very easily manage and see all the resources and application linked to your account. When you are logged in you can go to the Apps panel and select Add New to open the registration form for an app. After the registration is complete in the Apps panel you are going to see all the application currently registered to your account together with the Client Key and Client Secret associated with them which you are going to need for accessing the API with OAuth.
The flow of obtaining Access Token is well defined by the OAuth specifications and we will demonstrate it here in practice with the PROV-JSON API. Let's assume that John is a developer which wants to use the OAuth protocol to access user resources and he has a web application. He registers his application on the webUI site, and the result of the registration would look like this:
Name : John's App Description : A friendly application for displaying resources. Consumer_Key : dpf43f3p2l4k3l03 Consumer_Secret : kd94hf93k423kf44
On his application John now have to create a function to obtain a Request Token from the PROV-JSON Server. This is done by either a GET or POST request to http://www.example.com/oauth/request_token with the following parameters included in the request:
oauth_consumer_key : dpf43f3p2l4k3l03 oauth_signature_method : PLAINTEXT oauth_signature : kd94hf93k423kf44, oauth_timestamp :<PHONE_NUMBER> oauth_nonce : kllo9940pd9333jh oauth_version : 1.0 oauth_callback : http://johns_domain/request_token_ready scope: api
These parameters can be included in different places in the request according to
the OAuth Specifications - "The parameters are collected from three locations:
the URL query element (as defined by RFC 3986 section 3), the OAuth 'Authorization'
header (excluding the 'realm' parameter), and parameters included in a single-part
'application/x-www-form-urlencoded' POST body (as defined by HTML4)."
Assuming Jane visits Johns App and decides that she wants to check out Johns
visualization of the provenance, when she clicks to connect to her account
obtaining the Request Token is the first thing to do. A corespoding response would
contain the following information:
oauth_token_secret : Qc7bPafBTku2yT7X oauth_token : 6e63d062712c4381a559eaf5887a64ef oauth_callback_confirmed : true
After obtaining the Request Token now John's App have to get Jane's permission to access her resources. This happens by calling with GET or POST request the authorization URL www.example.com/oauth/authorize/ with only the ouath_token as parameter.
oauth_token : 6e63d062712c4381a559eaf5887a64ef
The response returned from the server would be a redirect and the 'Location' header will contain the URL to which Johns App have to redirect Jane. When this happen Jane would be presented with the login to the webUI server and when she logged in she would be given a choice to grant access to her data to John's App. When she grants that access she will be redirected back to the oauth_callback URL (http://johns_domain/request_token_ready) with attached two extra arguments - oauth_token and oauth_verifier, and John's Reques Token will be approved.
http://johns_domain/request_token_ready?oauth_verifier=8449664522&oauth_token=916197bbb7224e3facd7133c0ead7f52
Now all that is left to do for John is to exchange the Request Token for an Access Token which is the Token used for the actual data. This can be done again by either GET or POST method to the URL www.example.com/oauth/access_token/ with the following parameters:
oauth_consumer_key : dpf43f3p2l4k3l03 oauth_token : 6e63d062712c4381a559eaf5887a64ef oauth_signature_method : PLAINTEXT oauth_signature : kd94hf93k423kf44&Qc7bPafBTku2yT7X oauth_timestamp :<PHONE_NUMBER> oauth_nonce : kllo9940pd9333jh oauth_version : 1.0 oauth_verifier :<PHONE_NUMBER> scope : apiThis will result in response from the server containing the Access Token given all the information provided was correct and flow of the protocol was followed. An example response body may look like this:
oauth_token_secret : UUy9xz2b2YafykRJ oauth_token : b7c21ff3256447078a2de2a9572be44a
Now when John's App have acuired the Access Token it can access Jane's provenance resources.
An example request to the API using such Access Token:
oauth_consumer_key : dpf43f3p2l4k3l03 oauth_token : b7c21ff3256447078a2de2a9572be44a oauth_signature_method : 'HMAC-SHA1', oauth_timestamp : now oauth_nonce : accessresourcenonce oauth_version : 1.0
The URL path of the request would be 'www.example.com/api/bundle/X/' asssuming Jane is the owner of bundle with ID 'X'. Don't forget that you have to add one more parameter ot the request - the oauth_signature which is a digest using the given signature_method of a special oauth Request object. Most languages have support of already build libraries for creating such object given the Access Token, the URL and the parameters above. After adding the oauth_signature to the parameter list John is ready to make a request to 'www.example.com/api/bundle/X/?format=json' (don't forget the format=json argument) and successfully retrieve Jane's resource.
{% endblock %} {% block sidebar %}


My name is Fayas. I am a 15 years old boy and I was born on 30th December in 2005. I am a 10th standard finished student. I'm living in Palakkad, Kerala, India. I know Malayalam, Tamil, and English languages. I am an Opensource Developer. You can check my brief bio here.
You can send messages via email or you can contact me via my accounts and please follow / subscribe / join my accounts.
I created more public projects like APIs, Python Packages, Opensource Repositories etc. You can checkout my projects here.
Your donation needed for me. Please donate any amount via my donation links.
Puliyaparambu Higher Secondary School - Finished 10th standard ( High School )


[gecode-users] compilation without cygwin
Christian Schulte
cschulte at kth.se
Thu Jul 25 20:35:06 CEST 2013
You need the Cygwin toolchain plus the MSVC cl compiler. It is as usual:
- Install Cygwin
- Install MSVC
- Set up the MSVC path in Cygwin so that cl can be run under Cygwin
- Unpack gecode
- Run configure
- Run make (which then will use cl)
- Done
Gecode's pre-compiled binaries for Windows are built with MSVC following the
above recipe.
Cheers
Christian
--
Christian Schulte, www.ict.kth.se/~cschulte/
From: users-bounces at gecode.org [mailto:users-bounces at gecode.org] On Behalf
Of kTorpi
Sent: Thursday, July 25, 2013 3:21 PM
To: Gustavo Gutierrez
Cc: users at gecode.org
Subject: Re: [gecode-users] compilation without cygwin
Hi,
Thank you, but I don't think so.
I'd like to compile the gecode itself. In Section 2.6.2 it is mentioned,
that "For Windows, we require Cygwin environment...", but I'd like to
compile gecode without it.
Thank you,
Steve
2013/7/24 Gustavo Gutierrez <gustavo.ggutierrez at gmail.com>
On Wed, Jul 24, 2013 at 8:37 AM, kTorpi <ktorpi at gmail.com> wrote:
Hi,
Is there someone who tried to compile gecode under windows without using
cygwin? I'd like to compile it with cl natively somehow. Is it possible?
Seems like section 2.3.1 of the following document is what you are looking
for.
http://www.gecode.org/doc-latest/MPG.pdf
Regards,
--
Gustavo Gutierrez
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.gecode.org/pipermail/users/attachments/20130725/59c7511f/attachment.html>
More information about the users
mailing list


For Cars Lovers
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable
If you like the content leave a coment


[§321-425] Requests for information. The department shall provide information about appropriate health and early intervention services to persons who request the information. [L 2002, c 252, pt of §1]


Football and car accidents
Apparently, football games prevent car accidents.
We looked at every accident from 2010-2014, and every Barcelona football game during the same period. It turns out that, on average, game days are about 11% safer than non-game days.
| Status | Days | Accidents | Daily Rate |
|---|---|---|---|
| No game | 1572 | 40376 | 25.68 |
| Game day | 254 | 5802 | 22.84 |
Maybe it's not really the football...
One could surmise that football matches keep people inside (glued to their television screens) rather than on the road (probably true), or that games take place more on the weekends than weekdays (when there are less accidents generally) . In other words, football itself isn't causing anything, and is simply acting as a proxy for traffic density.
Is this the case? We don't think so.
When we dig deeper, we find that the outcome of the match matters more than whether or not there is a game. When the home team wins, there are few crashes. But when Barça loses, there are even more crashes than on non-game days!
| Outcome | Days | Accidents | Daily rate |
|---|---|---|---|
| Loss | 26 | 711 | 27.35 |
| No game | 1572 | 40376 | 25.68 |
| Tie | 45 | 1078 | 23.96 |
| Win | 183 | 4013 | 21.93 |
Two theories
What's the reason for this? Two possible theories:
(1) People just get mad and drive worse when their team loses (possible, but unlikely).
(2) People leave venues in a more staggered fashion after a victory than after a defeat (since post-victory parties are more likely than post-defeat parties).
So, does football save lives?
That's probably a stretch. Yes, there are slightly fewer deaths on a winning vs. losing days, but this doesn't quite reach the level of "statistical significance."That said, the reduction in accidents associated with football victories is significant. So, if you're reading this, Messi - put down the computer, and get back to your training!
Data sources, code, etc.
OpenDataBCN hosts the dataset for traffic accidents managed by the Guardia Urbana.
Data on football matches, locations, and outcomes was manually gathered from multiple Wikipedia pages. The cleaned-up data is here.
As always, the code and data for this post (including source files, cleaning script, visualizations, etc.) can all be found on github.


A Sample Form
Email
Password
Address
Address 2
City
State
Choose...
Lagos
Ibadan
Zip
Check me out
Sign In


ImageCompare allows the user to compare two images visually. The input images are merged into a new image.
Input Ports
Name Type Description inImage1 Mesh_Unif+Node_Data An image inDatamap1 DatamapTempl A datamap inImage2 Mesh_Unif+Node_Data An image inDatamap2 DatamapTempl A datamap
Parameters
Name Type Description UI Control Border value float The value used to calculate the border position in the merged image Slider Merge mode int 0 is vertical slice
1 is horizontal slice
2 is diagonal
3 is solid
4 is circle
5 is checkerboardSlider Switch datasets boolean Swaps the images Toggle
Output Ports
Name Type Description out Mesh_Unif+Node_Data output surface. obj Link A directly renderable object for UViewer2D.
img_compare merges 2 images using a selected mode. It is thus possible to compare images visually.
inImage1
This is an image.
inDatamap1
This is a datamap for Image1.
inImage2
This is an image.
inDatamap2
This is a datamap for Image2.
Border Value
Border value changes from 0 to 1 and defines the position of the border between the parts of the merged image.
Merge Mode
There are 6 merge modes (from 0 to 5). Mode 0 is vertical slice, 1 is horizontal slice, 2 is diagonal, 3 is solid (Image1), 4 is circle, 5 is checkerboard.
Switch datasets
Swaps the source images.
out
The merged image.
The User Macro img_compare makes use of the Functional Macro ImageFunc and the UI Macro ImageUI.
An example application ImageEg is provided, which uses 2 different slices of the hydrogen data to display a merged image.
xp_comm_proj/img_comp/img_mods.v contains the V definitions of the ImageParams parameter block and the Image_Compare module.
xp_comm_proj/img_comp/img_macs.v contains the V definitions of the ImageFunc Functional Macro, the ImageUI User Interface Macro, and the img_compare User Macro.
xp_comm_proj/img_comp/img_apps.v contains the V definition of the example application ImageEg.
anonymous
Alexander Korban Manchester Visualization Centre


jSignature is a plugin for jQuery which simplifies the creation of a field that allows a user to enter a signature either via a mouse, your finger on touch enabled devices or a pen input device. This plugin is currently in alpha and is very much just a concept so it may not be ready for production.
Note: This plugin requires a browser that supports HTML Canvas.
Please report any bugs or suggestion to https://github.com/brinley/jSignature/issues
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
The setup is quite straight forward, simply include jQuery and jSignature.js. At present, this plugin has only been tested with jQuery 1.4.4
<script language="JavaScript" type="text/javascript" src="jSignature.js"></script> <script type="text/javascript"> $(document).ready(function() { // Prevent default for touch devices document.ontouchmove = function(e){ e.preventDefault(); } $("#signature").jSignature({color:"#00f",lineWidth:5}); }); </script>
| Name | Usage | Description |
| clear | .jSignature("clear") | Empties and resets the canvas. |
| getData | .jSignature("getData") | Converts the canvas into a base64 encoded data string which can be saved as a string in any database during a form post or submit. |
| Name | Description | Default |
| width | Defines the width of the canvas. Numerical value without % or px | 250 |
| height | Defines the height of the canvas. Numerical value without % or px | 150 |
| color | Defines the color of the strokes on the canvas. Accepts any color hex values. | #000 |
| bgcolor | Defines the background color of the canvas. Accepts any color hex values. | #fff |
| lineWidth | Defines the thickness of the lines. Accepts any positive numerical value | 1 |
| cssclass | Defines a custom class for the canvas. | None |
$("#signature1").jSignature();
$("#signature2").jSignature({color:"#f00"});
$("#signature3").jSignature({color:"#00f",lineWidth:5});
$("#signature4").jSignature({width:300,height:200});
$("#signature5").jSignature({color:"#00f",bgcolor:"#0f0"});


This article is part of a series of articles about three.js. The first article is three.js fundamentals. If you haven't read that yet and you're new to three.js you might want to consider starting there.
Three.js provides several types of materials. They define how objects will appear in the scene. Which materials you use really depends on what you're trying to accomplish.
There are 2 ways to set most material properties. One at creation time which we've seen before.
const material = new THREE.MeshPhongMaterial({ color: 0xFF0000, // red (can also use a CSS color string here) flatShading: true, });
The other is after creation
const material = new THREE.MeshPhongMaterial(); material.color.setHSL(0, 1, .5); // red material.flatShading = true;
note that properties of type THREE.Color
have multiple ways to be set.
material.color.set(0x00FFFF); // same as CSS's #RRGGBB style material.color.set(cssString); // any CSS color, eg 'purple', '#F32', // 'rgb(255, 127, 64)', // 'hsl(180, 50%, 25%)' material.color.set(someColor) // some other THREE.Color material.color.setHSL(h, s, l) // where h, s, and l are 0 to 1 material.color.setRGB(r, g, b) // where r, g, and b are 0 to 1
And at creation time you can pass either a hex number or a CSS string
const m1 = new THREE.MeshBasicMaterial({color: 0xFF0000}); // red const m2 = new THREE.MeshBasicMaterial({color: 'red'}); // red const m3 = new THREE.MeshBasicMaterial({color: '#F00'}); // red const m4 = new THREE.MeshBasicMaterial({color: 'rgb(255,0,0)'}); // red const m5 = new THREE.MeshBasicMaterial({color: 'hsl(0,100%,50%)'}); // red
So let's go over three.js's set of materials.
The MeshBasicMaterial
is not affected by lights.
The MeshLambertMaterial
computes lighting only at the vertices vs the MeshPhongMaterial
which computes lighting at every pixel. The MeshPhongMaterial
also supports specular highlights.
The shininess
setting of the MeshPhongMaterial
determines the shininess of the specular highlight. It defaults to 30.
Note that setting the emissive
property to a color on either a
MeshLambertMaterial
or a MeshPhongMaterial
and setting the color
to black
(and shininess
to 0 for phong) ends up looking just like the MeshBasicMaterial
.
Why have all 3 when MeshPhongMaterial
can do the same things as MeshBasicMaterial
and MeshLambertMaterial
? The reason is the more sophisticated material
takes more GPU power to draw. On a slower GPU like say a mobile phone
you might want to reduce the GPU power needed to draw your scene by
using one of the less complex materials. It also follows that if you
don't need the extra features then use the simplest material. If you don't
need the lighting and the specular highlight then use the MeshBasicMaterial
.
The MeshToonMaterial
is similar to the MeshPhongMaterial
with one big difference. Rather than shading smoothly it uses a gradient map
(an X by 1 texture) to decide how to shade. The default uses a gradient map
that is 70% brightness for the first 70% and 100% after but you can supply your
own gradient map. This ends up giving a 2 tone look that looks like a cartoon.
Next up there are 2 physically based rendering materials. Physically Based Rendering is often abbreviated PBR.
The materials above use simple math to make materials that look 3D but they aren't what actually happens in real world. The 2 PBR materials use much more complex math to come close to what actually happens in the real world.
The first one is MeshStandardMaterial
. The biggest difference between
MeshPhongMaterial
and MeshStandardMaterial
is it uses different parameters.
MeshPhongMaterial
had a shininess
setting. MeshStandardMaterial
has 2
settings roughness
and metalness
.
At a basic level roughness
is the opposite
of shininess
. Something that has a high roughness, like a baseball doesn't
have hard reflections whereas something that's not rough, like a billiard ball,
is very shiny. Roughness goes from 0 to 1.
The other setting, metalness
, says
how metal the material is. Metals behave differently than non-metals. 0
for non-metal and 1 for metal.
Here's a quick sample of MeshStandardMaterial
with roughness
from 0 to 1
across and metalness
from 0 to 1 down.
The MeshPhysicalMaterial
is same as the MeshStandardMaterial
but it
adds a clearcoat
parameter that goes from 0 to 1 for how much to
apply a clearcoat gloss layer and a clearCoatRoughness
parameter
that specifies how rough the gloss layer is.
Here's the same grid of roughness
by metalness
as above but with
clearcoat
and clearCoatRoughness
settings.
The various standard materials progress from fastest to slowest
MeshBasicMaterial
➡ MeshLambertMaterial
➡ MeshPhongMaterial
➡
MeshStandardMaterial
➡ MeshPhysicalMaterial
. The slower materials
can make more realistic looking scenes but you might need to design
your code to use the faster materials on low powered or mobile machines.
There are 3 materials that have special uses. ShadowMaterial
is used to get the data created from shadows. We haven't
covered shadows yet. When we do we'll use this material
to take a peek at what's happening behind the scenes.
The MeshDepthMaterial
renders the depth of each pixel where
pixels at negative near
of the camera are 0 and negative far
are 1. Certain special effects can use this data which we'll
get into at another time.
The MeshNormalMaterial
will show you the normals of geometry.
Normals are the direction a particular triangle or pixel faces.
MeshNormalMaterial
draws the view space normals (the normals relative to the camera).
x is red,
y is green, and
z is blue so things facing
to the right will be pink,
to the left will be aqua,
up will be light green,
down will be purple,
and toward the screen will be lavender.
ShaderMaterial
is for making custom materials using the three.js shader
system. RawShaderMaterial
is for making entirely custom shaders with
no help from three.js. Both of these topics are large and will be
covered later.
Most materials share a bunch of settings all defined by Material
.
See the docs
for all of them but let's go over two of the most commonly used
properties.
flatShading
:
whether or not the object looks faceted or smooth. default = false
.
side
: which sides of triangles to show. The default is THREE.FrontSide
.
Other options are THREE.BackSide
and THREE.DoubleSide
(both sides).
Most 3D objects drawn in three are probably opaque solids so the back sides
(the sides facing inside the solid) do not need to be drawn. The most common
reason to set side
is for planes or other non-solid objects where it is
common to see the back sides of triangles.
Here are 6 planes drawn with THREE.FrontSide
and THREE.DoubleSide
.
There's really a lot to consider with materials and we actually still have a bunch more to go. In particular we've mostly ignored textures which open up a whole slew of options. Before we cover textures though we need to take a break and cover setting up your development environment


|
|
| DateTime (time_t timestamp) |
| |
|
| DateTime (const tm &tm) |
| |
|
| DateTime (int year, int month, int day) |
| |
|
| DateTime (int year, int month, int day, int hour, int minute, int second) |
| |
|
| operator const ::tm * () const |
| |
|
int | GetDay () const |
| |
|
int | GetMonth () const |
| |
|
int | GetYear () const |
| |
|
int | GetHour () const |
| |
|
int | GetMinute () const |
| |
|
int | GetSecond () const |
| |
|
DayOfWeek | GetDayOfWeek () const |
| |
|
time_t | GetTimestamp () const |
| |
|
DateTime | AddYears (int years) const |
| |
|
DateTime | AddMonths (int months) const |
| |
|
DateTime | AddDays (int days) const |
| |
|
DateTime | AddHours (int hours) const |
| |
|
DateTime | AddMinutes (int minutes) const |
| |
|
DateTime | AddSeconds (int seconds) const |
| |
|
size_t | Format (char *s, size_t max, const char *fmt) const |
| |
The documentation for this class was generated from the following file:


Cambridge & the Covid moment
- One Public High School (we can feel like a big town)
- Two world-class universities (with a global population)
- Triple AAA credit rating for 20 straight years (we can borrow on the cheap)
If Cambridge can't pilot a new way forward for cities, who can?


INTRODUCTION TO INFORMATION SYSTEM:- What is information system. Types of Information System:
1. Operational Information System (OIS):-Office Automation System (OAS),Process Control System (PCS),Transaction Processing System (TPS)
Management Information System (MIS):-Information Reporting System (IRS), Decision Support System (DSS),Executive Information System (EIS), Knowledge Based System (KBS)