|
JavaTM 2 Platform Standard Ed. 5.0 |
|||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES |
See:
Description
| Interface Summary | |
|---|---|
| Relation | This interface has to be implemented by any MBean class expected to represent a relation managed using the Relation Service. |
| RelationServiceMBean | The Relation Service is in charge of creating and deleting relation types and relations, of handling the consistency and of providing query mechanisms. |
| RelationSupportMBean | A RelationSupport object is used internally by the Relation Service to represent simple relations (only roles, no properties or methods), with an unlimited number of roles, of any relation type. |
| RelationType | The RelationType interface has to be implemented by any class expected to represent a relation type. |
| Class Summary | |
|---|---|
| MBeanServerNotificationFilter | Filter for MBeanServerNotification . |
| RelationNotification | A notification of a change in the Relation Service. |
| RelationService | The Relation Service is in charge of creating and deleting relation types and relations, of handling the consistency and of providing query mechanisms. |
| RelationSupport | A RelationSupport object is used internally by the Relation Service to represent simple relations (only roles, no properties or methods), with an unlimited number of roles, of any relation type. |
| RelationTypeSupport | A RelationTypeSupport object implements the RelationType interface. |
| Role | Represents a role: includes a role name and referenced MBeans (via their ObjectNames). |
| RoleInfo | A RoleInfo object summarises a role in a relation type. |
| RoleList | A RoleList represents a list of roles (Role objects). |
| RoleResult | Represents the result of a multiple access to several roles of a relation (either for reading or writing). |
| RoleStatus | This class describes the various problems which can be encountered when accessing a role. |
| RoleUnresolved | Represents an unresolved role: a role not retrieved from a relation due to a problem. |
| RoleUnresolvedList | A RoleUnresolvedList represents a list of RoleUnresolved objects, representing roles not retrieved from a relation due to a problem encountered when trying to access (read or write to roles). |
| Exception Summary | |
|---|---|
| InvalidRelationIdException | This exception is raised when relation id provided for a relation is already used. |
| InvalidRelationServiceException | This exception is raised when an invalid Relation Service is provided. |
| InvalidRelationTypeException | Invalid relation type. |
| InvalidRoleInfoException | This exception is raised when, in a role info, its minimum degree is greater than its maximum degree. |
| InvalidRoleValueException | Role value is invalid. |
| RelationException | This class is the superclass of any exception which can be raised during relation management. |
| RelationNotFoundException | This exception is raised when there is no relation for a given relation id in a Relation Service. |
| RelationServiceNotRegisteredException | This exception is raised when an access is done to the Relation Service and that one is not registered. |
| RelationTypeNotFoundException | This exception is raised when there is no relation type with given name in Relation Service. |
| RoleInfoNotFoundException | This exception is raised when there is no role info with given name in a given relation type. |
| RoleNotFoundException | This exception is raised when a role in a relation does not exist, or is not readable, or is not settable. |
Provides the definition of the Relation Service. The
Relation Service is used to record relationships between
MBeans in an MBean Server. The Relation Service is itself an
MBean. More than one instance of a RelationService
MBean can be registered in an MBean Server.
A relation type defines a relationship between MBeans. It contains roles that the MBeans play in the relationship. Usually there are at least two roles in a relation type.
A relation is a named instance of a relation type,
where specific MBeans appear in the roles, represented by
their ObjectName
s.
For example, suppose there are Module
MBeans,
representing modules within an application. A
DependsOn
relation type could express the
relationship that some modules depend on others, which could
be used to determine the order in which the modules are
started or stopped. The DependsOn
relation type
would have two roles, dependent
and
dependedOn
.
Every role is typed, meaning that an MBean that
appears in that role must be an instance of the role's type.
In the DependsOn
example, both roles would be of
type Module
.
Every role has a cardinality, which provides lower
and upper bounds on the number of MBeans that can appear in
that role in a given relation instance. Usually, the lower
and upper bounds are both 1, with exactly one MBean appearing
in the role. The cardinality only limits the number of MBeans
in the role per relation instance. The same MBean can appear
in the same role in any number of instances of a relation
type. In the DependsOn
example, a given module
can depend on many other modules, and be depended on by many
others, but any given relation instance links exactly one
dependent
module with exactly one
dependedOn
module.
A relation type can be created explicitly, as an object
implementing the RelationType
interface, typically a RelationTypeSupport
. Alternatively, it can be created
implicitly using the Relation Service's createRelationType
method.
A relation instance can be created explicitly, as an object
implementing the Relation
interface, typically a RelationSupport
.
(A RelationSupport
is itself a valid MBean, so it
can be registered in the MBean Server, though this is not
required.) Alternatively, a relation instance can be created
implicitly using the Relation Service's createRelation
method.
The DependsOn
example might be coded as follows.
import java.util.*; import javax.management.*; import javax.management.relation.*; // ... MBeanServer mbs = ...; // Create the Relation Service MBean ObjectName relSvcName = new ObjectName(":type=RelationService"); RelationService relSvcObject = new RelationService(true); mbs.registerMBean(relSvcObject, relSvcName); // Create an MBean proxy for easier access to the Relation Service RelationServiceMBean relSvc = (RelationServiceMBean) MBeanServerInvocationHandler.newProxyInstance(mbs, relSvcName, RelationServiceMBean.class, false); // Define the DependsOn relation type RoleInfo[] dependsOnRoles = { new RoleInfo("dependent", Module.class.getName()), new RoleInfo("dependedOn", Module.class.getName()) }; relSvc.createRelationType("DependsOn", dependsOnRoles); // Now define a relation instance "moduleA DependsOn moduleB" ObjectName moduleA = new ObjectName(":type=Module,name=A"); ObjectName moduleB = new ObjectName(":type=Module,name=B"); Role dependent = new Role("dependent", Collections.singletonList(moduleA)); Role dependedOn = new Role("dependedOn", Collections.singletonList(moduleB)); Role[] roleArray = {dependent, dependedOn}; RoleList roles = new RoleList(Arrays.asList(roleArray)); relSvc.createRelation("A-DependsOn-B", "DependsOn", roles); // Query the Relation Service to find what modules moduleA depends on Map dependentAMap = relSvc.findAssociatedMBeans(moduleA, "DependsOn", "dependent"); Set dependentASet = dependentAMap.keySet(); // Set of ObjectName containing moduleB
|
JavaTM 2 Platform Standard Ed. 5.0 |
|||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES |
Copyright © 2004, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.


