Integrating
Sun Java System Application Server with Sonic MQ 7.0 using
Generic Resource Adapter for JMS
By Ramesh Parthasarathy, July
2006
More often than not, EAI developers are faced with a situation
where they have to integrate disparate messaging products with
transactional
applications deployed in a Java EE application server. The preferred
message provider pluggability mechanism in J2EE 1.4 and beyond is,
using
the Connectors
1.5 architecture, but a lot of messaging providers do
not bundle Connectors 1.5 compliant resource adapters to help in this
integration. The situation is worse when the provider does not provider
an adapter ( even if its not Connection 1.5 based) for the
application server being used.
The Generic
resource adapter for JMS
project helps in integrating messaging products with
J2EE application servers by wrapping their JMS client library in a J2EE
Connector Architecture 1.5 resource adapter. It has been used to
integrate different messaging products like Tibco EMS, IBM WebSphere MQ
and Sun Java
System Message Queue with the Sun Java System Application
Server.
In this article we would
guide you through the steps for using the Generic Resource Adapter for
JMS [referred to as 'Generic RA' in the article going forward] to
integrate Sonic MQ 7.0 with Sun
Java
System Application Server 8.2 (SJSAS)
Instructions outlined in this article could also be used to integrate
Sonic MQ 7.0 with Project
GlassFish and the Java
EE 5 SDK preview/Sun Java System Application Server PE 9 versions
available today.
Contents
Article
Conventions/Assumptions
Through out this article, we have used the asadmin command line
interface to show all the interactions performed with the application
server. You could also use the asadmin GUI console to achieve
the
same. Similarly this article assumes a *nix based system [Solaris,
Linux]. If you are using Windows, Replace
the instructions with Windows equivalents as
necessary.
Similarly the steps outlined below assume a successful
installation of Sonic MQ 7.0 ("Typical" installation is assumed, if you
have done a "custom" installation you might require additional
configurations).
This article also assumes that the Sonic MQ broker and the
application server are deployed and running on the same physical
host/machine. If you have the MQ broker running on a different machine
and need to access it remotely, please refer the Sonic MQ
documentation for configuration details. The RA configuration and other
application server related configuration remains unchanged.
While looking at the configuration of the resource-adapter, connector
connection pool etc. in this article, only a handful of properties,
relevant for this discussion is covered. Please note that all the
resource adapter, connection factory and activationspec configuration,
listed in the Generic RA user
guide could be used while configuring these objects.
Initial
Setup
The following permissions need to be added to the server.policy and the
client.policy file to deploy the generic resource adapter and to run
the client application.
- Edit the server.policy file in the
[${appserver-install-dir}/domains/domain1/config/] directory using your
favourite text editor and add the following line to the default grant
block.
permission java.util.logging.LoggingPermission "control";
permission
java.util.PropertyPermission "*",
"read,write";
- Should you use an application client in your application,
edit
the application client's client.policy file in the
[${appserver-install-dir}/lib/appclient/client.policy] directory and
add the following line to it.
permission javax.security.auth.PrivateCredentialPermission
"javax.resource.spi.security.PasswordCredential * \"*\"","read";
- Modify the domain's classpath to add Sonic MQ 7.0 jars
located in Sonic MQ installation lib directory. The asadmin GUI could
be used to
modify a domain's classpath. Open a browser and type the url of the
application server admin GUI - http://hostname:adminport. Go to
Application Server -> JVM Settings -> Path Settings . Add
an
entry for the jar files shown below [comma-separated as shown below] in
the classpath suffix. Restart the application server domain for these
changes to take
effect.
/opt/Sonic/MQ7.0/lib/sonic_Client.jar
/opt/Sonic/MQ7.0/lib/mfcontext.jar
Set the LD_LIBRARY_PATH environment variable to /opt/Sonic/MQ7.0/lib
and restart the application server. For example in *NIX
system,
based on the choice of your shell. you would type in
$ export
LD_LIBRARY_PATH=/opt/Sonic/MQ7.0/lib
Configuring SonicMQ
administered objects
If a "Typical" installation was performed with default values it would
create a Domain Manager with following values :
Domain "Domain1"
Management Conatainer "DomainManager"
Management Broker "MgmtBroker"
Management Broker Port "2506"
Messaging Container <hostname of the machine>
Messaging Broker Name <hostname of the machine>
Messaging Broker Port "2507"
If your settings are different from the above then additional
configuration might be required to get the setup working. Please refer
the Sonic MQ
documentation for installation details. The following instructions are
based on the default values.
- Note: All artifacts created on the Sonic MQ side and
the application server side are shown in blue and green respectively in
the image above.
"/opt/Sonic" has been considered as the install location of Sonic MQ.
- Start the Sonic MQ container for the domain "Domain1"
$
/opt/Sonic/MQ7.0/bin/startcontainer.sh
- Create the required destinations :
3 queue destinations
have to be created , "inqueue", "outqueue" and the "deadmsgqueue"
The physical destinations can be
created in one of the 3 ways
- Through the sonic mq administration console
- Using the javascript samples
(/opt/Sonic/samples/Management/configApi/jsConfigBean).
- Exceuting the Java-based samples
(/opt/Sonic/samples/Management/configApi/javaConfigBean).
For e.g the following
steps have to be perfromed to create a queue "inqueue" in the default
- Go to the folder
/opt/Sonic/samples/Management/configApi/jsConfigBean and edit the
CreateQueue.js script. Set the QUEUE_NAME variable ( default would be
"NewQueue1") to "inqueue". Also comment out the following line in the
CreateQueue.js
//queue.setReadExclusive(true)
This will ensure that the queue does not have exclusive read access.
- Execute
# ../../../jsRun.sh CreateQueue.js
The output of the
command will be
inqueue doesn't exist. Creating it.
Queue: inqueue
Type = AdministrativelyCreated
Global = false
Exclusive = false
Max Size = 1000
Save Threshold = 1536
Queue: inqueue
Type = AdministrativelyCreated
Global = false
Exclusive = false
Max Size = 12345
Save Threshold = 1536
This would create a new physical
destination called "inqueue".
Similarly, create the other queues
(outqueue and deadmsgqueue).
- Create the jndi bindings :
In our example we would be
using the internal JNDI object store provided by Sonic MQ. The JNDI
bindings can be created either using the admin console or using
the
sample JNDI cli tool that is provided.
# cd
/opt/Sonic/samples/Management/jndiAPI/java
# ../../../Mgmt.sh
JndiCLI Domain1 tcp://localhost:2506 Administrator Administrator
( above command assumes
default values, modify if needed)
> bind qcf
inboundXAQCF
ConnectionURLs=tcp://localhost:2506,DefaultUser=Administrator,DefaultPassword=Administrator
>
bind qcf outboundXAQCF
ConnectionURLs=tcp://localhost:2506,DefaultUser=Administrator,DefaultPassword=Administrator
> bind
queue inqueue inqueue
> bind
queue outqueue outqueue
> bind
queue deadmsgqueue deadmsgqueue
The above
steps create the jndi bindings inbound Queue connection factory
with jndi name "inboundXAQCF", outbound Queue connection factory with
jndi name "outboundXAQCF", inbound queue with jndi
name "inqueue" and outbound queue with jndi name "outqueue, and dmd
queue with jndi
name "deadmsgqueue".
The jndiAPI
does not ( or iam not aware of) allow bindings of
type XAQueueConnectionFactory, so please change the "Factory Type" of
inboundXAQCF and outboundXAQCF to "XAQueueConnectionFactory"
through
the Sonic MQ admin console. The console can be started using the
command MQ7.0/bin/startmc.sh
To verify,
use
the list command
> list
testxa:
progress.message.jclient.QueueConnectionFactory
inqueue: progress.message.jclient.Queue
inboundXAQCF: progress.message.jclient.xa.XAQueueConnectionFactory
outboundXAQCF: progress.message.jclient.xa.XAQueueConnectionFactory
deadmsgqueue: progress.message.jclient.Queue
outqueue: progress.message.jclient.Queue
Configuring
the Resource Adapter
- Add ${appserver-install-dir}/bin to your PATH. The asadmin
CLI
command can be found at ${appserver-install-dir}/bin. In SJSAS, a
resource adapter configuration is used to specify the configuration of
a resource adapter. Use the following command to create a resource
adapter configuration for genericra, to configure it to work with
SonicMQ.
asadmin
create-resource-adapter-config --user <adminname>
--password
<admin password> --property SupportsXA=true:ProviderIntegrationMode=jndi:UserName=Administrator:Password=Administrator:JndiProperties=java.naming.factory.initial\=
com.sonicsw.jndi.mfcontext.MFContextFactory,java.naming.provider.url\=tcp\://localhost\:2506,com.sonicsw.jndi.mfcontext.domain\=Domain1,
java.naming.security.principal\=Administrator,java.naming.security.credentials\=Administrator:LogLevel=FINEST"
The security principal and
credentials are not required if "Security" is disabled in the domain
Domain1.
A brief description of the
various properties used in the above command is explained below:
SupportsXA
Set the supports distributed transactions attribute to true. The level
of transactional support the adapter provides -- none, local, or XA --
depends on the capabilities of the Enterprise Information System [EIS]
being adapted. If an adapter supports XA transactions and this
attribute is XA, the application can use distributed transactions to
coordinate the EIS resource with JDBC and JMS resources.
ProviderIntegrationMode
Set the integration mode as JNDI. Two integration modes exist in the
Generic Resource Adapter for JMS. The JNDI mode allows the resource
adapter to use the administered objects published in the message
provider's JNDI provider to integrate with the message provider.
Username and Password
Message provider specific user credentials. [In this case, modify this
attribute to reflect the SonicMQ username/password]
JndiProperties
This property [comma-separated list of name-value pairs] specifies JNDI
provider properties to be used for
connecting to the JMS provider's JNDI. In our case, we set it to the
JNDI configuration specified earlier.
Deploying
the Resource adapter
- Download the Generic RA bits from the project
site. With Sun
Java System Application Server 8.2 Platform Edition, Generic
RA is available out-of-the-box with the application server and you
could choose to use the bundled resource adapter as well in the step
below.
- Deploy the resource adapter using the asadmin deploy
command, as shown below. In the image above, see Generic JMS
RA deployed in the application server.
$ asadmin deploy --user admin --password
adminadmin
<location of the generic resource adapter rar file>
Creating
Connection Factories and Administered Objects in SJSAS
In order to configure a JMS Connection Factory, using the Generic
Resource Adapter for JMS, a Connector connection pool and resource
needs to be created in the application server, as shown below. In the
image above, see inpool [pointing to Generic JMS RA and QCF]
and jms/inboundXAQCF [for mypool] created in the application server.
Connector
connection pool creation
#Creates a Connection Pool called mypool and points to XAQCF created in
Sonic MQ
asadmin create-connector-connection-pool -- raname genericra
connectiondefinition javax.jms.QueueConnectionFactory
--transactionsupport XATransaction --property
ConnectionFactoryJndiName=inboundXAQCF inpool
#Creates a Connection Pool called mypool2 and points to XATCF created
in Sonic MQ
asadmin create-connector-connection-pool -- raname genericra
connectiondefinition javax.jms.QueueConnectionFactory
--transactionsupport XATransaction --property
ConnectionFactoryJndiName=outboundXAQCF outpool
Connector
resource creation
#Creates a connector resource named jms/MyQCF and
binds this resource to JNDI for applications to use.
asadmin create-connector-resource --poolname inpool jms/inboundXAQCF
Note: Though the inbound configuration of the RA happens through the
activation specification, a pool has to be created to make sure that
the transaction recovery happens when the application restarts. This is
because the transaction manager does recovery only for connector
resources that are registered in domain.xml.
#Creates a connector resource named jms/MyTCF and
binds this resource to JNDI for applications to use.
asadmin create-connector-resource --poolname outpool jms/outboundXAQCF
Admin
Objects
For JMS Destination Resources, an administered object needs to be
created. In the image above, see jms/MyQueue [pointing to Generic JMS
RA and TQueue] created in the application server.
#Creates a javax.jms.Queue Administered Object and binds it to
application server's JNDI tree at
jms/inqueue and points to inqueue created in Sonic MQ.
asadmin create-admin-object --raname genericra --restype
javax.jms.Queue --property DestinationJndiName=inqueue jms/inqueue
#Creates a javax.jms.Topic Administered Object and binds it to
application server's JNDI tree at
jms/MyTopic and points to outqueue created in Sonic MQ.
asadmin create-admin-object --raname genericra --restype
javax.jms.Topic --property DestinationJndiName=outqueue jms/outqueue
Component
Deployment descriptors.
The deployment descriptors need to take into account the resource
adapter and the connection resources that have been created. A sample
sun-ejb-jar.xml for a Message Driven Bean that listens to a destination
called inqueue in SonicMQ, and publishes back reply messages to a
destination resource named jms/outqueue is shown below.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD
Application Server 8.1 EJB 2.1//EN"
"http://www.sun.com/software/appserver/dtds/sun-ejb-jar_2_1-1.dtd">
<sun-ejb-jar>
<enterprise-beans>
<ejb>
<ejb-name>SonicMQTestMDB</ejb-name>
<jndi-name>SonicMQTestMDB</jndi-name>
<resource-ref>
<res-ref-name>jms/outboundXAQCF</res-ref-name>
<jndi-name>jms/outboundXAQCF</jndi-name>
</resource-ref>
<resource-env-ref>
<resource-env-ref-name>jms/outqueue</resource-env-ref-name>
<jndi-name>jms/outqueue</jndi-name>
</resource-env-ref>
<bean-pool>
<steady-pool-size>10</steady-pool-size>
<resize-quantity>2</resize-quantity>
<max-pool-size>30</max-pool-size>
<pool-idle-timeout-in-seconds>60</pool-idle-timeout-in-seconds>
</bean-pool>
<mdb-resource-adapter>
<resource-adapter-mid>genericra</resource-adapter-mid>
<activation-config>
<activation-config-property>
<activation-config-property-name>DestinationType</activation-config-property-name>
<activation-config-property-value>javax.jms.Queue</activation-config-property-value>
</activation-config-property>
<activation-config-property>
<activation-config-property-name>MaxPoolSize</activation-config-property-name>
<activation-config-property-value>30</activation-config-property-value>
</activation-config-property>
<activation-config-property>
<activation-config-property-name>RedeliveryAttempts</activation-config-property-name>
<activation-config-property-value>3</activation-config-property-value>
</activation-config-property>
<activation-config-property>
<activation-config-property-name>RedeliveryInterval</activation-config-property-name>
<activation-config-property-value>1</activation-config-property-value>
</activation-config-property>
<activation-config-property>
<activation-config-property-name>ReconnectAttempts</activation-config-property-name>
<activation-config-property-value>1000</activation-config-property-value>
</activation-config-property>
<activation-config-property>
<activation-config-property-name>ReconnectInterval</activation-config-property-name>
<activation-config-property-value>1</activation-config-property-value>
</activation-config-property>
<activation-config-property>
<activation-config-property-name>ConnectionFactoryJndiName</activation-config-property-name>
<activation-config-property-value>inboundXAQCF</activation-config-property-value>
</activation-config-property>
<activation-config-property>
<activation-config-property-name>DestinationJndiName</activation-config-property-name>
<activation-config-property-value>inqueue</activation-config-property-value>
</activation-config-property>
<activation-config-property>
<activation-config-property-name>SendBadMessagesToDMD</activation-config-property-name>
<activation-config-property-value>true</activation-config-property-value>
</activation-config-property>
<activation-config-property>
<activation-config-property-name>DeadMessageDestinationType</activation-config-property-name>
<activation-config-property-value>javax.jms.Queue</activation-config-property-value>
</activation-config-property>
<activation-config-property>
<activation-config-property-name>DeadMessageDestinationJndiName</activation-config-property-name>
<activation-config-property-value>deadmsgqueue</activation-config-property-value>
</activation-config-property>
<activation-config-property>
<activation-config-property-name>DeadMessageConnectionFactoryJndiName</activation-config-property-name>
<activation-config-property-value>outboundXAQCF</activation-config-property-value>
</activation-config-property>
<activation-config-property>
<activation-config-property-name>EndpointReleaseTimeOut</activation-config-property-name>
<activation-config-property-value>30</activation-config-property-value>
</activation-config-property>
</activation-config>
</mdb-resource-adapter>
</ejb>
</enterprise-beans>
</sun-ejb-jar>
The business logic encoded in Message Driven Bean could then lookup the
configured QueueConnectionFactory/Destination resource
to create a connection as shown below.
/**
* Creates a bean. Required by EJB spec.
*/
public void ejbCreate() {
System.out.println("In SonicMQTestBean.ejbCreate()");
try {
Context jndiContext = new InitialContext();
queueConnectionFactory = (QueueConnectionFactory)
jndiContext.lookup("java:comp/env/jms/outboundXAQCF");
queue = (Queue)jndiContext.lookup("jms/outqueue");
} catch (Exception e) {
System.out.println("MESSAGEBEAN.ejbcreate() got
Exception "+ e.getMessage());
e.printStackTrace();
}
}
/**
* When the queue receives a message, the EJB
container invokes the onMessage
* method of the message-driven bean. In the
SonicMQTestBean class, the
* onMessage method
casts the incoming message to a TextMessage and displays the text.
* @param inMessage incoming message.
*/
public void onMessage(Message inMessage) {
QueueConnection qconn = null;
try {
if
(inMessage instanceof TextMessage) {
TextMessage txtmsg =
(TextMessage)inMessage;
if (txtmsg.getText().trim().equals("2"))
{
// if (!txtmsg.getJMSRedelivered()) {
throw new RuntimeException("payload cannot be 2");
// }
}
System.out.println("MESSAGE BEAN: Message received:
index="+txtmsg.getText());
qconn = queueConnectionFactory.createQueueConnection();
QueueSession qss = qconn.createQueueSession(false,
Session.AUTO_ACKNOWLEDGE);
QueueSender sender = qss.createSender(queue);
TextMessage msg = qss.createTextMessage();
msg.setText(txtmsg.getText());
sender.send(msg);
qconn.close();
}
else {
System.out.println("WRONG MESSAGE TYPE received: " +
inMessage.getClass().getName());
}
} catch (Throwable t) {
t.printStackTrace();
mdc.setRollbackOnly();
try {
if (qconn != null) qconn.close();
System.out.println("MESSAGE BEAN: Rollback:
index="+((TextMessage)inMessage).getText());
}
catch (Exception e) {
System.out.println("MESSAGE BEAN: Unable to get index property
because:"+e.getMessage());
e.printStackTrace();
}
throw new RuntimeException(t.getMessage());
}
Resources
Thanks to Binod PG and SivaKumar Thyagarajan
for reviewing this documentation and providing
feedback.


Teleoperation interface for Jetbot
This This interface allows to control the Jetbot platform using either the keyboard or a gamepad:
steering = 0
throttle = 0
throttle_factor = 0.2


≡
Home
Habitat
Facts
Protection
Media
Useful links
Chart
Map
Settings
Bold
Italic
Small caps
Settings
Select your favorite font:
PT Sans
Baloo Bhaina
Ranga
Merriweather
Cinzel Decorative
Select you favorite color:
Orange
Green
Blue


We are a small but effective team of change agents who expose the issues, and work collaboratively to find solutions. We count on your support to enable the work that we do. With your support, we can make the world a better place one film, one action, and one person at a time.


The term Facelets refers to the view declaration language for JavaServer Faces technology. Facelets is a part of the JavaServer Faces specification and also the preferred presentation technology for building JavaServer Faces technology–based applications. JavaServer Pages (JSP) technology, previously used as the presentation technology for JavaServer Faces, does not support all the new features available in JavaServer Faces in the Java EE 7 platform. JSP technology is considered to be a deprecated presentation technology for JavaServer Faces.
The following topics are addressed here:
Facelets is a powerful but lightweight page declaration language that is used to build JavaServer Faces views using HTML style templates and to build component trees. Facelets features include the following:
Use of XHTML for creating web pages
Support for Facelets tag libraries in addition to JavaServer Faces and JSTL tag libraries
Support for the Expression Language (EL)
Templating for components and pages
The advantages of Facelets for large-scale development projects include the following:
Support for code reuse through templating and composite components
Functional extensibility of components and other server-side objects through customization
Faster compilation time
Compile-time EL validation
High-performance rendering
In short, the use of Facelets reduces the time and effort that needs to be spent on development and deployment.
Facelets views are usually created as XHTML pages. JavaServer Faces implementations support XHTML pages created in conformance with the XHTML Transitional Document Type Definition (DTD), as listed at http://www.w3.org/TR/xhtml1/#a_dtd_XHTML-1.0-Transitional
. By convention, web pages built with XHTML have an .xhtml
extension.
JavaServer Faces technology supports various tag libraries to add components to a web page. To support the JavaServer Faces tag library mechanism, Facelets uses XML namespace declarations. Table 8-1 lists the tag libraries supported by Facelets.
Table 8-1 Tag Libraries Supported by Facelets
| Tag Library | URI | Prefix | Example | Contents |
|---|---|---|---|---|
|
JavaServer Faces Facelets Tag Library |
|
|
|
Tags for templating |
|
JavaServer Faces HTML Tag Library |
|
|
|
JavaServer Faces component tags for all |
|
JavaServer Faces Core Tag Library |
|
|
|
Tags for JavaServer Faces custom actions that are independent of any particular render kit |
|
Pass-through Elements Tag Library |
|
|
|
Tags to support HTML5-friendly markup |
|
Pass-through Attributes Tag Library |
|
|
|
Tags to support HTML5-friendly markup |
|
Composite Component Tag Library |
|
|
|
Tags to support composite components |
|
JSTL Core Tag Library |
|
|
|
JSTL 1.2 Core Tags |
|
JSTL Functions Tag Library |
|
|
|
JSTL 1.2 Functions Tags |
Facelets provides two namespaces to support HTML5-friendly markup. For details, see HTML5-Friendly Markup.
Facelets supports tags for composite components, for which you can declare custom prefixes. For more information on composite components, see Composite Components.
The namespace prefixes shown in the table are conventional, not mandatory. As is always the case when you declare an XML namespace, you can specify any prefix in your Facelets page. For example, you can declare the prefix for the composite component tag library as
xmlns:composite="http://java.sun.com/jsf/composite"
instead of as
xmlns:cc="http://java.sun.com/jsf/composite"
Based on the JavaServer Faces support for Expression Language (EL) syntax, Facelets uses EL expressions to reference properties and methods of managed beans. EL expressions can be used to bind component objects or values to methods or properties of managed beans that are used as backing beans. For more information on using EL expressions, see Using the EL to Reference Managed Beans.
The JavaServer Faces specification defines the lifecycle of a JavaServer Faces application. For more information on this lifecycle, see The Lifecycle of a JavaServer Faces Application. The following steps describe that process as applied to a Facelets-based application.
When a client, such as a browser, makes a new request to a page that is created using Facelets, a new component tree or javax.faces.component.UIViewRoot
is created and placed in the FacesContext
.
The UIViewRoot
is applied to the Facelets, and the view is populated with components for rendering.
The newly built view is rendered back as a response to the client.
On rendering, the state of this view is stored for the next request. The state of input components and form data is stored.
The client may interact with the view and request another view or change from the JavaServer Faces application. At this time, the saved view is restored from the stored state.
The restored view is once again passed through the JavaServer Faces lifecycle, which eventually will either generate a new view or re-render the current view if there were no validation problems and no action was triggered.
If the same view is requested, the stored view is rendered once again.
If a new view is requested, then the process described in Step 2 is continued.
The new view is then rendered back as a response to the client.
This section describes the general steps involved in developing a JavaServer Faces application. The following tasks are usually required:
Developing the managed beans
Creating the pages using the component tags
Defining page navigation
Mapping the FacesServlet
instance
Adding managed bean declarations
The example used in this tutorial is the guessnumber-jsf
application. The application presents you with a page that asks you to guess a number from 0 to 10, validates your input against a random number, and responds with another page that informs you whether you guessed the number correctly or incorrectly.
The source code for this application is in the tut-install/examples/web/jsf/guessnumber-jsf/
directory.
In a typical JavaServer Faces application, each page of the application connects to a managed bean that serves as a backing bean. The backing bean defines the methods and properties that are associated with the components. In this example, both pages use the same backing bean.
The following managed bean class, UserNumberBean.java
, generates a random number from 0 to 10 inclusive:
package javaeetutorial.guessnumber; import java.io.Serializable; import java.util.Random; import javax.enterprise.context.SessionScoped; import javax.inject.Named; @Named @SessionScoped public class UserNumberBean implements Serializable { private static final long serialVersionUID =<PHONE_NUMBER>396868724L; Integer randomInt = null; Integer userNumber = null; String response = null; private int maximum = 10; private int minimum = 0; public UserNumberBean() { Random randomGR = new Random(); randomInt = new Integer(randomGR.nextInt(maximum + 1)); // Print number to server log System.out.println("Duke's number: " + randomInt); } public void setUserNumber(Integer user_number) { userNumber = user_number; } public Integer getUserNumber() { return userNumber; } public String getResponse() { if ((userNumber == null) || (userNumber.compareTo(randomInt) != 0)) { return "Sorry, " + userNumber + " is incorrect."; } else { return "Yay! You got it!"; } } public int getMaximum() { return (this.maximum); } public void setMaximum(int maximum) { this.maximum = maximum; } public int getMinimum() { return (this.minimum); } public void setMinimum(int minimum) { this.minimum = minimum; } }
Note the use of the @Named
annotation, which makes the managed bean accessible through the EL. The @SessionScoped
annotation registers the bean scope as session
to enable you to make multiple guesses as you run the application.
To create a page or view, you add components to the pages, wire the components to backing bean values and properties, and register converters, validators, or listeners on the components.
For the example application, XHTML web pages serve as the front end. The first page of the example application is a page called greeting.xhtml
. A closer look at various sections of this web page provides more information.
The first section of the web page declares the content type for the page, which is XHTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
The next section specifies the language of the XHTML page and then declares the XML namespace for the tag libraries that are used in the web page:

The next section uses various tags to insert components into the web page:
<h:head> <h:outputStylesheet library="css" name="default.css"/> <title>Guess Number Facelets Application</title> </h:head> <h:body> <h:form> <h:graphicImage value="#{resource['images:wave.med.gif']}" alt="Duke waving his hand"/>
 Hi, my name is Duke. I am thinking of a number from #{userNumberBean.minimum} to #{userNumberBean.maximum}. Can you guess it?

<h:inputText id="userNo" title="Enter a number from 0 to 10:" value="#{userNumberBean.userNumber}"> <f:validateLongRange minimum="#{userNumberBean.minimum}" maximum="#{userNumberBean.maximum}"/> </h:inputText> <h:commandButton id="submit" value="Submit" action="response"/>
 <h:message showSummary="true" showDetail="false" style="color: #d20005; font-family: 'New Century Schoolbook', serif; font-style: oblique; text-decoration: overline" id="errors1" for="userNo"/> </h:form> </h:body>
Note the use of the following tags:
Facelets HTML tags (those beginning with h:
) to add components
The Facelets core tag f:validateLongRange
to validate the user input
An h:inputText
tag accepts user input and sets the value of the managed bean property userNumber
through the EL expression #{userNumberBean.userNumber}
. The input value is validated for value range by the JavaServer Faces standard validator tag f:validateLongRange
.
The image file, wave.med.gif
, is added to the page as a resource, as is the style sheet. For more details about the resources facility, see Web Resources.
An h:commandButton
tag with the ID submit
starts validation of the input data when a user clicks the button. Using implicit navigation, the tag redirects the client to another page, response.xhtml
, which shows the response to your input. The page specifies only response
, which by default causes the server to look for response.xhtml
.
You can now create the second page, response.xhtml
, with the following content:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <h:head> <h:outputStylesheet library="css" name="default.css"/> <title>Guess Number Facelets Application</title> </h:head> <h:body> <h:form> <h:graphicImage value="#{resource['images:wave.med.gif']}" alt="Duke waving his hand"/>
 <h:outputText id="result" value="#{userNumberBean.response}"/>
 <h:commandButton id="back" value="Back" action="greeting"/> </h:form> </h:body>
This page also uses implicit navigation, setting the action
attribute for the Back button to send the user to the greeting.xhtml
page.
Configuring a JavaServer Faces application involves mapping the Faces Servlet in the web deployment descriptor file, such as a web.xml
file, and possibly adding managed bean declarations, navigation rules, and resource bundle declarations to the application configuration resource file, faces-config.xml
.
If you are using NetBeans IDE, a web deployment descriptor file is automatically created for you. In such an IDE-created web.xml
file, change the default greeting page, which is index.xhtml
, to greeting.xhtml
. Here is an example web.xml
file, showing this change in bold.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>greeting.xhtml</welcome-file>
</welcome-file-list>
</web-app>
Note the use of the context parameter PROJECT_STAGE
. This parameter identifies the status of a JavaServer Faces application in the software lifecycle.
The stage of an application can affect the behavior of the application. For example, if the project stage is defined as Development
, debugging information is automatically generated for the user. If not defined by the user, the default project stage is Production
.
You can use either NetBeans IDE or Maven to build, package, deploy, and run the guessnumber-jsf
example.
Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server).
From the File menu, choose Open Project.
In the Open Project dialog box, navigate to:
tut-install/examples/web/jsf
Select the guessnumber-jsf
folder.
Click Open Project.
In the Projects tab, right-click the guessnumber-jsf
project and select Build.
This option builds the example application and deploys it to your GlassFish Server instance.
Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server).
In a terminal window, go to:
tut-install/examples/web/jsf/guessnumber-jsf/
Enter the following command:
mvn install
This command builds and packages the application into a WAR file, guessnumber-jsf.war
, that is located in the target
directory. It then deploys it to the server.
Open a web browser.
Enter the following URL in your web browser:
http://localhost:8080/guessnumber-jsf
In the field, enter a number from 0 to 10 and click Submit.
Another page appears, reporting whether your guess is correct or incorrect.
If you guessed incorrectly, click Back to return to the main page.
You can continue to guess until you get the correct answer, or you can look in the server log, where the UserNumberBean
constructor displays the correct answer.
JavaServer Faces technology provides the tools to implement user interfaces that are easy to extend and reuse. Templating is a useful Facelets feature that allows you to create a page that will act as the base, or template, for the other pages in an application. By using templates, you can reuse code and avoid recreating similarly constructed pages. Templating also helps in maintaining a standard look and feel in an application with a large number of pages.
Table 8-2 lists Facelets tags that are used for templating and their respective functionality.
Table 8-2 Facelets Templating Tags
| Tag | Function |
|---|---|
|
|
Defines a component that is created and added to the component tree. |
|
|
Defines a page composition that optionally uses a template. Content outside of this tag is ignored. |
|
|
Defines a debug component that is created and added to the component tree. |
|
|
Similar to the composition tag but does not disregard content outside this tag. |
|
|
Defines content that is inserted into a page by a template. |
|
|
Similar to the component tag but does not disregard content outside this tag. |
|
|
Encapsulates and reuses content for multiple pages. |
|
|
Inserts content into a template. |
|
|
Used to pass parameters to an included file. |
|
|
Used as an alternative for loop tags, such as |
|
|
Removes content from a page. |
For more information on Facelets templating tags, see the documentation at http://docs.oracle.com/javaee/7/javaserverfaces/2.2/vdldocs/facelets/
.
The Facelets tag library includes the main templating tag ui:insert
. A template page that is created with this tag allows you to define a default structure for a page. A template page is used as a template for other pages, usually referred to as client pages.
Here is an example of a template saved as template.xhtml
:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <h:head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <h:outputStylesheet library="css" name="default.css"/> <h:outputStylesheet library="css" name="cssLayout.css"/> <title>Facelets Template</title> </h:head> <h:body>
 <ui:insert name="top">Top Section</ui:insert>

 <ui:insert name="left">Left Section</ui:insert>

 <ui:insert name="content">Main Content</ui:insert>

 </h:body>
The example page defines an XHTML page that is divided into three sections: a top section, a left section, and a main section. The sections have style sheets associated with them. The same structure can be reused for the other pages of the application.
The client page invokes the template by using the ui:composition
tag. In the following example, a client page named templateclient.xhtml
invokes the template page named template.xhtml
from the preceding example. A client page allows content to be inserted with the help of the ui:define
tag.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <h:body> <ui:composition template="./template.xhtml"> <ui:define name="top"> Welcome to Template Client Page </ui:define> <ui:define name="left"> <h:outputLabel value="You are in the Left Section"/> </ui:define> <ui:define name="content"> <h:graphicImage value="#{resource['images:wave.med.gif']}"/> <h:outputText value="You are in the Main Content Section"/> </ui:define> </ui:composition> </h:body>
You can use NetBeans IDE to create Facelets template and client pages. For more information on creating these pages, see https://netbeans.org/kb/docs/web/jsf20-intro.html
.
JavaServer Faces technology offers the concept of composite components with Facelets. A composite component is a special type of template that acts as a component.
Any component is essentially a piece of reusable code that behaves in a particular way. For example, an input component accepts user input. A component can also have validators, converters, and listeners attached to it to perform certain defined actions.
A composite component consists of a collection of markup tags and other existing components. This reusable, user-created component has a customized, defined functionality and can have validators, converters, and listeners attached to it like any other component.
With Facelets, any XHTML page that contains markup tags and other components can be converted into a composite component. Using the resources facility, the composite component can be stored in a library that is available to the application from the defined resources location.
Table 8-3 lists the most commonly used composite tags and their functions.
Table 8-3 Composite Component Tags
| Tag | Function |
|---|---|
|
|
Declares the usage contract for a composite component. The composite component can be used as a single component whose feature set is the union of the features declared in the usage contract. |
|
|
Defines the implementation of the composite component. If a |
|
|
Declares an attribute that may be given to an instance of the composite component in which this tag is declared. |
|
|
Any child components or template text within the composite component tag in the using page will be reparented into the composite component at the point indicated by this tag's placement within the |
|
|
Declares that the composite component whose contract is declared by the |
|
|
Declares that the composite component whose contract is declared by the |
|
|
Declares that the composite component whose contract is declared by the |
For more information and a complete list of Facelets composite tags, see the documentation at http://docs.oracle.com/javaee/7/javaserverfaces/2.2/vdldocs/facelets/
.
The following example shows a composite component that accepts an email address as input:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <h:head> <title>This content will not be displayed</title> </h:head> <h:body> <composite:interface> <composite:attribute name="value" required="false"/> </composite:interface> <composite:implementation> <h:outputLabel value="Email id: "></h:outputLabel> <h:inputText value="#{cc.attrs.value}"></h:inputText> </composite:implementation> </h:body>
Note the use of cc.attrs.value
when defining the value of the inputText
component. The word cc
in JavaServer Faces is a reserved word for composite components. The #{cc.attrs.
attribute-name}
expression is used to access the attributes defined for the composite component's interface, which in this case happens to be value
.
The preceding example content is stored as a file named email.xhtml
in a folder named resources/emcomp
, under the application web root directory. This directory is considered a library by JavaServer Faces, and a component can be accessed from such a library. For more information on resources, see Web Resources.
The web page that uses this composite component is generally called a using page. The using page includes a reference to the composite component, in the xml
namespace declarations:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <h:head> <title>Using a sample composite component</title> </h:head>  <h:form>  </h:form>
The local composite component library is defined in the xmlns
namespace with the declaration xmlns:em="http://xmlns.jcp.org/jsf/composite/emcomp"
. The component itself is accessed through the em:email
tag. The preceding example content can be stored as a web page named emuserpage.xhtml
under the web root directory. When compiled and deployed on a server, it can be accessed with the following URL:
http://localhost:8080/application-name/emuserpage.xhtml
See Chapter 14, "Composite Components: Advanced Topics and an Example," for more information and an example.
Web resources are any software artifacts that the web application requires for proper rendering, including images, script files, and any user-created component libraries. Resources must be collected in a standard location, which can be one of the following.
A resource packaged in the web application root must be in a subdirectory of a resources
directory at the web application root: resources/
resource-identifier.
A resource packaged in the web application's classpath must be in a subdirectory of the META-INF/resources
directory within a web application: META-INF/resources/
resource-identifier. You can use this file structure to package resources in a JAR file bundled in the web application.
The JavaServer Faces runtime will look for the resources in the preceding listed locations, in that order.
Resource identifiers are unique strings that conform to the following format (all on one line):
[locale-prefix/][library-name/][library-version/]resource-name[/resource-version]
Elements of the resource identifier in brackets ([]
) are optional, indicating that only a resource-name, which is usually a file name, is a required element. For example, the most common way to specify a style sheet, image, or script is to use the library
and name
attributes, as in the following tag from the guessnumber-jsf
example:
<h:outputStylesheet library="css" name="default.css"/>
This tag specifies that the default.css
style sheet is in the directory web/resources/css
.
You can also specify the location of an image using the following syntax, also from the guessnumber-jsf
example:
<h:graphicImage value="#{resource['images:wave.med.gif']}"/>
This tag specifies that the image named wave.med.gif
is in the directory web/resources/images
.
Resources can be considered as a library location. Any artifact, such as a composite component or a template that is stored in the resources
directory, becomes accessible to the other application components, which can use it to create a resource instance.
You can place a resource tag in one part of a page and specify that it be rendered in another part of the page. To do this, you use the target
attribute of a tag that specifies a resource. Acceptable values for this attribute are as follows.
"head"
renders the resource in the head
element.
"body"
renders the resource in the body
element.
"form"
renders the resource in the form
element.
For example, the following h:outputScript
tag is placed within an h:form
element, but it renders the JavaScript in the head
element:
<h:form> <h:outputScript name="myscript.js" library="mylibrary" target="head"/> </h:form>
The h:outputStylesheet
tag also supports resource relocation, in a similar way.
Relocatable resources are essential for composite components that use stylesheets and can also be useful for composite components that use JavaScript. See The compositecomponentexample Example Application for an example.
Resource library contracts allow you to define a different look and feel for different parts of one or more applications, instead of either having to use the same look and feel for all or having to specify a different look on a page-by-page basis.
To do this, you create a contracts
section of your web application. Within the contracts
section, you can specify any number of named areas, each of which is called a contract. Within each contract you can specify resources such as template files, stylesheets, JavaScript files, and images.
For example, you could specify two contracts named c1
and c2
, each of which uses a template and other files:
src/main/webapp WEB-INF/ contracts c1 template.xhtml style.css myImg.gif myJS.js c2 template.xhtml style2.css img2.gif JS2.js index.xhtml ...
One part of the application can use c1
, while another can use c2
.
Another way to use contracts is to specify a single contract that contains multiple templates:
src/main/webapp contracts myContract template1.xhtml template2.xhtml style.css img.png img2.png
You can package a resource library contract in a JAR file for reuse in different applications. If you do so, the contracts must be located under META-INF/contracts
. You can then place the JAR file in the WEB-INF/lib
directory of an application. This means that the application would be organized as follows:
src/main/webapp/ WEB-INF/lib/myContract.jar ...
You can specify the contract usage within an application's faces-config.xml
file, under the resource-library-contracts
element. You need to use this element only if your application uses more than one contract, however.
The hello1-rlc
example modifies the simple hello1
example from A Web Module That Uses JavaServer Faces Technology: The hello1 Example to use two resource library contracts. Each of the two pages in the application uses a different contract.
The managed bean for hello1-rlc
, Hello.java
, is identical to the one for hello1
(except that it replaces the @Named
and @RequestScoped
annotations with @Model
).
The source code for this application is in the tut-install/examples/web/jsf/hello1-rlc/
directory.
The faces-config.xml
file for the hello1-rlc
example contains the following elements:
<resource-library-contracts> <contract-mapping> <url-pattern>/reply/*</url-pattern> <contracts>reply</contracts> </contract-mapping> <contract-mapping> <url-pattern>*</url-pattern> <contracts>hello</contracts> </contract-mapping> </resource-library-contracts>
The contract-mapping
elements within the resource-library-contracts
element map each contract to a different set of pages within the application. One contract, named reply
, is used for all pages under the reply
area of the application (/reply/*
). The other contract, hello
, is used for all other pages in the application (*
).
The application is organized as follows:
hello1-rlc pom.xml src/main/java/javaeetutorial/hello1rlc/Hello.java src/main/webapp WEB-INF faces-config.xml web.xml contracts hello default.css duke.handsOnHips.gif template.xhtml reply default.css duke.thumbsup.gif template.xhtml reply response.xhtml greeting.xhtml
The web.xml
file specifies the welcome-file
as greeting.xhtml
. Because it is not located under src/main/webapp/reply
, this Facelets page uses the hello
contract, whereas src/main/webapp/reply/response.xhtml
uses the reply
contract.
The greeting.xhtml
and response.xhtml
pages have identical code calling in their templates:
<ui:composition template="/template.xhtml">
The template.xhtml
files in the hello
and reply
contracts differ only in two respects: the placeholder text for the title
element ("Hello Template" and "Reply Template") and the graphic that each specifies.
The default.css
stylesheets in the two contracts differ in only one respect: the background color specified for the body
element.
Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server).
From the File menu, choose Open Project.
In the Open Project dialog box, navigate to:
tut-install/examples/web/jsf
Select the hello1-rlc
folder.
Click Open Project.
In the Projects tab, right-click the hello1-rlc
project and select Build.
This option builds the example application and deploys it to your GlassFish Server instance.
Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server).
In a terminal window, go to:
tut-install/examples/web/jsf/hello1-rlc/
Enter the following command:
mvn install
This command builds and packages the application into a WAR file, hello1-rlc.war
, that is located in the target
directory. It then deploys it to your GlassFish Server instance.
Enter the following URL in your web browser:
http://localhost:8080/hello1-rlc
The greeting.xhtml
page looks just like the one from hello1
except for its background color and graphic.
In the text field, enter your name and click Submit.
The response page also looks just like the one from hello1
except for its background color and graphic.
The page displays the name you submitted. Click Back to return to the greeting.xhtml
page.
When you want to produce user interface features for which HTML does not have its own elements, you can create a custom JavaServer Faces component and insert it in your Facelets page. This mechanism can cause a simple element to create complex web code. However, creating such a component is a significant task (see Chapter 15, "Creating Custom UI Components and Other Custom Objects").
HTML5 offers new elements and attributes that can make it unnecessary to write your own components. It also provides many new capabilities for existing components. JavaServer Faces technology supports HTML5 not by introducing new UI components that imitate HTML5 ones but by allowing you to use HTML5 markup directly. It also allows you to use JavaServer Faces attributes within HTML5 elements. JavaServer Faces technology support for HTML5 falls into two categories:
Pass-through elements
Pass-through attributes
The effect of the HTML5-friendly markup feature is to offer the Facelets page author almost complete control over the rendered page output, rather than having to pass this control off to component authors. You can mix and match JavaServer Faces and HTML5 components and elements as you see fit.
Pass-through elements allow you to use HTML5 tags and attributes but to treat them as equivalent to JavaServer Faces components associated with a server-side UIComponent
instance.
To make an element that is not a JavaServer Faces element a pass-through element, specify at least one of its attributes using the http://xmlns.jcp.org/jsf
namespace. For example, the following code declares the namespace with the short name jsf
:
<html ... xmlns:jsf="http://xmlns.jcp.org/jsf" ... <input type="email" jsf:id="email" name="email" value="#{reservationBean.email}" required="required"/>
Here, the jsf
prefix is placed on the id
attribute so that the HTML5 input tag's attributes are treated as part of the Facelets page. This means that, for example, you can use EL expressions to retrieve managed bean properties.
Table 8-4 shows how pass-through elements are rendered as Facelets tags. The JSF implementation uses the element name and the identifying attribute to determine the corresponding Facelets tag that will be used in the server-side processing. The browser, however, interprets the markup that the page author has written.
 They allow you to pass attributes that are not JavaServer Faces attributes through to the browser without interpretation. If you specify a pass-through attribute in a JavaServer Faces UIComponent
, the attribute name and value are passed straight through to the browser without being interpreted by JavaServer Faces components or renderers. There are several ways to specify pass-through attributes.
Use the JavaServer Faces namespace for pass-through attributes to prefix the attribute names within a JavaServer Faces component. For example, the following code declares the namespace with the short name p
, then passes the type
, min
, max
, required
, and title
attributes through to the HTML5 input
component:
<html ... xmlns:p="http://xmlns.jcp.org/jsf/passthrough" ... <h:form prependId="false"> <h:inputText id="nights" p:type="number" value="#{bean.nights}" p:min="1" p:max="30" p:required="required" p:title="Enter a number between 1 and 30 inclusive."> ...
This will cause the following markup to be rendered (assuming that bean.nights
has a default value set to 1):
<input id="nights" type="number" value="1" min="1" max="30" required="required" title="Enter a number between 1 and 30 inclusive.">
To pass a single attribute, nest the f:passThroughAttribute
tag within a component tag. For example:
<h:inputText value="#{user.email}"> <f:passThroughAttribute name="type" value="email" /> </h:inputText>
This code would be rendered similarly to the following:
<input<EMAIL_ADDRESS>type="email" />
To pass a group of attributes, nest the f:passThroughAttributes
tag within a component tag, specifying an EL value that must evaluate to a Map<String, Object>
. For example:
<h:inputText value="#{bean.nights"> <f:passThroughAttributes value="#{bean.nameValuePairs}" /> </h:inputText>
If the bean used the following Map
declaration and initialized the map in the constructor as follows, the markup would be similar to the output of the code that uses the pass-through attribute namespace:
private Map<String, Object> nameValuePairs; ... public Bean() { this.nameValuePairs = new HashMap<>(); this.nameValuePairs.put("type", "number"); this.nameValuePairs.put("min", "1"); this.nameValuePairs.put("max", "30"); this.nameValuePairs.put("required", "required"); this.nameValuePairs.put("title", "Enter a number between 1 and 4 inclusive."); }
The reservation
example application provides a set of HTML5 input
elements of various types to simulate purchasing tickets for a theatrical event. It consists of two Facelets pages, reservation.xhtml
and confirmation.xhtml
, and a backing bean, ReservationBean.java
. The pages use both pass-through attributes and pass-through elements.
The source code for this application is in the tut-install/examples/web/jsf/reservation/
directory.
The first important feature of the Facelets pages for the reservation
application is the DOCTYPE
header. Most Facelets pages in JavaServer Faces applications refer to the XHTML DTD. The facelets pages for this application begin simply with the following DOCTYPE
header, which indicates an HTML5 page:
<!DOCTYPE html>
The namespace declarations in the html
element of the reservation.xhtml
page specify both the jsf
and the passthrough
namespaces:

Next, an empty h:head
tag followed by an h:outputStylesheet
tag within the h:body
tag illustrates the use of a relocatable resource (as described in Relocatable Resources):
<h:head> </h:head> <h:body> <h:outputStylesheet name="css/stylesheet.css" target="head"/>
The reservation.xhtml
page uses pass-through elements for most of the form fields on the page. This allows it to use some HTML5-specific input
element types, such as date
and email
. For example, the following element renders both a date format and a calendar from which you can choose a date. The jsf
prefix on the id
attribute makes the element a pass-through one:
<input type="date" jsf:id="date" name="date" value="#{reservationBean.date}" required="required" title="Enter or choose a date."/>
The field for the number of tickets, however, uses the h:passThroughAttributes
tag to pass a Map
defined in the managed bean. It also recalculates the total in response to a change in the field:
<h:inputText id="tickets" value="#{reservationBean.tickets}"> <f:passThroughAttributes value="#{reservationBean.ticketAttrs}"/> <f:ajax event="change" render="total" listener="#{reservationBean.calculateTotal}"/> </h:inputText>
The field for the price specifies the number
type as a pass-through attribute of the h:inputText
element, offering a range of four ticket prices. Here, the p
prefix on the HTML5 attributes passes them through to the browser uninterpreted by the JavaServer Faces input component:
<h:inputText id="price" p:type="number" value="#{reservationBean.price}" p:min="80" p:max="120" p:step="20" p:required="required" p:title="Enter a price: 80, 100, 120, or 140."> <f:ajax event="change" render="total" listener="#{reservationBean.calculateTotal}"/> </h:inputText>
The output of the calculateTotal
method that is specified as the listener for the Ajax event is rendered in the output element whose id
and name
value is total
. See Chapter 13, "Using Ajax with JavaServer Faces Technology", for more information.
The second Facelets page, confirmation.xhtml
, uses a pass-through output
element to display the values entered by the user and provides a Facelets h:commandButton
tag to allow the user to return to the reservation.xhtml
page.
The session-scoped managed bean for the reservation application, ReservationBean.java
, contains properties for all the elements on the Facelets pages. It also contains two methods, calculateTotal
and clear
, that act as listeners for Ajax events on the reservation.xhtml
page.
Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server).
From the File menu, choose Open Project.
In the Open Project dialog box, navigate to:
tut-install/examples/web/jsf
Select the reservation
folder.
Click Open Project.
In the Projects tab, right-click the reservation
project and select Build.
This option builds the example application and deploys it to your GlassFish Server instance.
Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server).
In a terminal window, go to:
tut-install/examples/web/jsf/reservation/
Enter the following command:
mvn install
This command builds and packages the application into a WAR file, reservation.war
, that is located in the target
directory. It then deploys the WAR file to your GlassFish Server instance.
At the time of the publication of this tutorial, the browser that most fully implements HTML5 is Google Chrome, and it is recommended that you use it to run this example. Other browsers are catching up, however, and may work equally well by the time you read this.
Enter the following URL in your web browser:
http://localhost:8080/reservation
Enter information in the fields of the reservation.xhtml
page.
The Performance Date field has a date field with up and down arrows that allow you to increment and decrement the month, day, and year as well as a larger down arrow that brings up a date editor in calendar form.
The Number of Tickets and Ticket Price fields also have up and down arrows that allow you to increment and decrement the values within the allowed range and steps. The Estimated Total changes when you change either of these two fields.
Email addresses and dates are checked for format, but not for validity (you can make a reservation for a past date, for instance).
Click Make Reservation to complete the reservation or Clear to restore the fields to their default values.
If you click Make Reservation, the confirmation.xhtml
page appears, displaying the submitted values.
Click Back to return to the reservation.xhtml
page.


Nuclei Segmentation - Deep Learning Demo
<EMAIL_ADDRESS>Pick an image
{%for item in img_list %}
{%endfor%}
Analyze


Welcome to a unique competition hosted by @Liftoff. In this competition only HTML entries are allowed. The competition will try to use API's to create a very automated experience.
Only people joining before DD.MM.YYYY will be accepted by the API and you will be automatically sorted into a team based on the availability of seats.
Teams
Judges
What is the difference with other competitions ?
In this competition there will initially be no teams.....
I will choose some capable captains.
Then you can join any captain's team if a slot is available
There is also automatic verification based on date. Basically if you join after the last date, your joining won't count.


va·ness·a
coffee addict · chocolate enthusiast · pug lover · math geek
My goal is to travel and explore 23 different countries - one for each year I have lived. (Of course, the list will expand as I grow older every year!). This will be a platform for me to create an album of my adventures as a means to track my journey, beginning with my hometown: Vancouver, British Columbia, Canada.


Principle has the rights to view all the records that is maintained by the users and more.
He can view number of students being admitted through the forum. He can also view all the staff members that are logged in.
Contact:
+91 8251 233 635 (Principal’s Office)
+91 8251 233 0455 (Admn. Office)
+91 9448 624 951 (Cell)
08251 232 591 (Res)
Office staff who controls the students records and maintains it.Every records are being maintained by the office staffs.New updates are notified to the students. Students internal marks are uploaded here and all the staff admission is done here.
Student forum includes Online admission and online facility to upload details,it consists online fees payment for different courses.
Students can also view thier semester wise marks and thier progress,they can view thier own profile and send queries to staff members.
Faculty views the progress of students records and sends notifications related to exams.
Notifications to send mssages to principal and students about events and exam details. they can also view thier own profile and view each students details.
Library is vast and spacious to read your desired books and large amount of collection to choose from with a comfortable seating arrangement.


Valorant is a 5v5 character-based tactical shooter. With gunplay and special abilities, 13 rounds are needed to secure the victory through both attack and defense. Every player has one-life per round and they must be creative in order to get an upperhand on their opponents. Different agents have different skill sets which must be utilized properly to gain the most value out of them. Guns and abilities are purchased at the beginning of every round with the credits earned from each round win or loss. With different games modes to play on, players can select whether they want to earn ranks based on their performance in Competitive or play a casual game of Unranked or Spike Rush. Gunplay can be practiced in Deathmatch and all these modes are played in a pool of 6 maps.
| COMPONENTS | MINIMUM / 30 FPS | RECOMMENDED / 60 FPS | HIGH-END / 144+ FPS |
|---|---|---|---|
| OS | Windows 7/8/10 64-bit | Windows 7/8/10 64-bit | Windows 7/8/10 64-bit |
| CPU | Intel Core 2 Duo | Intel Core i3-4150 | Intel Core i5-4460 3.2 Ghz |
| GPU | Intel HD 4000 | Geforce GT 730 | GTX 1050Ti |
| RAM | 4GB | 4GB | 4GB |
| VRAM | 1GB | 1GB | 1GB |


--- layout: page title: About header-img: "img/about-bg.png" ---
I am a part time worker at subway and wish to do bigger things.


cloudmesh-common.cloudmesh.common.FlatDict
¶
Module Contents¶
Classes¶
A data structure to manage a flattened dict. It is initialized by passing |
|
Functions¶
|
replaces the list of prefix in keys of a flattened dict |
|
|
|
flattens the dict into a one dimensional dictionary |
-
cloudmesh-common.cloudmesh.common.FlatDict.
collectionsAbc
¶
-
cloudmesh-common.cloudmesh.common.FlatDict.
key_prefix_replace
(d, prefix, new_prefix='')¶ replaces the list of prefix in keys of a flattened dict
- Parameters
d – the flattened dict
prefix (list of str) – a list of prefixes that are replaced with a new prefix. Typically this will be “”
new_prefix – The new prefix. By default it is set to “”
- Returns
the dict with the keys replaced as specified
-
cloudmesh-common.cloudmesh.common.FlatDict.
flatme
(d)¶
-
cloudmesh-common.cloudmesh.common.FlatDict.
flatten
(d, parent_key='', sep='__')¶ flattens the dict into a one dimensional dictionary
- Parameters
d – multidimensional dict
parent_key – replaces from the parent key
sep – the separation character used when fattening. the default is __
- Returns
the flattened dict
-
class
cloudmesh-common.cloudmesh.common.FlatDict.
FlatDict
(d, sep='__')¶ Bases:
dict
A data structure to manage a flattened dict. It is initialized by passing the dict at time of initialization.
-
property
dict
(self)¶ returns the dict :return: dict
-
__setitem__
(self, key, item)¶ sets an item at a key
- Parameters
key – this is the key
item – this is the item to be set
-
__getitem__
(self, key)¶ gets an item form the key
- Parameters
key – the key
- Returns
the value
-
__repr__
(self)¶ Return repr(self).
-
__str__
(self)¶ The string representation of the dict
- Returns
str
-
__len__
(self)¶ number of elements in the dict
- Returns
int
-
__delitem__
(self, key)¶ delete the specified item
- Parameters
key – key of the item
- Returns
dict with the elementremoved
-
keys
(self)¶ returns the keys
- Returns
list of keys
-
values
(self)¶ list of all values
- Returns
list
-
__cmp__
(self, dictionary)¶
-
__contains__
(self, item)¶ True if the dictionary has the specified key, else False.
-
add
(self, key, value)¶
-
__iter__
(self)¶ Implement iter(self).
-
__call__
(self)¶
-
__getattr__
(self, attr)¶
-
search
(self, key, value=None)¶ returns from a flatdict all keys that match the given pattern and have the given value. If the value None is specified or ommitted, all keys are returned regardless of value.
Example:
search(“cloudmesh.cloud.*.cm.active”, True)
- Parameters
key – The key pattern to be searched (given as regex)
value – The value
- Returns
keys matching the vakue in flat dict format.
-
property
-
class
cloudmesh-common.cloudmesh.common.FlatDict.
FlatDict2
¶ Bases:
object
-
classmethod
is_primitive
(cls, thing)¶
-
classmethod
convert
(cls, obj, flatten=True)¶ This function converts object into a Dict optionally Flattening it :param obj: Object to be converted :param flatten: boolean to specify if the dict has to be flattened :return dict: the dict of the object (Flattened or Un-flattened)
-
classmethod
object_to_dict
(cls, obj)¶ This function converts Objects into Dictionary
-
classmethod


"""setuptools.command.egg_info Create a distribution's .egg-info directory and contents""" from distutils.filelist import FileList as _FileList from distutils.errors import DistutilsInternalError from distutils.util import convert_path from distutils import log import distutils.errors import distutils.filelist import os import re import sys import io import warnings import time import collections from setuptools.extern import six from setuptools.extern.six.moves import map from setuptools import Command from setuptools.command.sdist import sdist from setuptools.command.sdist import walk_revctrl from setuptools.command.setopt import edit_config from setuptools.command import bdist_egg from pkg_resources import ( parse_requirements, safe_name, parse_version, safe_version, yield_lines, EntryPoint, iter_entry_points, to_filename) import setuptools.unicode_utils as unicode_utils from setuptools.glob import glob from setuptools.extern import packaging from setuptools import SetuptoolsDeprecationWarning def translate_pattern(glob): """ Translate a file path glob like '*.txt' in to a regular expression. This differs from fnmatch.translate which allows wildcards to match directory separators. It also knows about '**/' which matches any number of directories. """ pat = '' # This will split on '/' within [character classes]. This is deliberate. chunks = glob.split(os.path.sep) sep = re.escape(os.sep) valid_char = '[^%s]' % (sep,) for c, chunk in enumerate(chunks): last_chunk = c == len(chunks) - 1 # Chunks that are a literal ** are globstars. They match anything. if chunk == '**': if last_chunk: # Match anything if this is the last component pat += '.*' else: # Match '(name/)*' pat += '(?:%s+%s)*' % (valid_char, sep) continue # Break here as the whole path component has been handled # Find any special characters in the remainder i = 0 chunk_len = len(chunk) while i < chunk_len: char = chunk[i] if char == '*': # Match any number of name characters pat += valid_char + '*' elif char == '?': # Match a name character pat += valid_char elif char == '[': # Character class inner_i = i + 1 # Skip initial !/] chars if inner_i < chunk_len and chunk[inner_i] == '!': inner_i = inner_i + 1 if inner_i < chunk_len and chunk[inner_i] == ']': inner_i = inner_i + 1 # Loop till the closing ] is found while inner_i < chunk_len and chunk[inner_i] != ']': inner_i = inner_i + 1 if inner_i >= chunk_len: # Got to the end of the string without finding a closing ] # Do not treat this as a matching group, but as a literal [ pat += re.escape(char) else: # Grab the insides of the [brackets] inner = chunk[i + 1:inner_i] char_class = '' # Class negation if inner[0] == '!': char_class = '^' inner = inner[1:] char_class += re.escape(inner) pat += '[%s]' % (char_class,) # Skip to the end ] i = inner_i else: pat += re.escape(char) i += 1 # Join each chunk with the dir separator if not last_chunk: pat += sep pat += r'\Z' return re.compile(pat, flags=re.MULTILINE | re.DOTALL) class InfoCommon: tag_build = None tag_date = None @property def name(self): return safe_name(self.distribution.get_name()) def tagged_version(self): version = self.distribution.get_version() # egg_info may be called more than once for a distribution, # in which case the version string already contains all tags. if self.vtags and version.endswith(self.vtags): return safe_version(version) return safe_version(version + self.vtags) def tags(self): version = '' if self.tag_build: version += self.tag_build if self.tag_date: version += time.strftime("-%Y%m%d") return version vtags = property(tags) class egg_info(InfoCommon, Command): description = "create a distribution's .egg-info directory" user_options = [ ('egg-base=', 'e', "directory containing .egg-info directories" " (default: top of the source tree)"), ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"), ('tag-build=', 'b', "Specify explicit tag to add to version number"), ('no-date', 'D', "Don't include date stamp [default]"), ] boolean_options = ['tag-date'] negative_opt = { 'no-date': 'tag-date', } def initialize_options(self): self.egg_base = None self.egg_name = None self.egg_info = None self.egg_version = None self.broken_egg_info = False #################################### # allow the 'tag_svn_revision' to be detected and # set, supporting sdists built on older Setuptools. @property def tag_svn_revision(self): pass @tag_svn_revision.setter def tag_svn_revision(self, value): pass #################################### def save_version_info(self, filename): """ Materialize the value of date into the build tag. Install build keys in a deterministic order to avoid arbitrary reordering on subsequent builds. """ egg_info = collections.OrderedDict() # follow the order these keys would have been added # when PYTHONHASHSEED=0 egg_info['tag_build'] = self.tags() egg_info['tag_date'] = 0 edit_config(filename, dict(egg_info=egg_info)) def finalize_options(self): # Note: we need to capture the current value returned # by `self.tagged_version()`, so we can later update # `self.distribution.metadata.version` without # repercussions. self.egg_name = self.name self.egg_version = self.tagged_version() parsed_version = parse_version(self.egg_version) try: is_version = isinstance(parsed_version, packaging.version.Version) spec = ( "%s==%s" if is_version else "%s===%s" ) list( parse_requirements(spec % (self.egg_name, self.egg_version)) ) except ValueError: raise distutils.errors.DistutilsOptionError( "Invalid distribution name or version syntax: %s-%s" % (self.egg_name, self.egg_version) ) if self.egg_base is None: dirs = self.distribution.package_dir self.egg_base = (dirs or {}).get('', os.curdir) self.ensure_dirname('egg_base') self.egg_info = to_filename(self.egg_name) + '.egg-info' if self.egg_base != os.curdir: self.egg_info = os.path.join(self.egg_base, self.egg_info) if '-' in self.egg_name: self.check_broken_egg_info() # Set package version for the benefit of dumber commands # (e.g. sdist, bdist_wininst, etc.) # self.distribution.metadata.version = self.egg_version # If we bootstrapped around the lack of a PKG-INFO, as might be the # case in a fresh checkout, make sure that any special tags get added # to the version info # pd = self.distribution._patched_dist if pd is not None and pd.key == self.egg_name.lower(): pd._version = self.egg_version pd._parsed_version = parse_version(self.egg_version) self.distribution._patched_dist = None def write_or_delete_file(self, what, filename, data, force=False): """Write `data` to `filename` or delete if empty If `data` is non-empty, this routine is the same as ``write_file()``. If `data` is empty but not ``None``, this is the same as calling ``delete_file(filename)`. If `data` is ``None``, then this is a no-op unless `filename` exists, in which case a warning is issued about the orphaned file (if `force` is false), or deleted (if `force` is true). """ if data: self.write_file(what, filename, data) elif os.path.exists(filename): if data is None and not force: log.warn( "%s not set in setup(), but %s exists", what, filename ) return else: self.delete_file(filename) def write_file(self, what, filename, data): """Write `data` to `filename` (if not a dry run) after announcing it `what` is used in a log message to identify what is being written to the file. """ log.info("writing %s to %s", what, filename) if not six.PY2: data = data.encode("utf-8") if not self.dry_run: f = open(filename, 'wb') f.write(data) f.close() def delete_file(self, filename): """Delete `filename` (if not a dry run) after announcing it""" log.info("deleting %s", filename) if not self.dry_run: os.unlink(filename) def run(self): self.mkpath(self.egg_info) os.utime(self.egg_info, None) installer = self.distribution.fetch_build_egg for ep in iter_entry_points('egg_info.writers'): ep.require(installer=installer) writer = ep.resolve() writer(self, ep.name, os.path.join(self.egg_info, ep.name)) # Get rid of native_libs.txt if it was put there by older bdist_egg nl = os.path.join(self.egg_info, "native_libs.txt") if os.path.exists(nl): self.delete_file(nl) self.find_sources() def find_sources(self): """Generate SOURCES.txt manifest file""" manifest_filename = os.path.join(self.egg_info, "SOURCES.txt") mm = manifest_maker(self.distribution) mm.manifest = manifest_filename mm.run() self.filelist = mm.filelist def check_broken_egg_info(self): bei = self.egg_name + '.egg-info' if self.egg_base != os.curdir: bei = os.path.join(self.egg_base, bei) if os.path.exists(bei): log.warn( "-" * 78 + '\n' "Note: Your current .egg-info directory has a '-' in its name;" '\nthis will not work correctly with "setup.py develop".\n\n' 'Please rename %s to %s to correct this problem.\n' + '-' * 78, bei, self.egg_info ) self.broken_egg_info = self.egg_info self.egg_info = bei # make it work for now class FileList(_FileList): # Implementations of the various MANIFEST.in commands def process_template_line(self, line): # Parse the line: split it up, make sure the right number of words # is there, and return the relevant words. 'action' is always # defined: it's the first word of the line. Which of the other # three are defined depends on the action; it'll be either # patterns, (dir and patterns), or (dir_pattern). (action, patterns, dir, dir_pattern) = self._parse_template_line(line) # OK, now we know that the action is valid and we have the # right number of words on the line for that action -- so we # can proceed with minimal error-checking. if action == 'include': self.debug_print("include " + ' '.join(patterns)) for pattern in patterns: if not self.include(pattern): log.warn("warning: no files found matching '%s'", pattern) elif action == 'exclude': self.debug_print("exclude " + ' '.join(patterns)) for pattern in patterns: if not self.exclude(pattern): log.warn(("warning: no previously-included files " "found matching '%s'"), pattern) elif action == 'global-include': self.debug_print("global-include " + ' '.join(patterns)) for pattern in patterns: if not self.global_include(pattern): log.warn(("warning: no files found matching '%s' " "anywhere in distribution"), pattern) elif action == 'global-exclude': self.debug_print("global-exclude " + ' '.join(patterns)) for pattern in patterns: if not self.global_exclude(pattern): log.warn(("warning: no previously-included files matching " "'%s' found anywhere in distribution"), pattern) elif action == 'recursive-include': self.debug_print("recursive-include %s %s" % (dir, ' '.join(patterns))) for pattern in patterns: if not self.recursive_include(dir, pattern): log.warn(("warning: no files found matching '%s' " "under directory '%s'"), pattern, dir) elif action == 'recursive-exclude': self.debug_print("recursive-exclude %s %s" % (dir, ' '.join(patterns))) for pattern in patterns: if not self.recursive_exclude(dir, pattern): log.warn(("warning: no previously-included files matching " "'%s' found under directory '%s'"), pattern, dir) elif action == 'graft': self.debug_print("graft " + dir_pattern) if not self.graft(dir_pattern): log.warn("warning: no directories found matching '%s'", dir_pattern) elif action == 'prune': self.debug_print("prune " + dir_pattern) if not self.prune(dir_pattern): log.warn(("no previously-included directories found " "matching '%s'"), dir_pattern) else: raise DistutilsInternalError( "this cannot happen: invalid action '%s'" % action) def _remove_files(self, predicate): """ Remove all files from the file list that match the predicate. Return True if any matching files were removed """ found = False for i in range(len(self.files) - 1, -1, -1): if predicate(self.files[i]): self.debug_print(" removing " + self.files[i]) del self.files[i] found = True return found def include(self, pattern): """Include files that match 'pattern'.""" found = [f for f in glob(pattern) if not os.path.isdir(f)] self.extend(found) return bool(found) def exclude(self, pattern): """Exclude files that match 'pattern'.""" match = translate_pattern(pattern) return self._remove_files(match.match) def recursive_include(self, dir, pattern): """ Include all files anywhere in 'dir/' that match the pattern. """ full_pattern = os.path.join(dir, '**', pattern) found = [f for f in glob(full_pattern, recursive=True) if not os.path.isdir(f)] self.extend(found) return bool(found) def recursive_exclude(self, dir, pattern): """ Exclude any file anywhere in 'dir/' that match the pattern. """ match = translate_pattern(os.path.join(dir, '**', pattern)) return self._remove_files(match.match) def graft(self, dir): """Include all files from 'dir/'.""" found = [ item for match_dir in glob(dir) for item in distutils.filelist.findall(match_dir) ] self.extend(found) return bool(found) def prune(self, dir): """Filter out files from 'dir/'.""" match = translate_pattern(os.path.join(dir, '**')) return self._remove_files(match.match) def global_include(self, pattern): """ Include all files anywhere in the current directory that match the pattern. This is very inefficient on large file trees. """ if self.allfiles is None: self.findall() match = translate_pattern(os.path.join('**', pattern)) found = [f for f in self.allfiles if match.match(f)] self.extend(found) return bool(found) def global_exclude(self, pattern): """ Exclude all files anywhere that match the pattern. """ match = translate_pattern(os.path.join('**', pattern)) return self._remove_files(match.match) def append(self, item): if item.endswith('\r'): # Fix older sdists built on Windows item = item[:-1] path = convert_path(item) if self._safe_path(path): self.files.append(path) def extend(self, paths): self.files.extend(filter(self._safe_path, paths)) def _repair(self): """ Replace self.files with only safe paths Because some owners of FileList manipulate the underlying ``files`` attribute directly, this method must be called to repair those paths. """ self.files = list(filter(self._safe_path, self.files)) def _safe_path(self, path): enc_warn = "'%s' not %s encodable -- skipping" # To avoid accidental trans-codings errors, first to unicode u_path = unicode_utils.filesys_decode(path) if u_path is None: log.warn("'%s' in unexpected encoding -- skipping" % path) return False # Must ensure utf-8 encodability utf8_path = unicode_utils.try_encode(u_path, "utf-8") if utf8_path is None: log.warn(enc_warn, path, 'utf-8') return False try: # accept is either way checks out if os.path.exists(u_path) or os.path.exists(utf8_path): return True # this will catch any encode errors decoding u_path except UnicodeEncodeError: log.warn(enc_warn, path, sys.getfilesystemencoding()) class manifest_maker(sdist): template = "MANIFEST.in" def initialize_options(self): self.use_defaults = 1 self.prune = 1 self.manifest_only = 1 self.force_manifest = 1 def finalize_options(self): pass def run(self): self.filelist = FileList() if not os.path.exists(self.manifest): self.write_manifest() # it must exist so it'll get in the list self.add_defaults() if os.path.exists(self.template): self.read_template() self.prune_file_list() self.filelist.sort() self.filelist.remove_duplicates() self.write_manifest() def _manifest_normalize(self, path): path = unicode_utils.filesys_decode(path) return path.replace(os.sep, '/') def write_manifest(self): """ Write the file list in 'self.filelist' to the manifest file named by 'self.manifest'. """ self.filelist._repair() # Now _repairs should encodability, but not unicode files = [self._manifest_normalize(f) for f in self.filelist.files] msg = "writing manifest file '%s'" % self.manifest self.execute(write_file, (self.manifest, files), msg) def warn(self, msg): if not self._should_suppress_warning(msg): sdist.warn(self, msg) @staticmethod def _should_suppress_warning(msg): """ suppress missing-file warnings from sdist """ return re.match(r"standard file .*not found", msg) def add_defaults(self): sdist.add_defaults(self) self.check_license() self.filelist.append(self.template) self.filelist.append(self.manifest) rcfiles = list(walk_revctrl()) if rcfiles: self.filelist.extend(rcfiles) elif os.path.exists(self.manifest): self.read_manifest() if os.path.exists("setup.py"): # setup.py should be included by default, even if it's not # the script called to create the sdist self.filelist.append("setup.py") ei_cmd = self.get_finalized_command('egg_info') self.filelist.graft(ei_cmd.egg_info) def prune_file_list(self): build = self.get_finalized_command('build') base_dir = self.distribution.get_fullname() self.filelist.prune(build.build_base) self.filelist.prune(base_dir) sep = re.escape(os.sep) self.filelist.exclude_pattern(r'(^|' + sep + r')(RCS|CVS|\.svn)' + sep, is_regex=1) def write_file(filename, contents): """Create a file with the specified name and write 'contents' (a sequence of strings without line terminators) to it. """ contents = "\n".join(contents) # assuming the contents has been vetted for utf-8 encoding contents = contents.encode("utf-8") with open(filename, "wb") as f: # always write POSIX-style manifest f.write(contents) def write_pkg_info(cmd, basename, filename): log.info("writing %s", filename) if not cmd.dry_run: metadata = cmd.distribution.metadata metadata.version, oldver = cmd.egg_version, metadata.version metadata.name, oldname = cmd.egg_name, metadata.name try: # write unescaped data to PKG-INFO, so older pkg_resources # can still parse it metadata.write_pkg_info(cmd.egg_info) finally: metadata.name, metadata.version = oldname, oldver safe = getattr(cmd.distribution, 'zip_safe', None) bdist_egg.write_safety_flag(cmd.egg_info, safe) def warn_depends_obsolete(cmd, basename, filename): if os.path.exists(filename): log.warn( "WARNING: 'depends.txt' is not used by setuptools 0.6!\n" "Use the install_requires/extras_require setup() args instead." ) def _write_requirements(stream, reqs): lines = yield_lines(reqs or ()) def append_cr(line): return line + '\n' lines = map(append_cr, lines) stream.writelines(lines) def write_requirements(cmd, basename, filename): dist = cmd.distribution data = six.StringIO() _write_requirements(data, dist.install_requires) extras_require = dist.extras_require or {} for extra in sorted(extras_require): data.write('\n[{extra}]\n'.format(**vars())) _write_requirements(data, extras_require[extra]) cmd.write_or_delete_file("requirements", filename, data.getvalue()) def write_setup_requirements(cmd, basename, filename): data = io.StringIO() _write_requirements(data, cmd.distribution.setup_requires) cmd.write_or_delete_file("setup-requirements", filename, data.getvalue()) def write_toplevel_names(cmd, basename, filename): pkgs = dict.fromkeys( [ k.split('.', 1)[0] for k in cmd.distribution.iter_distribution_names() ] ) cmd.write_file("top-level names", filename, '\n'.join(sorted(pkgs)) + '\n') def overwrite_arg(cmd, basename, filename): write_arg(cmd, basename, filename, True) def write_arg(cmd, basename, filename, force=False): argname = os.path.splitext(basename)[0] value = getattr(cmd.distribution, argname, None) if value is not None: value = '\n'.join(value) + '\n' cmd.write_or_delete_file(argname, filename, value, force) def write_entries(cmd, basename, filename): ep = cmd.distribution.entry_points if isinstance(ep, six.string_types) or ep is None: data = ep elif ep is not None: data = [] for section, contents in sorted(ep.items()): if not isinstance(contents, six.string_types): contents = EntryPoint.parse_group(section, contents) contents = '\n'.join(sorted(map(str, contents.values()))) data.append('[%s]\n%s\n\n' % (section, contents)) data = ''.join(data) cmd.write_or_delete_file('entry points', filename, data, True) def get_pkg_info_revision(): """ Get a -r### off of PKG-INFO Version in case this is an sdist of a subversion revision. """ warnings.warn( "get_pkg_info_revision is deprecated.", EggInfoDeprecationWarning) if os.path.exists('PKG-INFO'): with io.open('PKG-INFO') as f: for line in f: match = re.match(r"Version:.*-r(\d+)\s*$", line) if match: return int(match.group(1)) return 0 class EggInfoDeprecationWarning(SetuptoolsDeprecationWarning): """Deprecated behavior warning for EggInfo, bypassing suppression."""


ecomplus-client
JS client for E-Com Plus REST APIs
Usage
TL;DR: We have methods to run requests for almost all E-Com Plus APIs, but you're probably searching for Store API.
The @ecomplus/client
package provides a
list of methods,
each one is a function to request a specific E-Com Plus REST API,
using axios HTTP client
and returning a
Promise.
It's available for both Node.js and browser environments.
Dependencies
It requires and doesn't include
axios
and
@ecomplus/utils
.
It'll be automatically imported if you're developing on Node.js environment or using a bundler such as Webpack, in other case those libraries must be included manually on window scope.
Development
We're using Conventional Commits, all commit messages must follow these conventions.
For documentation, we're using jsdoc, all methods should be well documented.
Contributing
-
Fork the repository;
-
Create a new branch with the name of your proposal;
-
Clone the repository:
git clone git@github.com:{user}/ecomplus-client.git
- Move to folder and install dependencies:
cd ecomplus-client
npm i
- Run dev server and use global
ecomClient
or edittest/demo.js
for tests on http://localhost:9245/:
npm run serve
-
Commit changes following Conventional Commits;
-
Create a new PR describing your proposal :)
Deploy
Take a look on package.json
scripts:
npm run doc
- Update jsdoc/docdash generated documentation;npm run release
- Generate changelog and new version;