A multi-column element (or multicol element for short) is an element whose ‘column-width’ or ‘column-count’ property is not ‘auto’ and therefore acts as a container for multi-column layout.
In the traditional CSS box model, the content of an element is flowed into the content box of the corresponding element. Multi-column layout introduces a new type of container between the content box and the content, namely the column box (or column for short). The content of a multicol element is flowed into its column boxes.
Column boxes in a multi-column element are arranged into rows. Like table cells, the column boxes in a row are ordered in the inline direction of the multicol element. The column width is the length of the column box in the inline direction. The column height is the length of the column box in the block direction. All column boxes in a row have the same column width, and all column boxes in a row have the same column height. Within each row in the multi-column element, adjacent column boxes are separated by a column gap, which may contain a column rule. All column gaps in the same row are equal. All column rules in the same row are also equal, if they appear; column rules only appear between columns that both have content.
In the simplest case a multicol element will contain only one row of columns, and the height of each column will be equivalent to the used height of the multi-column element's content box. If the multi-column element is paginated, the height of each row is constrained by the page and the content continues in a new row of column boxes on the next page; a column box never splits across pages. The same effect occurs when a spanning element divides the multi-column element: the columns before the spanning element are balanced and shortened to fit their content. Content after the spanning element then flows into a new row of column boxes.
It is not possible to set properties/values on column boxes. For example, the background of a certain column box cannot be set and a column box has no concept of padding, margin or borders.


Class: ActiveRecord::FixtureSet::TableRow
Do not use. This class is for internal use only.
| Relationships & Source Files | |
| Namespace Children | |
|
Classes:
| |
|
Exceptions:
| |
| Inherits: | Object |
| Defined in: | activerecord/lib/active_record/fixture_set/table_row.rb |
Class Method Summary
Instance Method Summary
- #to_hash
- #add_join_records(association) private
- #fill_row_model_attributes private
- #fill_timestamps private
- #generate_primary_key private
- #interpolate_label private
- #model_class private
- #model_metadata private
- #reflection_class private
- #resolve_enums private
- #resolve_sti_reflections private
Constructor Details
.new(fixture, table_rows:, label:, now:) ⇒ TableRow
# File 'activerecord/lib/active_record/fixture_set/table_row.rb', line 65
def initialize(fixture, table_rows:, label:, now:) @table_rows = table_rows @label = label @now = now @row = fixture.to_hash fill_row_model_attributes end
Instance Method Details
#add_join_records(association) (private)
[ GitHub ]# File 'activerecord/lib/active_record/fixture_set/table_row.rb', line 165
def add_join_records(association) # This is the case when the join table has no fixtures file if (targets = @row.delete(association.name.to_s)) table_name = association.join_table column_type = association.primary_key_type lhs_key = association.lhs_key rhs_key = association.rhs_key targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/) joins = targets.map do |target| join = { lhs_key => @row[ .primary_key_name], rhs_key => ActiveRecord::FixtureSet.identify(target, column_type) } association. .each do |col| join[col] = @now end join end @table_rows.tables[table_name].concat(joins) end end
#fill_row_model_attributes (private)
[ GitHub ]# File 'activerecord/lib/active_record/fixture_set/table_row.rb', line 86
def fill_row_model_attributes return unless model_class interpolate_label generate_primary_key resolve_enums resolve_sti_reflections end
#fill_timestamps (private)
[ GitHub ]# File 'activerecord/lib/active_record/fixture_set/table_row.rb', line 103
def # fill in timestamp columns if they aren't specified and the model is set to record_timestamps if model_class. . .each do |c_name| @row[c_name] = @now unless @row.key?(c_name) end end end
#generate_primary_key (private)
[ GitHub ]# File 'activerecord/lib/active_record/fixture_set/table_row.rb', line 119
def generate_primary_key # generate a primary key if necessary if .has_primary_key_column? && !@row.include?( .primary_key_name) @row[ .primary_key_name] = ActiveRecord::FixtureSet.identify( @label, .primary_key_type ) end end
#interpolate_label (private)
[ GitHub ]#model_class (private)
[ GitHub ]# File 'activerecord/lib/active_record/fixture_set/table_row.rb', line 82
def model_class @table_rows.model_class end
#model_metadata (private)
[ GitHub ]# File 'activerecord/lib/active_record/fixture_set/table_row.rb', line 78
def @table_rows. end
#reflection_class (private)
[ GitHub ]# File 'activerecord/lib/active_record/fixture_set/table_row.rb', line 95
def reflection_class @reflection_class ||= if @row.include?( .inheritance_column_name) @row[ .inheritance_column_name].constantize rescue model_class else model_class end end
#resolve_enums (private)
[ GitHub ]#resolve_sti_reflections (private)
[ GitHub ]# File 'activerecord/lib/active_record/fixture_set/table_row.rb', line 136
def resolve_sti_reflections # If STI is used, find the correct subclass for association reflection reflection_class._reflections.each_value do |association| case association.macro when :belongs_to # Do not replace association name with association foreign key if they are named the same fk_name = association.join_foreign_key if association.name.to_s != fk_name && value = @row.delete(association.name.to_s) if association.polymorphic? if value.sub!(/\s*\(([^)]*)\)\s*$/, "") # support polymorphic belongs_to as "label (Type)" @row[association.join_foreign_type] = $1 end elsif association.join_primary_key != association.klass.primary_key raise PrimaryKeyError.new(@label, association, value) end fk_type = reflection_class.type_for_attribute(fk_name).type @row[fk_name] = ActiveRecord::FixtureSet.identify(value, fk_type) end when :has_many if association. [:through] add_join_records(HasManyThroughProxy.new(association)) end end end end
#to_hash
[ GitHub ]# File 'activerecord/lib/active_record/fixture_set/table_row.rb', line 73
def to_hash @row end


--- layout: post status: publish published: true title: Samardzija Update and Cubs/Cardinals author: display_name: Corey Fineran login: Corey email<EMAIL_ADDRESS>url: '' author_login: Corey author_email<EMAIL_ADDRESS>excerpt: "I won't brag about every Jeff Samardzija accomplishment on Ivy Envy. Let's be clear, my man-crush is on Matt Murton. But I have never owned any Cubs shirt/jersey with a name on the back and when Jeff Samardzija makes it to the Cubs and is issued a number, I will own one. I almost feel like I should apologize to Ryne Sandberg for saying that. \n\nJeff Samardzija took the hill in Oklahoma City against the Rangers Triple A Affiliate. Samardzija earned a win, going over 6 innings, giving up 4 runs on 8 hits. He walked 3 and struck out 6. He is now 2-1 with a 3.93 ERA with Iowa. Samardzija was gifted " wordpress_id: 120 wordpress_url: http://ivyenvy.wordpress.com/?p=120 date: '2008-07-05 12:25:00 +0000' date_gmt: '2008-07-05 17:25:00 +0000' categories: - Minor Leagues - The Cubs tags: - Aramis Ramirez - Cardinals - Carlos Zambrano - Felix Pie - Iowa Cubs - Jeff Samardzija - Matt Murton - Micah Hoffpauir - Oklahoma City - Rangers - Reed Johnson - Ryne Sandberg comments: - id: 67 author: JSFAN author_email<EMAIL_ADDRESS>author_url: '' date: '2008-07-05 18:07:54 +0000' date_gmt: '2008-07-05 23:07:54 +0000' content: 'You can get Samardzija''s shirt on his website (jeff samardzija.com) WHEN he gets to Wrigley, he''ll be wearing #50. Also check out Samardzijapalooza.com. Great entertainment value.' ---
I won't brag about every Jeff Samardzija accomplishment on Ivy Envy. Let's be clear, my man-crush is on Matt Murton. But I have never owned any Cubs shirt/jersey with a name on the back and when Jeff Samardzija makes it to the Cubs and is issued a number, I will own one. I almost feel like I should apologize to Ryne Sandberg for saying that.
Jeff Samardzija took the hill in Oklahoma City against the Rangers Triple A Affiliate. Samardzija earned a win, going over 6 innings, giving up 4 runs on 8 hits. He walked 3 and struck out 6. He is now 2-1 with a 3.93 ERA with Iowa. Samardzija was gifted with a lot of offense as the Iowa Cubs put up 11 runs on 19 hits. Oklahoma also had 3 errors in the game. A few names of interest had great days at the plate. Felix Pie went 4-5 with 1 RBI and Micah Hoffpauir went 3-4 with a HR, Double and 4 RBI's. A sidenote, Hoffpauir is hitting .339 in Iowa.
What a great weekend for baseball. I was relieved to see the Cubs take one in St. Louis after a long night of travel. It was great to see (well, hear...I was with Andy at the fireworks) Zambrano come back without missing a step. It's also a relief to have Reed Johnson back. I will also admit that I feel better with having Aramis Ramirez back in the line-up. There, I said it.
Any series against the Cardinals is important around these parts. I would say that we live on the northern edge of the Cubs/Cardinals geographic border in Illinois. I grew up 2 hours south of here and the area was dominated by Cardinals fans. I think there are far more Cubs fans in this area, though I work with a surprising number of Cardinals fans. So though we are north, and much closer to Chicago, there are some that follow the birds and the bats. Now that I think about it, most of the Cardinals fans I know in this area live in Iowa, so that explains it. They're a different kind of there.
I know every game is just as important/insignificant as another, but when you are playing the team right next to you in the standings, I would think it would have to be a confidence and momentum builder to take a series from them. Especially when you go into their brand new shiny house.
Go Cubs!


Disable the responsiveness of Bootstrap by fixing the width of the container and using the first grid system tier. Read the documentation for more information.
Note the lack of the <meta name="viewport" content="width=device-width, initial-scale=1">
, which disables the zooming aspect of sites in mobile devices. In addition, we reset our container's width and are basically good to go.
As a heads up, the navbar component is rather tricky here in that the styles for displaying it are rather specific and detailed. Overrides to ensure desktop styles display are not as performant or sleek as one would like. Just be aware there may be potential gotchas as you build on top of this example when using the navbar.
Non-responsive layouts highlight a key drawback to fixed elements. Any fixed component, such as a fixed navbar, will not be scrollable when the viewport becomes narrower than the page content. In other words, given the non-responsive container width of 970px and a viewport of 800px, you'll potentially hide 170px of content.
There is no way around this as it's default browser behavior. The only solution is a responsive layout or using a non-fixed element.