{% extends 'admin_base.html' %} {% block title %}Make:good - Admin!{% endblock %} {% block content %}
Cath: You can add a new Page, or delete/edit existing Pages. A Page is of a defined type (e.g. Portfolio or Gallery or WYSIWYG). You cannot create new types. A Page also belongs to a Category and will be displayed under that Category on the homepage. If you delete a Category then the Page will still exist, but will not be linked to on the homepage.


About Access Spring'97
Schedule at a Glance
Hotel & Travel Information
ACT NOW TO RESERVE YOUR SPACE:
CALL 1-800-325-3034
The first 400 registered attendees will receive an entry to win one of these exciting products:
Compaq Professional Workstation 5000
Compaq PC companion
Compaq Armada Notebook
Valuable Partner SoftwareSponsored by:
| |||||||||||||
|
Revised: 20 May 1997 |


Welcome to the HexEdit Keystroke Macro Tutorial.
What are Keystroke Macros?
Keystroke macros allow you to automate repetitive tasks. You "record" a series of keystrokes so that they can be later "played back" as many times as you like.
When combined with other powerful features such as the calculator you can quickly perform complex tasks that might take hours or days to write a specialised program to perform. Moreover, you can save them to macro files so that you can use them again later or give them to colleagues who have the same need.
Who Should Use this Tutorial?
This tutorial is for anyone who wants to get more out of using HexEdit.
For more complex tasks it can be quicker and easier to create a HexEdit macro to do the job than to write a special program to do it. Though sometimes it takes a bit of trial and error to get keystroke macros just right.
Many users ask us to add special features HexEdit, for a specific problem they have. They are often surprised when they find that what they require can be done simply with a keystroke macro.
It should take less than 40 minutes to complete the tutorial.
Before You Start...
It is assumed that you are reasonably familiar with HexEdit and tools such as the calculator. You do not need to know how to create keystroke macros.
What You will Learn
In this tutorial you will learn how to record and run a macro. You will also learn how to save a macro to a disk file and run such a macro. Some of the macro commands we use include creating a new file, performing operations using data from multiple files and displaying informational messages to the user.
There are also more advanced techniques like creating a loop using a nested macro. And we will use the calculator to manipulate file data and move the cursor (current insert position) in the active file.
There are five steps:
2. Creating a macro to XOR bytes
At the top and bottom of each step there is a "Next" button, which allows you to move to the next step (and a "Previous" button to allow you to go backwards).
Each step consists of explanatory text (in black) as well as numbered instructions (in blue) like this:
1. Click the button below to start the tutorial now.