The Criteria API is used to define queries for entities and their persistent state by creating query-defining objects. Criteria queries are written using Java programming language APIs, are typesafe, and are portable. Such queries work regardless of the underlying data store.
The following topics are addressed here:
Similar to JPQL, the Criteria API is based on the abstract schema of persistent entities, their relationships, and embedded objects. The Criteria API operates on this abstract schema to allow developers to find, modify, and delete persistent entities by invoking Java Persistence API entity operations. The Metamodel API works in concert with the Criteria API to model persistent entity classes for Criteria queries.
The Criteria API and JPQL are closely related and are designed to allow similar operations in their queries. Developers familiar with JPQL syntax will find equivalent object-level operations in the Criteria API.
The following simple Criteria query returns all instances of the Pet
entity in the data source:
EntityManager em = ...; CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); cq.select(pet); TypedQuery<Pet> q = em.createQuery(cq); List<Pet> allPets = q.getResultList();
The equivalent JPQL query is
SELECT p FROM Pet p
This query demonstrates the basic steps to create a Criteria query.
Use an EntityManager
instance to create a CriteriaBuilder
object.
Create a query object by creating an instance of the CriteriaQuery
interface. This query object's attributes will be modified with the details of the query.
Set the query root by calling the from
method on the CriteriaQuery
object.
Specify what the type of the query result will be by calling the select
method of the CriteriaQuery
object.
Prepare the query for execution by creating a TypedQuery<T>
instance, specifying the type of the query result.
Execute the query by calling the getResultList
method on the TypedQuery<T>
object. Because this query returns a collection of entities, the result is stored in a List
.
The tasks associated with each step are discussed in detail in this chapter.
To create a CriteriaBuilder
instance, call the getCriteriaBuilder
method on the EntityManager
instance:
CriteriaBuilder cb = em.getCriteriaBuilder();
Use the CriteriaBuilder
instance to create a query object:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
The query will return instances of the Pet
entity. To create a typesafe query, specify the type of the query when you create the CriteriaQuery
object.
Call the from
method of the query object to set the FROM
clause of the query and to specify the root of the query:
Root<Pet> pet = cq.from(Pet.class);
Call the select
method of the query object, passing in the query root, to set the SELECT
clause of the query:
cq.select(pet);
Now, use the query object to create a TypedQuery<T>
object that can be executed against the data source. The modifications to the query object are captured to create a ready-to-execute query:
TypedQuery<Pet> q = em.createQuery(cq);
Execute this typed query object by calling its getResultList
method, because this query will return multiple entity instances. The following statement stores the results in a List<Pet>
collection-valued object:
List<Pet> allPets = q.getResultList();
Use the Metamodel API to create a metamodel of the managed entities in a particular persistence unit. For each entity class in a particular package, a metamodel class is created with a trailing underscore and with attributes that correspond to the persistent fields or properties of the entity class.
The following entity class, com.example.Pet
, has four persistent fields: id
, name
, color
, and owners
:
package com.example; ... @Entity public class Pet { @Id protected Long id; protected String name; protected String color; @ManyToOne protected Set<Person> owners; ... }
The corresponding Metamodel class is as follows:
package com.example; ... @Static Metamodel(Pet.class) public class Pet_ { public static volatile SingularAttribute<Pet, Long> id; public static volatile SingularAttribute<Pet, String> name; public static volatile SingularAttribute<Pet, String> color; public static volatile SetAttribute<Pet, Person> owners; }
Criteria queries use the metamodel class and its attributes to refer to the managed entity classes and their persistent state and relationships.
Metamodel classes that correspond to entity classes are of the following type:
javax.persistence.metamodel.EntityType<T>
Annotation processors typically generate metamodel classes either at development time or at runtime. Developers of applications that use Criteria queries may do either of the following:
Generate static metamodel classes by using the persistence provider's annotation processor
Obtain the metamodel class by doing one of the following:
Call the getModel
method on the query root object
Obtain an instance of the Metamodel
interface and then pass the entity type to the instance's entity
method
The following code snippet shows how to obtain the Pet
entity's metamodel class by calling Root<T>.getModel
:
EntityManager em = ...; CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); EntityType<Pet> Pet_ = pet.getModel();
The following code snippet shows how to obtain the Pet
entity's metamodel class by first obtaining a metamodel instance by using EntityManager.getMetamodel
and then calling entity
on the metamodel instance:
EntityManager em = ...; Metamodel m = em.getMetamodel(); EntityType<Pet> Pet_ = m.entity(Pet.class);
|
Note: The most common use case is to generate typesafe static metamodel classes at development time. Obtaining the metamodel classes dynamically, by calling |
The basic semantics of a Criteria query consists of a SELECT
clause, a FROM
clause, and an optional WHERE
clause, similar to a JPQL query. Criteria queries set these clauses by using Java programming language objects, so the query can be created in a typesafe manner.
The javax.persistence.criteria.CriteriaBuilder
interface is used to construct
Criteria queries
Selections
Expressions
Predicates
Ordering
To obtain an instance of the CriteriaBuilder
interface, call the getCriteriaBuilder
method on either an EntityManager
or an EntityManagerFactory
instance.
The following code shows how to obtain a CriteriaBuilder
instance by using the EntityManager.getCriteriaBuilder
method:
EntityManager em = ...; CriteriaBuilder cb = em.getCriteriaBuilder();
Criteria queries are constructed by obtaining an instance of the following interface:
javax.persistence.criteria.CriteriaQuery
CriteriaQuery
objects define a particular query that will navigate over one or more entities. Obtain CriteriaQuery
instances by calling one of the CriteriaBuilder.createQuery
methods. To create typesafe queries, call the CriteriaBuilder.createQuery
method as follows:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
The CriteriaQuery
object's type should be set to the expected result type of the query. In the preceding code, the object's type is set to CriteriaQuery<Pet>
for a query that will find instances of the Pet
entity.
The following code snippet creates a CriteriaQuery
object for a query that returns a String
:
CriteriaQuery<String> cq = cb.createQuery(String.class);
For a particular CriteriaQuery
object, the root entity of the query, from which all navigation originates, is called the query root. It is similar to the FROM
clause in a JPQL query.
Create the query root by calling the from
method on the CriteriaQuery
instance. The argument to the from
method is either the entity class or an EntityType<T>
instance for the entity.
The following code sets the query root to the Pet
entity:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class);
The following code sets the query root to the Pet
class by using an EntityType<T>
instance:
EntityManager em = ...; Metamodel m = em.getMetamodel(); EntityType<Pet> Pet_ = m.entity(Pet.class); Root<Pet> pet = cq.from(Pet_);
Criteria queries may have more than one query root. This usually occurs when the query navigates from several entities.
The following code has two Root
instances:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet1 = cq.from(Pet.class); Root<Pet> pet2 = cq.from(Pet.class);
For queries that navigate to related entity classes, the query must define a join to the related entity by calling one of the From.join
methods on the query root object or another join object. The join
methods are similar to the JOIN
keyword in JPQL.
The target of the join uses the Metamodel class of type EntityType<T>
to specify the persistent field or property of the joined entity.
The join
methods return an object of type Join<X, Y>
, where X
is the source entity and Y
is the target of the join. In the following code snippet, Pet
is the source entity, Owner
is the target, and Pet_
is a statically generated metamodel class:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); Join<Pet, Owner> owner = pet.join(Pet_.owners);
You can chain joins together to navigate to related entities of the target entity without having to create a Join<X, Y>
instance for each join:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); Join<Owner, Address> address = pet.join(Pet_.owners).join(Owner_.addresses);
Path
objects, which are used in the SELECT
and WHERE
clauses of a Criteria query, can be query root entities, join entities, or other Path
objects. Use the Path.get
method to navigate to attributes of the entities of a query.
The argument to the get
method is the corresponding attribute of the entity's Metamodel class. The attribute can be either a single-valued attribute, specified by @SingularAttribute
in the Metamodel class, or a collection-valued attribute, specified by one of @CollectionAttribute
, @SetAttribute
, @ListAttribute
, or @MapAttribute
.
The following query returns the names of all the pets in the data store. The get
method is called on the query root, pet
, with the name
attribute of the Pet
entity's Metamodel class, Pet_
, as the argument:
CriteriaQuery<String> cq = cb.createQuery(String.class); Root<Pet> pet = cq.from(Pet.class); cq.select(pet.get(Pet_.name));
Conditions that are set by calling the CriteriaQuery.where
method can restrict the results of a query on the CriteriaQuery
object. Calling the where
method is analogous to setting the WHERE
clause in a JPQL query.
The where
method evaluates instances of the Expression
interface to restrict the results according to the conditions of the expressions. To create Expression
instances, use methods defined in the Expression
and CriteriaBuilder
interfaces.
An Expression
object is used in a query's SELECT
, WHERE
, or HAVING
clause. Table 40-1 shows conditional methods you can use with Expression
objects.
Table 40-1 Conditional Methods in the Expression Interface
| Method | Description |
|---|---|
|
|
Tests whether an expression is null |
|
|
Tests whether an expression is not null |
|
|
Tests whether an expression is within a list of values |
The following query uses the Expression.isNull
method to find all pets where the color
attribute is null:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); cq.where(pet.get(Pet_.color).isNull());
The following query uses the Expression.in
method to find all brown and black pets:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); cq.where(pet.get(Pet_.color).in("brown", "black"));
The in
method can also check whether an attribute is a member of a collection.
The CriteriaBuilder
interface defines additional methods for creating expressions. These methods correspond to the arithmetic, string, date, time, and case operators and functions of JPQL. Table 40-2 shows conditional methods you can use with CriteriaBuilder
objects.
Table 40-2 Conditional Methods in the CriteriaBuilder Interface
| Conditional Method | Description |
|---|---|
|
|
Tests whether two expressions are equal |
|
|
Tests whether two expressions are not equal |
|
|
Tests whether the first numeric expression is greater than the second numeric expression |
|
|
Tests whether the first numeric expression is greater than or equal to the second numeric expression |
|
|
Tests whether the first numeric expression is less than the second numeric expression |
|
|
Tests whether the first numeric expression is less than or equal to the second numeric expression |
|
|
Tests whether the first expression is between the second and third expression in value |
|
|
Tests whether the expression matches a given pattern |
The following code uses the CriteriaBuilder.equal
method:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); cq.where(cb.equal(pet.get(Pet_.name), "Fido"));
The following code uses the CriteriaBuilder.gt
method:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); Date someDate = new Date(...); cq.where(cb.gt(pet.get(Pet_.birthday), date));
The following code uses the CriteriaBuilder.between
method:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); Date firstDate = new Date(...); Date secondDate = new Date(...); cq.where(cb.between(pet.get(Pet_.birthday), firstDate, secondDate));
The following code uses the CriteriaBuilder.like
method:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); cq.where(cb.like(pet.get(Pet_.name), "*do"));
To specify multiple conditional predicates, use the compound predicate methods of the CriteriaBuilder
interface, as shown in Table 40-3.
Table 40-3 Compound Predicate Methods in the CriteriaBuilder Interface
| Method | Description |
|---|---|
|
|
A logical conjunction of two Boolean expressions |
|
|
A logical disjunction of two Boolean expressions |
|
|
A logical negation of the given Boolean expression |
The following code shows the use of compound predicates in queries:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); cq.where(cb.equal(pet.get(Pet_.name), "Fido") .and(cb.equal(pet.get(Pet_.color), "brown")));
For queries that return more than one result, it is often helpful to organize those results. The CriteriaQuery
interface defines the following ordering and grouping methods:
The orderBy
method orders query results according to attributes of an entity
The groupBy
method groups the results of a query together according to attributes of an entity, and the having
method restricts those groups according to a condition
To order the results of a query, call the CriteriaQuery.orderBy
method, passing in an Order
object. To create an Order
object, call either the CriteriaBuilder.asc
or the CriteriaBuilder.desc
method. The asc
method is used to order the results by ascending value of the passed expression parameter. The desc
method is used to order the results by descending value of the passed expression parameter. The following query shows the use of the desc
method:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); cq.select(pet); cq.orderBy(cb.desc(pet.get(Pet_.birthday)));
In this query, the results will be ordered by the pet's birthday from highest to lowest. That is, pets born in December will appear before pets born in May.
The following query shows the use of the asc
method:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); Join<Owner, Address> address = pet.join(Pet_.owners).join(Owner_.address); cq.select(pet); cq.orderBy(cb.asc(address.get(Address_.postalCode)));
In this query, the results will be ordered by the pet owner's postal code from lowest to highest. That is, pets whose owner lives in the 10001 zip code will appear before pets whose owner lives in the 91000 zip code.
If more than one Order
object is passed to orderBy
, the precedence is determined by the order in which they appear in the argument list of orderBy
. The first Order
object has precedence.
The following code orders results by multiple criteria:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); Join<Pet, Owner> owner = pet.join(Pet_.owners); cq.select(pet); cq.orderBy(cb.asc(owner.get(Owner_.lastName)), owner.get(Owner_.firstName)));
The results of this query will be ordered alphabetically by the pet owner's last name, then first name.
The CriteriaQuery.groupBy
method partitions the query results into groups. To set these groups, pass an expression to groupBy
:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); cq.groupBy(pet.get(Pet_.color));
This query returns all Pet
entities and groups the results by the pet's color.
Use the CriteriaQuery.having
method in conjunction with groupBy
to filter over the groups. The having
method, which takes a conditional expression as a parameter, restricts the query result according to the conditional expression:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Root<Pet> pet = cq.from(Pet.class); cq.groupBy(pet.get(Pet_.color)); cq.having(cb.in(pet.get(Pet_.color)).value("brown").value("blonde"));
In this example, the query groups the returned Pet
entities by color, as in the preceding example. However, the only returned groups will be Pet
entities where the color
attribute is set to brown
or blonde
. That is, no gray-colored pets will be returned in this query.
To prepare a query for execution, create a TypedQuery<T>
object with the type of the query result, passing the CriteriaQuery
object to EntityManager.createQuery
.
To execute a query, call either getSingleResult
or getResultList
on the TypedQuery<T>
object.
Use the TypedQuery<T>.getSingleResult
method to execute queries that return a single result:
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); ... TypedQuery<Pet> q = em.createQuery(cq); Pet result = q.getSingleResult();


We aim to simplify the attendance process for both student and professor
For the learning environment, there have been times where attendance can become tedious and redundant. What we are working to deliver is a remedy to that 5 - 10 minute waste before class where nothing gets done so those involved will not feel the need to rush. We at Square have had these problems and are working to finally create a solution that will satisfy students, professors, and the learning environment they belong to.
Project demonstration Square Demonstration
User tutorial available Here
Developer notes Here
XAMPP Download
git clone https://github.com/Square-CS2020/AttendWebsite.git
Here is a little about our team of six
Senior in computer science with programming experience in Java, C, C++, and Python 3. Experience with Microsoft Windows and Linux operating systems.
Senior in computer science with programming experience in Java, C, HTML, Javascript, and Python
Senior in computer science with programming experience in Java and C. Earned a Bachelor's Degree in Anthropology from the University of Florida in 2011.
Senior in computer science with programming experience in java, C, C++, and HTML.
Senior in computer science with programming experience in Java, C, C++, Python, and the game development engine Unity.
Senior in computer science with programming experience in Java, C, CSS, JavaScript, HTML, and SQL.Has developed websites that utilized ASP. Net and has created small scale databases for the web pages.
We here at Square have similar backgrounds and similar experience. We assure you that we know how to work because we have all stubbornly made it this far and have a clear vision to what we want to deliver to you.