This provides a brief introduction to the concepts behind UrhoSharp
UrhoSharp is a powerful 3D Game Engine for Xamarin and .NET developers. It is similar in spirit to Apple’s SceneKit and SpriteKit and include physics, navigation, networking and much more while still being cross platform.
It is a .NET binding to the Urho3D engine and allows developers to write cross platform code that can target Android, iOS, Windows and Mac with the same codebase and can render to both OpenGL and Direct3D systems.
UrhoSharp is a game engine with a lot of functionality out of the box:
UrhoSharp is conveniently distributed as a NuGet package and it can be added to your C# or F# projects that target Windows, Mac, Android or iOS. The NuGet comes with both the libraries required to run your program, as well as the basic assets (CoreData) used by the engine.
The Urho package can be consumed either from a platform-specific project, or from a Portable Class Library project, allowing you to reuse all of your code across all platforms. This means that all you would have to do on each platform is to write your platform specific entry point, and then transfer control to your shared game code.
You can get a taste for the capabilities of Urho by opening in either Xamarin Studio or Visual Studio the Sample solution from:
https://github.com/xamarin/urho-samples
The default solution contains projects for Android, iOS, Windows and Mac. We have structured that solution so that we have a tiny platform specific launcher, and all of the sample code and game code lives in a portable class library, illustrating how to maximize code reuse across all platforms.
Consult the Urho and Your Platform page for more information on how to create your own solutions.
Since all of the samples share a common set of user interface elements, the samples have abstracted the basic setup in this file:
https://github.com/xamarin/urho-samples/blob/master/FeatureSamples/Core/Sample.cs
This provides a Sample base class that handles some basic keystrokes and touch events, setups a camera, provides basic user interface elements, and this allows each sample to focus on the specific functionality that is being showcased.
The following sample shows what the engine is capable of doing:
Samply Game a simple clone of ShootySkies.
While the other samples show individual properties of each sample.
Your game should subclass the
Application
class, this is where you will setup your game (on the Setup
method)
and start your game (in the Start
method). Then you construct your
main user interface. We are going to walk through a small sample that
shows the APIs to setup a 3D scene, some UI elements and attaching a
simple behavior to it.
class MySample : Application {
protected override void Start ()
{
CreateScene ();
Input.KeyDown += (args) => {
if (args.Key == Key.Esc) Engine.Exit ();
};
}
async void CreateScene()
{
// UI text
var helloText = new Text()
{
Value = "Hello World from MySample",
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
helloText.SetColor(new Color(0f, 1f, 1f));
helloText.SetFont(
font: ResourceCache.GetFont("Fonts/Font.ttf"),
size: 30);
UI.Root.AddChild(helloText);
// Create a top-level scene, must add the Octree
// to visualize any 3D content.
var scene = new Scene();
scene.CreateComponent<Octree>();
// Box
Node boxNode = scene.CreateChild();
boxNode.Position = new Vector3(0, 0, 5);
boxNode.Rotation = new Quaternion(60, 0, 30);
boxNode.SetScale(0f);
StaticModel modelObject = boxNode.CreateComponent<StaticModel>();
modelObject.Model = ResourceCache.GetModel("Models/Box.mdl");
// Light
Node lightNode = scene.CreateChild(name: "light");
lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
lightNode.CreateComponent<Light>();
// Camera
Node cameraNode = scene.CreateChild(name: "camera");
Camera camera = cameraNode.CreateComponent<Camera>();
// Viewport
Renderer.SetViewport(0, new Viewport(scene, camera, null));
// Perform some actions
await boxNode.RunActionsAsync(
new EaseBounceOut(new ScaleTo(duration: 1f, scale: 1)));
await boxNode.RunActionsAsync(
new RepeatForever(new RotateBy(duration: 1,
deltaAngleX: 90, deltaAngleY: 0, deltaAngleZ: 0)));
}
}
If you run this application, you will quickly discover that the runtime is complaining about your assets are not there. What you need to do is create a hierarchy in your project that starts with the special directory name "Data", and inside this, you would place the assets that you reference in your program. You must then set in the item properties for each asset the "Copy to Output Directory” to "Copy if Newer”, that will ensure that your data is there.
Let us explain what is going on here.
To launch your application you call the engine initialization function, followed by creating a new instance of your Application class, like this:
new MySample().Run();
The runtime will invoke the Setup
and Start
methods for you. If you
override Setup
you can configure the engine parameters (not show in
this sample).
You must override Start
as this will launch your game. In this method
you will load your assets, connect event handlers, setup your scene
and start any actions that you desire. In our sample, we both create
a little bit of UI to show to the user as well as setting up a 3D
scene.
The following piece of code uses the UI framework to create a text element and add it to your application:
// UI text
var helloText = new Text()
{
Value = "Hello World from UrhoSharp",
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
helloText.SetColor(new Color(0f, 1f, 1f));
helloText.SetFont(
font: ResourceCache.GetFont("Fonts/Font.ttf"),
size: 30);
UI.Root.AddChild(helloText);
The UI framework is there to provide a very simple in-game user
interface, and it works by adding new nodes to the UI.Root
node.
The second part of our sample setups the main scene. This involves a number of steps, creating a 3D Scene, creating a 3D box in the screen, adding a light, a camera and a viewport. These are explored in more detail in the section "Scene, Nodes, Components and Cameras"
The third part of our sample triggers a couple of actions. Actions
are recipes that describe a particular effect, and once created they
can be executed by a node on demand by calling the RunActionAsync
method on a Node
.
The first action scales the box with a bouncing effect and the second one rotates the box forever:
await boxNode.RunActionsAsync(
new EaseBounceOut(new ScaleTo(duration: 1f, scale: 1)));
The above shows how the first action that we create is a ScaleTo
action, this is merely a recipe that indicates that you want to scale
for a second towards the value one the scale property of a node. This
action in turn is wrapped around an easing action, the EaseBounceOut
action. The easing actions distort the linear execution of an action
and apply an effect, in this case it provides the bouncing-out effect.
So our recipe could be written as:
var recipe = new EaseBounceOut(new ScaleTo(duration: 1f, scale: 1));
Once the recipe has been created, we execute the recipe:
await boxNode.RunActionsAsync (recipe)
The await indicates that the will want to resume execution after this line when the action completes. Once the action completes we trigger the second animation.
The Using UrhoSharp document explores in more depth the concepts behind Urho and how to structure your code to build a game.
This documentation contains original content from Xamarin Inc, but draws extensively from the open source documentation for the Urho3D project and contains screenshots from the Cocos2D project.