rel="stylesheet">
Do you want to know your Ghanian aka name?. well put in your deteils below and find out.!


| Interface | Description |
|---|---|
| Indexed |
A simple interface (simpler than List) for accessing random-access objects without changing their size.
|
| RandomChoiceChooser |
Used by RandomChoice to pick objects by probability from a distribution.
|
| RandomChoiceChooserD |
Used by RandomChoice to pick objects by probability from a distribution.
|
| SortComparator |
The interface for passing objects to ec.util.QuickSort
|
| SortComparatorL |
The interface for passing objects to ec.util.QuickSort
|
| ThreadPool.Worker |
A Worker is a special kind of object which represents an underlying
Worker thread usable in the ThreadPool.
|
| Class | Description |
|---|---|
| Checkpoint |
Checkpoints ec.EvolutionState objects out to checkpoint files, or
restores the same from checkpoint files.
|
| Code |
Code provides some simple wrapper functions for encoding and decoding
basic data types for storage in a pseudo-Java source code strings
format.
|
| DataPipe | |
| DecodeReturn |
DecodeReturn is used by Code to provide varied information returned
when decoding.
|
| IIntPoint |
An immutable 2-dimensional point.
|
| IntBag |
Maintains a simple array (objs) of ints and the number of ints (numObjs) in the array
(the array can be bigger than this number).
|
| Lexer |
A simple line-by-line String tokenizer.
|
| LocalHost |
Modified from
apache mail-archives.
|
| Log |
Defines a log to which Output outputs.
|
| LogRestarter |
A LogRestarter is an abstract superclass of objects which are
capable of restarting logs after a computer failure.
|
| MersenneTwister |
MersenneTwister and MersenneTwisterFast
|
| MersenneTwisterFast |
MersenneTwister and MersenneTwisterFast
|
| Misc |
Miscellaneous static utility methods.
|
| Output |
Outputs and logs system messages, errors, and other various
items printed as a result of a run.
|
| Parameter |
A Parameter is an object which the ParameterDatabase class
uses as a key to associate with strings, forming a key-value pair.
|
| ParameterDatabase |
This extension of the Properties class allows you to set, get, and delete
Parameters in a hierarchical tree-like database.
|
| ParameterDatabaseEvent | |
| ParameterDatabaseTreeModel | |
| QuickSort |
Implementations of various center-pivot QuickSort routines in Java,
and (if you really want 'em) Insertion Sort routines as well.
|
| RandomChoice |
RandomChoice organizes arrays of floats into distributions which can
be used to pick randomly from.
|
| ReflectedObject | |
| ThreadPool |
ThreadPool.java
A simple, lightweight thread pool, for those who cannot or will not use Java's baroque
java.util.concurrent package.
|
| Version |
Version is a static class which stores version information for this
evolutionary computation system.
|
| Exception | Description |
|---|---|
| BadParameterException |
Thrown when you attempt to create a Parameter from bad path items.
|
| Output.OutputExitException | |
| OutputException |
Thrown whenever a problem occurs when attempting to output to a Log.
|
| ParamClassLoadException |
This exception is thrown by the Parameter Database when it fails to
locate and load a class specified by a given parameter as requested.
|


## Overview
1. Background
1. Current state of code
1. Future state of code
1. Plan
1. Execution
1. Risks
1. After base renovations
1. Chosen solutions
## 1. Background
- Ongoing project for years
- Lots of features implemented
- Prio new features and bug fix
- Quite a bit of technical debt
- Wish to achieve a modern JS-code base
- Rewrite from scratch? Migrate?
## 2. Current state of code
- Automated tests?
- What build system is used?
- Dependency management
- Modular code?
- Hand written solutions?
## 3. Future state of code
- Mantra: simplify!
- Browser support nowadays?
- What can be removed?
- Simplest possible build system
- Standardized code formatting
## 4. Plan
- Clear goals / milestones
- Separated iterations
- Where to begin
- Lots of value for little effort
## 5. Execution
- Begin with build system, easy to verify
- Modularise without reorganizing code
- Keep behaviors and names of build scripts
- Test constantly - both auto and manually
- Always do only one thing at a time!
## 6. Risks
- Doing more than one thing at a time
- Rollback needs to be trivial
- Replacing a complex thing with another complex thing
- Rewriting something "just because"
## 7. Next steps?
- Modules and modern JS available
- AngularJS -> Angular (5)
- State management with Redux
- Web Components
- Componentized UI-components
## Chosen Solutions
## JavaScript-modules
- Newly standardized
- Predecessors AMD, CommonJS
- Code navigation in editor
- Autocomplete, intellisense
## Compile to JavaScript
- TypeScript: Superset of JavaScript
- Transpiles modern JS to work in browsers
- Refactoring no-brainer
## Data store
- All data in one place
- Easy to organize and test
- Time traveling - "undo"
## Editor with code analysis
- Visual Studio Code
- Atom
- VIM
- Sublime
- Autocompletion etc.
## Code formatting
- Prettier.js
- Opinionated
- Can set a few options
- Automatic formatting
- Scary until you've tried
- Scaffolding base and components
- All build steps necessary
- Environments
## Webpack (via Angular CLI)
- Automated bundling and building JS
- Also CSS-moduler etc.
- Live reload
- Cache busting, minifying code
## Front End Framework
- Complete FE Framework
- Components for UI element
- FormBuilder, Router, HTTP Client
- Observables, One way binding


Oleh Petrashevskyi, National Transport University, Department of Airports, Professor, https://orcid.org/0000-0001-7909-6057
Ivan Popelish, National Transport University, Department of Airports, Associate Professor, https://orcid.org/0000-0003-3358-6565
Oleksandr Alieksieienko, National transport university, Department of Airports, senior lecturer, https://orcid.org/0000-0002-3796-9929
Sergey Koritchuk, National Transport University, Department of Airports, Assistant, https://orcid.org/0000-0001-5100-873Х
Yuliia Artemchuk, National Transport University, Department of Transport systems and road safety, Assistant, https://orcid.org/0000-0002-3872-7745
Abstract: We continue to publish proposals for improving transport systems. This article defines the 4th part of a large topic on the creation and adjustment of terms and definitions required for communication processes of communication, primarily researchers in this field of subject activity "researcher of transport systems (theorist) - researcher of transport systems (practitioner)". The second aspect of verвal interaction is to establish a communication relationship between "man - computer", which is important in modern conditions.
Article language: Ukrainian
Referenses:
7.Petrashevskyi O.L. Kontrolno Vremennye Tochky Na Osy Stsenaryev Dostavky Hruzov Avtomobylnym Transportom (1-Ia Chast). O.L. Petrashevskyi Y.Y. Popelysh A.V. Alekseenko S.A. Korytchuk.
Open Access: http://publications.ntu.edu.ua/avtodorogi_i_stroitelstvo/109/174.pdf
Online publication date: 25.02.2021
Print date: 01.02.2021


class: center, middle, inverse, title-slide # Lab2: Basic programming in R ## Conditional executions and iterative statements ### Christopher Moore ### 2018/02/18 --- # Basic programming to R(1 + Studio) * **Conditional executions**: `if` statements determine whether or not to execute code -- * **Iterative statements**: iterates your code * **`for()` loops**: iterate dependent actions * **the `apply()` family**: iterate independent actions in a fraction of the time * **`while()`**: a simple conditional iterative function --- background-image: url(https://d33v4339jhl8k0.cloudfront.net/docs/assets/534421c6e4b09045db8e8a4b/images/5346a718e4b0b2c45b46a36b/file-ofGnbryhhh.gif) background-size: center class: inverse, center, bottom # Conditional executions: `if()` statements --- # `if()` statements in R *A statement that might or might not be executed depending on whether a test is true or false.* -- **Pseudocode:** `if (`condition`) {` operation `}` -- **Code:** ```r temp <- 200 ``` -- ```r if (temp > 100) { message("The porridge is too hot.") } ``` -- ``` ## The porridge is too hot. ``` --- # `if()` statements in R: adding else **Pseudocode, II:** `if (`condition`) {` operation `} else {` other operation `}` -- ```r temp <- 20 ``` -- ```r if (temp > 100) { message("The porridge is too hot.") } else { message("The porridge is too cold.") } ``` -- ``` ## The porridge is too cold. ``` --- # `if()` statements in R: ladders **Pseudocode, III:** `if (`condition I`) {` operation `} else if (`condition II`) {` other operation `}` -- ```r temp <- 100 ``` -- ```r if (temp > 100) { message("The porridge is too hot.") } else if ( temp < 100) { message("The porridge is too cold.") } else { message("The porridge is perfect.") } ``` -- ``` ## The porridge is perfect. ``` --- class: inverse, center, bottom background-image: url(https://www.hongkiat.com/blog/wp-content/uploads/programming-jokes/joke-shampoo.jpg) background-size: center # Iterative statements in R --- # `for()` loops in R: the basics An iterative statement (*that tells the computer to do all of the work for you*) -- **Pseudocode:** `for (`variable in vector`) {` operation `}` -- **Code**: ```r for (i in 1:4) { print(i) } ## [1] 1 ## [1] 2 ## [1] 3 ## [1] 4 ``` --- # `for()` loops in R: saving output The idea is that you give `for()` a vector, and it performs an operation over it (**note a `for()` loop isn't needed for this, but it has heuristic value to do it**) -- **Code**: ```r my.vec <- rep(x = 0, times = 4) #rep means repeat, and the arguments are "x" to repeat and number of "times" my.vec ## [1] 0 0 0 0 for (i in 1:4) { # this saves to element `i` the value `i + 10` my.vec[i] <- i + 10 } my.vec ## [1] 11 12 13 14 ``` --- # `for()` loops in R: successive operations For perform an action based on a pervious value, and there are two common ways of doing this: -- **Example 1, code**: ```r n.steps <- 4 my.vec <- rep(x = 0, times = n.steps) initial.val <- 20 my.vec[1] <- initial.val for (i in 1:(n.steps - 1)) { # this saves to element `i + 1` the value `i + 10` my.vec[i+1] <- my.vec[i]*2 } ``` -- ```r my.vec ## [1] 20 40 80 160 ``` --- # `for()` loops in R: successive operations For perform an action based on a pervious value, and there are two common ways of doing this: -- **Example 2, code**: ```r n.steps <- 4 my.vec <- rep(x = 0, times = n.steps) initial.val <- 20 my.vec[1] <- initial.val for (i in 2:n.steps) { # this saves to element `i` the value `(i - 1) + 10` my.vec[i] <- my.vec[i-1]*2 } ``` -- ```r my.vec ## [1] 20 40 80 160 ``` --- # `for()` loops in R: a note on preallocation 1. Open R (or RStudio) 2. Create two vectors 1. One with a length of 0 (i.e., `c()`) 2. One with a length of 1 million (yes, we are about to do 1M things—I love loops) 3. Write two `for()` loops (one for each vector) from 1 to 1 million and let's just save the value of i to its corresponding element in the vector (e.g., i = 1 is the first element, i = 2 is the second) 4. Run the code a few times -- 5. Now, increase the length of both vectors to 10 million, and run one at a time for a few times: how long are they taking? -- 6. Now, increase the length of both vectors to 100 million! Try to time how long it takes each to loop through each vector. -- ### Take-home message: always preallocate! --- # `for()` loops in R: a note on preallocation ```r size <- 1e8 d.start <- proc.time() abc <- c() for (i in 1:size) { abc[i] <- i } d.end <- proc.time() p.start <- proc.time() cba <- vector(mode = "numeric", length = size) for (i in 1:size) { cba[i] <- i } p.end <- proc.time() d.end - d.start ## user system elapsed ## 28.706 4.312 33.687 p.end - p.start ## user system elapsed ## 8.722 1.637 10.991 ``` --- background-image: url(https://img.devrant.com/devrant/rant/r_263557_mfJLG.jpg) background-size: center class: inverse, bottom, center **A final rule of thumb—avoid magic numbers** (Specify your variables as much as possible to reduce redundancy and errors in your code [e.g., `size` in the previous slide is used 3 subsequent times].) --- # Lab Report 2, problem 2.3 and 2.4: 2.3. Alas, some ecology! Take the difference equation (discrete time) that models density-indepedent growth. Write a `for()` loop that iterates the equation for 10 timesteps with an initial density of 0.01 and `\(\lambda = 1.01\)`. That's much easier than doing it by hand, isn't it? -- 2.4. Let’s now turn to a density-dependent model from this week’s reading: the Ricker model. It’s equation 30 in chapter 1. Simulate this model for 20 timesteps with `\(r=0.5\)` and `\(b = 0.1\)` from an initial density of 1 and plot it. What is the final density?


PyPulse v0.0.1¶
PyPulse is a package used to handle PSRFITS files and perform subsequent analyses on pulse profiles.
Download:
Requirements:
Contents:
Citations¶
See ASCL. You can cite as:
Lam, M. T., 2017, PyPulse, Astrophysics Source Code Library, record ascl:1706.011
Contact¶
Please contact michael-dot-lam-at-nanograv-dot-org.


- InBox - Class in client
-
Class for handling message strings.
- InBox(Connect) - Constructor for class client.InBox
-
- initialize() - Method in class ui.GamesUI
-
Updates the game list panel.
- initialize(String) - Method in class ui.HighScoresUI
-
Loads and initializes the high scores list.
- initialize() - Method in class ui.SettingsUI
-
Loads and initializes the saved/default user settings.
- inOverState() - Method in class controller.Controller
-
Checks to see if the game is in the setup state.
- inOverState() - Method in class game.Logic
-
Checks and returns a boolean whether or not the game is in the over state.
- inOverState() - Method in class ui.Viewer
-
- inSetupState() - Method in class controller.Controller
-
Checks to see if the game is in the setup state.
- inSetupState() - Method in class game.Logic
-
Checks and returns a boolean whether or not the game is in setup state.
- inSetupState() - Method in class ui.Viewer
-
- isAllowed() - Method in class game.SelectValue
-
Returns allowed
- isHidden() - Method in class pawns.Pawn
-
- isInPlayerArea(Position) - Method in class controller.Controller
-
Checks if a position is in the players setup area.
- isInPlayerArea(Position) - Method in class game.HotseatLogic
-
- isInPlayerArea(Position) - Method in class game.Logic
-
Checks if a position is within the players area.
- isInPlayerArea(Position) - Method in class game.OnlineLogic
-
- isInPlayerArea(Position) - Method in class ui.Viewer
-
- isOnlineGame() - Method in class controller.Controller
-
Checks if the game is an online game
- isOnlineGame() - Method in class ui.Viewer
-
- itemStateChanged(ItemEvent) - Method in class server.ServerUI
-
ItemListener on the checkboxes.


--- title: "Days 21-22: NIO in Java" created: !!timestamp '2019-02-06 12:00:00' --- {% mark excerpt -%} To experiment with distributed systems, I've decided to first build a [skeleton project](distributed-systems-getting-started-2.html) in Java that will announce itself on the network and send messages to other instances of itself. In other words, I'm building a chat application. {%- endmark %} Java has 3 main options for sending messages using [sockets](https://en.wikipedia.org/wiki/Network_socket): 1. [java.net](https://docs.oracle.com/javase/tutorial/networking/sockets/index.html): the original method, providing classes for blocking IO with TCP/UDP 2. [java.nio](https://en.wikipedia.org/wiki/Non-blocking_I/O_(Java)): newer than java.net, provides blocking or non-blocking IO using buffers 3. [java.nio2](https://www.ibm.com/developerworks/library/j-nio2-1/index.html): similar to java.nio, but adds an asynchronous API The difference between blocking and non-blocking IO is that with blocking IO, the socket thread will wait until it receives a response, so to serve many clients, you'll need many threads. With non-blocking IO, requests return immediately (even if there is no data), so many clients can be served with a single thread. (For a fuller explanation, try [Blocking I/O and non-blocking I/O](https://medium.com/coderscorner/tale-of-client-server-and-socket-a6ef54a74763) by Rukshani Athapathu.) If I was coding a professional chat application, there would be a [debate](https://stackoverflow.com/questions/267306/java-net-versus-java-nio) to be had about whether java.nio is actually necessary to support the expected number of connections. Since I'm not, I'm simply going with my gut feeling, which is that using java.nio is just good practice (and not actually all that hard). Many [java.nio tutorials](https://crunchify.com/java-nio-non-blocking-io-with-server-client-example-java-nio-bytebuffer-and-channels-selector-java-nio-vs-io/) follow a client-server pattern (which doesn't really work for a distributed system since it introduces a single point of failure) so here's a quick overview of how to write an application that's capable of doing both. **1. Get a Selector** The [Selector](https://docs.oracle.com/javase/7/docs/api/java/nio/channels/Selector.html) class is central to non-blocking IO with Java. It's used to examine one or more [channels](https://docs.oracle.com/javase/7/docs/api/java/nio/channels/SelectableChannel.html) and find out what (if anything) they are ready to do. The 4 possible operations are Accept, Connect, Read and Write.
Selector selector = Selector.open();**2. Start listening** Open a port to which other clients can connect, and register this with the selector so that it knows we are interested in the "accept" event.
ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.configureBlocking(false); InetSocketAddress address = new InetSocketAddress("localhost", port); serverChannel.socket().bind(address); serverChannel.register(selector, SelectionKey.OP_ACCEPT);**3. Accept incoming connections** When a client connects to us, we want to accept the connection, put the channel into non-blocking mode, and register that we are interested in reading and writing.
private void accept(SelectionKey key) { ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); SocketChannel channel = serverChannel.accept(); // Configure the connection as non-blocking, and register it as readable and writable channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); }**4. Make outgoing connections** To act as both client and server, the application shouldn't just accept incoming connections, but should make outgoing connections too. Until I set up [service discovery](https://en.wikipedia.org/wiki/Service_discovery), I'm just going to give the application a port range, listen on the first available port in that range, and attempt to connect to the others. To make a single outgoing connection:
InetSocketAddress address = new InetSocketAddress("localhost", port); SocketChannel channel = SocketChannel.open(address); // Configure the connection as non-blocking, and register it as readable and writable channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);**5. Read and write** Read from and write to the socket using [ByteBuffer](https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html)s.
private void read(SelectionKey key) { SocketChannel channel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(1024); int numRead = channel.read(buffer); if (numRead == -1) { return; } byte[] data = new byte[numRead]; System.arraycopy(buffer.array(), 0, data, 0, numRead); ... }
private void write(SelectionKey key) { SocketChannel channel = (SocketChannel) key.channel(); ByteBuffer bufferedMessage = ByteBuffer.wrap(message); int written = channel.write(bufferedMessage); ... }**6. Put it all together: query the Selector and handle the result**
IteratorThe full source is [available on GitHub](https://github.com/hmcc/java-sockets-demo/blob/master/src/main/java/org/problemchimp/io/NIORunnable.java). Enjoy!keyIterator = selector.selectedKeys().iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); if (key.isAcceptable()) { // accept the connection accept(key); } else if (key.isReadable()) { // read data read(key); } else if (key.isWritable()) { // write to the socket write(key, message); } // very important: remove the key to be notified of future events keyIterator.remove(); }