DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

The Latest Java Topics

article thumbnail
Java Quiz 8: Upcasting and Downcasting Objects
Check in on the results from a previous quiz about unary operators in Java and try out your knowledge up upcasting and downcasting objects.
January 4, 2018
by Sar Maroof
· 16,076 Views · 4 Likes
article thumbnail
Java Quiz 4: Passing a Parameter to a Constructor
Catch up with the answer to the last Java Quiz about exception handling and dive into a new one about passing parameters to constructors.
November 9, 2017
by Sar Maroof
· 9,709 Views · 7 Likes
article thumbnail
Java Quiz 18: Multidimensional Arrays
Let's take a look at the answer to our last quiz (dealing with Arrays) before jumping into this week's puzzle, which tackles working with multidimensional Arrays.
May 24, 2018
by Sar Maroof
· 11,076 Views · 5 Likes
article thumbnail
A Java Programmer’s Guide to Random Numbers. Part 2: Not just coins and dice
This is the second in a series of articles about random numbers in Java programs. The series covers the following topics and also serves as an introduction to the random numbers package of the Uncommons Maths library: True Random Numbers and Pseudorandom Numbers Statistical Quality (making sure the dice are not loaded) Performance (because sometimes you really do need half a million random numbers a second) Different kinds of randomness (because not everything can be modelled by tossing a coin) Degrees of Freedom (is every possible outcome actually possible?) Security and Integrity (when not losing money depends on nobody knowing what happens next) Part 1 of this series discussed different kinds of random number generators (RNGs), highlighted the issues with using the default Java RNGs (java.util.Random and java.security.SecureRandom) and introduced the Uncommons Maths library, which provides three fast, high-quality alternative Java RNGs. But there is more to the random numbers package than just replacement RNGs. Uncommons Maths also provides convenient classes for working with several different probability distributions, which is pretty much essential for modelling anything other than the most simple random processes. The Uncommons Maths random numbers demo application (WebStart required) demonstrates many of the concepts discussed in this article. It also serves as an example of the performance differences between different RNGs as discussed in the previous article. Different Kinds of Randomness Uniform Distribution The Uniform Distribution is what you get by default from java.util.Random (and its sub-classes - including the Uncommons Maths RNGs). The discrete uniform distribution says that there are a certain number of possible outcomes and each is equally likely. The obvious example is rolling a dice. You can get a 1, 2, 3, 4, 5 or 6 and no single outcome is more likely than any of the others. If you record the results of 6 million dice rolls you would expect to get pretty close to a million of each number. The uniform distribution is useful for some problems, such as shuffling a deck of cards, but it is not a good choice for many other scenarios that don’t involve a set of equally likely outcomes. Normal (Gaussian) Distribution The Normal Distribution (also known as the Gaussian Distribution) is the familiar bell curve. It is a good model for many real world phenomena. In a normal distribution, the average outcome is more likely than any other outcome. A slightly above or below average outcome is almost as likely, and extreme outcomes, while still possible, are very unlikely. An example of this would be the distribution of IQ test scores. Most people would achieve somewhere close to an average score (maybe slightly above or below), but a few people would achieve very low scores and a similarly small number would achieve very high scores. The nextGaussian() method of the java.util.Random class provides rudimentary support for obtaining normally-distributed values. Uncommons Maths’ GaussianGenerator class builds on this, making it easy to create distributions with different means and standard deviations. The standard deviation parameter controls how spread out the values are. A low standard deviation means most values will be very close to the mean (on either side). A high standard deviation increases the likelihood that a value will be a long way from the mean. GaussianGenerator is a wrapper around a standard RNG (you can use any of the Uncommons Maths RNGs, or even one of the standard Java ones if you so choose). Once you have created a GaussianGenerator by specifying a mean, standard deviation and source RNG, you can call the nextValue() method ad infinitum: Random rng = new MersenneTwisterRNG(); GaussianGenerator gen = new GaussianGenerator(100, 15, rng); while (true) { System.out.println(gen.nextValue()); } If we were to generate thousands of simulated IQ test scores with this code, we would see that the vast majority of scores would be close to the average (100). Around 68% of the values would be within one standard deviation (15) of the mean (i.e. in the range 85 - 115), and approximately 95% would be within two standard deviations (between 70 and 130). These percentages are a well-known property of normal distributions. The demo shows how the distribution of generated values compares to a theoretical normal distribution (the more values you generate, the closer the fit will be). Binomial Distribution The probability of a coin flip coming up heads is 0.5. This is pretty simple - we can just use the uniform distribution to simulate a single coin flip. But what is the probability of getting exactly 7 heads from 10 coin flips? This is where the Binomial Distribution comes in. It provides probabilities for the outcome of a series of trials, where each trial has two possible results - success or failure. The binomial distribution tells us that the probability of obtaining heads 7 times from 10 fair coin flips is about 0.12. Suppose, for example, we wanted to randomly generate the number of times the number 6 occurred in 100 dice rolls. We could simulate the full series of trials using a uniform RNG, but this is cumbersome: Random rng = new MersenneTwisterRNG(); int sixes = 0; for (int i = 0; i < 100; i++) { int diceRoll = rng.nextInt(6) + 1; if (diceRoll == 6)) { ++sixes; } } System.out.println("No. of 6s from 100 rolls is " + sixes); It is much easier, and more efficient, to use the binomial distribution. If we consider an occurrence of a 6 to be a “success”, then the probability of succes is 1/6 (or ~0.1667). If we plug this value and the number of trials (100) into the Uncommons Maths BinomialGenerator class, we can get our answer from a single method call: Random rng = new MersenneTwisterRNG(); BinomialGenerator gen = new BinomialGenerator(100, 1d/6, rng); int sixes = gen.nextValue(); System.out.println("No. of 6s from 100 rolls is " + sixes); Poisson Distribution Suppose a telephone call centre, between 2pm and 4pm in the afternoon, receives calls at average of 3 per minute. What is the probability that we receive exactly 5 calls in the next minute? This is the kind of question that we can answer with the Poisson Distribution. The Poisson distribution is not dissimilar to the Binomial distribution, as you will see if you plot them. The difference is that the Poisson distribution is concerned with how many independent events occur within a set interval. Whereas values from a binomial distribution have an upper bound determined by the number of trials, there is no upper bound for a Poisson distribution. The probability of 5 calls in a minute when the average is 3 is around 0.17 according to the Poisson distribution. In simulation applications we can use the PoissonGenerator class (its single parameter is the mean) to determine how many times something happens within a given interval. Exponential Distribution The Exponential Distibution is related to the Poisson Distribution. Rather than modelling how many events occur in a fixed period of time, it models the period of time between two independent events that occur at a given average rate. Suppose you wanted to simulate some random event that happened on average 10 times a minute - perhaps you are simulating load for a server. You could simply generate events at the constant rate of exactly one every 6 seconds. But the real world is rarely this metronomic. A more realistic approach would be to generate events randomly, using an exponential distribution (provided by the ExponentialGenerator class) to determine the intervals between events: final long oneMinute = 60000; Random rng = new MersenneTwisterRNG(); // Generate events at an average rate of 10 per minute. ExponentialGenerator gen = new ExponentialGenerator(10, rng); boolean running = true; while (true) { long interval = Math.round(gen.nextValue() * oneMinute); Thread.sleep(interval); // Fire event here. } http://blog.uncommons.org/2008/04/06/a-java-programmers-guide-to-random-numbers-part-2-not-just-coins-and-dice/
May 23, 2023
by Dan Dyer
· 27,352 Views · 1 Like
article thumbnail
Java: Create a Map With Predefined Keys
In this article, we discuss how to use Lombok, Jackson, and enums to create a Map from a set of predefined keys.
January 27, 2020
by Taha Dalal CORE
· 22,412 Views · 6 Likes
article thumbnail
Java Performance Tools: Nine Types of Tools You Need to Know!
Can you name all nine?
October 8, 2019
by Darin Howard
· 11,993 Views · 4 Likes
article thumbnail
Java and JavaScript Integration in OSGI
You will learn how to integrate front-end with backend by following along with this great tutorial. Read on to get started!
Updated October 1, 2018
by Kees Pieters
· 9,136 Views · 2 Likes
article thumbnail
Java HTML Report in a Few Lines of Code (Part 2)
Bringing Java to the frontend.
May 24, 2021
by Pavel Ponec
· 6,477 Views · 1 Like
article thumbnail
Java HTML Report in a Few Lines of Code
A practical example of how to build real-world applications in Java and create a simple but useful front-end with basic HTML.
Updated May 12, 2021
by Pavel Ponec
· 6,907 Views · 1 Like
article thumbnail
Java for Testers: A Complete Step-By-Step Guide
In test-driven development (TDD), if you want to write good code, you have to write tests first and then figure out how to make them pass.
November 14, 2022
by Arunpandi R
· 8,665 Views · 3 Likes
article thumbnail
Java Enterprise and Desktop: Spot The Difference
The two main branches of Java development, Enterpise and Desktop, have traditionally been seen as separate skill sets. But some current trends are contributing to blurring the line between the desktop and the web. For years I've been working on desktop Java with Swing and with the Eclipse platform. I've regarded JEE development as a separate activity, targeting the web market. Some changes in the industry have led me to question this assumption. What is an Enterprise Application Anyway? Before we discuss why desktop and enterprise Java aren’t all that different, we should look at what defines an application as an enterprise application An application that involves the integration of many resources An application with high performance requirements Scalable, secure and robust Easy to maintain and extend May run across a network If you look at what you are writing at the moment, I'm sure it must tick at least 3 out of the 5 points above. I would go as far to say that it covers almost 80% of all applications currently being developed. The important thing to take from this is that whether you are developing for your application server, or for your desktop environment, chances are you are developing an enterprise application. Signs of a Welcome Change Analysts at Gartner Group, writing in the report Trends in Platform Middleware state something that has been quite obvious from the past few years of enterprise development, often quoted by Rod Johnson. The popular Java Platform, Enterprise Edition (Java EE) and .NET platform middleware technologies are increasingly inadequate to cover needs for extensive scalability and performance, event-based programming styles, advanced service-oriented architecture (SOA) and dynamic application developments. When the original J2EE architecture was defined, it tried, but failed to predict the future. By attempting to cover all cases, including more than its fair share of “what-if” scenarios, it became an overwhelming specification. Trends over the past few years have seen a rise of innovation in the open source community, giving us frameworks such as Spring and Hibernate, each dealing with a particular piece of the jigsaw. In particular, OSGi has given the chance to produce properly dynamic applications. Each of these frameworks can run as standalone on a desktop, or deployed on an application server. This lack of dependency on the application server gives the freedom to use the same approaches on different platforms. The Desktop Moves to the Web So far we’ve seen that the enterprise applications are becoming more lightweight and more modular thanks to Spring and OSGi. Integration with key third party APIs is easy thanks to the rise of open source. One of the most interesting trends in the past year has been the ramping up of the effort to move desktop quality software onto the web browser. Appcelerator’s Nolan Wright, notes that his RIA development platform will be making a move towards better desktop integration in a recent interview. We see the next big thing for us being desktop integration, but not at the expense of the browser. We want to have the power of the web in a desktop container, where we get to use features like drag n drop and saving files locally. Adobe AIR is already making progress in this area. With the expected spotlight to be on JavaFX at this year's JavaONE, we can see that Sun recognizes that we need to have a useful presentation layer for many target platforms. Google’s GWT API has been written to closely mirror what the Swing API looks like. Developers who previously thought themselves to be pure desktop can now find themselves comfortably developing front ends on either the desktop or the web, thanks to this trend. Online IDEs have been getting a lot more coverage, and are seen as one of the next big things. Eclipse has been making some moves towards this web-enabled future with the announcement of e4, and we can expect to see a lot more companies looking at this convergence of the web and the desktop. IBM’s Mike Wilson, leader of the Eclipse Platform project, explains why this change in focus needs to happen for Eclipse. I think it's very important for the Eclipse code base to move out to the Web, and get involved more in that space, because the world is changing. A lot of business software development is moving to Web-base UIs backed by services. We're also seeing the IDE world moving in that direction. The Part OSGi has to Play This move to service based software has many implications, not least a better, more modular design. It’s a natural evolution for software development to take, and helps to make the field more mature. OSGi plays a central role in this modular approach, providing a dynamic component model. As an example, Eclipse provides the Equinox OSGi framework, which can run in many modes – standalone on any JVM, as part of an Eclipse RCP application or to even deploy the Equinox WAR file on your Java EE server. Ian Skerrett, Director of Marketing for the Eclipse Foundation specifies the problem that the OSGi approach will solve. In Java we have SE (Standard Edition) and ME (Micro Edition) and EE (Enterprise Edition). These all require different models. It's portable, but not properly consistent. Infrastructure technology needs to be a lot more adaptable. It is fair to say that OSGi is one of the most important enabling technologies to get us to this goal of a better infrastructure where we just choose our target platform and deploy accordingly, rather than having to create separate projects to deal with different environments. What This Means for the Industry So how does this affect a daily developer's life? For a start, it's time to break down any barriers and pre-conceptions that you may have about either desktop or enterprise developers. To survive in the industry of the future, and I'm guessing around two years time here, we need to be able to work with both streams. Desktop developers need to ramp up on JEE skills - perhaps even looking at the older J2EE approaches to full appreciate the technologies provided - it's much more than just technologies for the web. On the other hand JEE developers need to familiarize themselves with the traditional user interface technologies such as Swing and SWT. At some point, we'll find a nice middle ground, but this knowledge will help us shape a better future for the Java applications we write. So, what do you think - have you seen this trend happening already where you work? Are there cases where we can't think of enterprise and desktop as the same thing?
May 23, 2023
by James Sugrue CORE
· 7,717 Views · 1 Like
article thumbnail
Java EE Guardians Survey Results: Java SE 8 Alignment
How important is it for Oracle to start aligning Java EE with Java SE? According to a recent survey, probably pretty important. See how the future of that hope looks.
February 15, 2017
by Reza Rahman CORE
· 10,288 Views · 5 Likes
article thumbnail
Java EE Guardians Survey Results: HTTP 2/Servlet 4
Exactly how important is HTTP 2 support (and by extension, Servlet 4 support to make it happen) for Java EE? Our survey says devs think it's pretty important.
February 3, 2017
by Reza Rahman CORE
· 9,893 Views · 7 Likes
article thumbnail
Java EE 6 Pet Catalog with GlassFish and MySQL
This Pet Catalog app explains a web application that uses JSF 2.0, Java EE 6, GlassFish and MySQL. I took this example GlassFish and MySQL, Part 2: Building a CRUD Web Application With Data Persistence and modified it to use some of the new features of JSF 2.0 and Java EE 6. Download the sample code Explanation of the usage of JSF 2.0 and Java EE 6 in a sample Store Catalog Application The image below shows the Catalog Listing page, which allows a user to page through a list of items in a store. JSF 2.0 Facelets XHTML instead of JSP For JSF 2.0, Facelets XHTML is the preferred way to declare JSF Web Pages. JSP is supported for backwards compatibility, but not all JSF 2.0 features will be available for views using JSP as their page declaration language. JSF 2.0 Facelets has some nice features like templating (similar in functionality to Tiles) and composite components, which I'm not going to discuss here but you can read about that in this article: http://www.ibm.com/developerworks/java/library/j-jsf2fu2/index.html and in this Tech Tip Composite UI Components in JSF 2.0. The Catalog application's resources JSF 2.0 standardizes how to define web resources. Resources are any artifacts that a component may need in order to be rendered properly -- images, CSS, or JavaScript files. With JSF 2.0 you put resources in a resources directory or a subdirectory. In your Facelets pages, you can access css files with the , javascript files with the , and images with the JSF tags. The list.xhtml uses the The Catalog application uses a resource bundle to contain the static text and error messages used by the Facelets pages. Putting messages in a resource bundle makes it easier to modify and internationalize your Application text. The messages are in a properties file in a java package directory. Title=Pet Catalog Next=Next Previous=Prev Name=Name The resource bundle is configured in the faces-config.xml File (you don't need any other configuration in the faces-config.xml for JSF 2.0, as explained later you no longer have to configure managed beans and navigation with XML). web.WebMessages msgs The List.xhtml facelets page uses a JSF dataTable component to display a list of catalog items in an html table. The dataTable component is useful when you want to show a set of results in a table. In a JavaServer Faces application, the UIData component (the superclass of dataTable) supports binding to a collection of data objects. It does the work of iterating over each record in the data source. The HTML dataTable renderer displays the data as an HTML table. In the list.xhtml web page the dataTable is defined as shown below: (Note: Red colors are for Java EE tags, annotations code, and Green is for my code or variables) The value attribute of a dataTable tag references the data to be included in the table. The var attribute specifies a name that is used by the components within the dataTable tag as an alias to the data referenced in the value attribute of dataTable. In the dataTable tag from the List.jsp page, the value attribute points to a list of catalog items. The var attribute points to a single item in that list. As the dataTable component iterates through the list, each reference to dataTableItem points to the current item in the list. JSF 2.0 Annotations instead of XML configuration The dataTable's value is bound to the items property of the catalog managed bean. With JSF 2.0 managed beans do not have to be configured in the faces-config.xml file, you annotate the managed beans instead as shown below: @ManagedBean @SessionScoped public class Catalog implements Serializable { By convention, the name of a managed bean is the same as the class name, with the first letter of the class name in lowercase. To specify a managed bean name you can use the name attribute of the ManagedBean annotation, like this: @ManagedBean(name = "Catalog"). This Catalog ManagedBean items property is defined as shown below: private List items = null; public List getItems() { if (items == null) { getPagingInfo(); items = getNextItems(pagingInfo.getBatchSize(), pagingInfo.getFirstItem()); } return items; } The getItems() method returns a List of item objects. The JSF dataTable, supports data binding to a collection of data objects. The dataTable object is modeled as a collection of row objects that can be accessed by a row index. The APIs provide mechanisms to position to a specified row index, and to retrieve an object that represents the data that corresponds to the current row index. The Item properties name, imagethumburl, and priceare displayed with the column component: The column tags represent columns of data in a dataTable component. While the dataTable component is iterating over the rows of data, it processes the UIColumn component associated with each column tag for each row in the table. The dataTable component iterates through the list of items (catalog.items) and displays the item (var="row") attribute value. Each time UIData iterates through the list of items, it renders one cell in each column. The dataTable and column tags use facet to represent parts of the table that are not repeated or updated. These include headers, footers, and captions. Java EE 6: JSF 2.0, EJB 3.1, and Java Persistence API (JPA) 2.0 The Catalog ManagedBean annotates the field private ItemFacade itemFacade; with @EJB , which causes an itemFacade EJB to be injected when the managed bean is instatiated. The Catalog getNextItems method calls the ItemFacade Stateless EJB which uses the Java Persistence API EntityManager Query object to return a list of items. @ManagedBean @SessionScoped public class Catalog implements Serializable { @EJB private ItemFacade itemFacade; public List getNextItems(int maxResults, int firstResult) { return itemFacade.findRange(maxResults, firstResult); } EJB 3.1 No-interface local client View With EJB 3.1, local EJBs do not have to a implement separate interface, that is, all public methods of the bean class are automatically exposed to the caller. Simplified Packaging With Java EE 6, EJBs can be directly packaged in a WAR file just like web components. The ItemFacade EJB uses the Java Persistence API EntityManager Query object to return a list of items. The ItemFacade EJB annotates the field private EntityManager em; with @PersistenceContext , which causes an entity manager to be injected when it is instatiated. @Stateless public class ItemFacade { @PersistenceContext(unitName = "catalogPU") private EntityManager em; public List findRange(int maxResults, int firstResult) { Query q = em.createQuery("select object(o) from Item as o"); q.setMaxResults(maxResults); q.setFirstResult(firstResult); return q.getResultList(); } The Java Persistence Query APIs are used to create and execute queries that can return a list of results. The JPA Query interface provides support for pagination via the setFirstResult() and setMaxResults() methods: q.setMaxResults(int maxResult) sets the maximum number of results to retrieve. q.setFirstResult(int startPosition) sets the position of the first result to retrieve. In the code below, we show the Item entity class which maps to the ITEM table that stores the item instances. This is a typical Java Persistence entity object. There are two requirements for an entity: annotating the class with an @Entity annotation. annotating the primary key identifier with @Id Because the fields name, description.... are basic mappings from the object fields to columns of the same name in the database table, they don't have to be annotated. The O/R relationships with Address and Product are also annotated. For more information on defining JPA entities see Pro EJB 3: Java Persistence API book. @Entity public class Item implements java.io.Serializable { @Id private Integer id; private String name; private String description; private String imageurl; private String imagethumburl; private BigDecimal price; @ManyToOne private Address address; @ManyToOne private Product product; public Item() { } public String getName() { return name; } public void setName(String name) { this.name = name; } ... } The Catalog ManagedBean pages through the list of Items by maintaining the PagingInfo.firstItem and PagingInfo.batchSize attributes and passing these as parameters to the getNextItems(firstItem, batchSize) method. The catalog's scope is defined with the annotation @SessionScoped, a JSF Managedbean with session scope will be stored in the session meaning that the bean's properties will stay alive for the life of the Http Session. A JSF commandButton is used to provide a button to click on to display the next page of items. The commandButton tag is used to submit an action event to the application. This commandButton action attribute references the catalog Managed bean next() method which calculates the next page's first row number and returns a logical outcome String, which causes the list.xhtml page to display the next page's list . The catalog next method is defined as shown below: public String next() { if (firstItem + batchSize < itemCount()) { firstItem += batchSize; } return "list"; } JSF 2.0 Simplified Navigation The JavaServer Faces 2.0 NavigationHandler convention adds .xhtml to the logical outcome of the action method (in this example list) and loads that file, in this case, it loads the list .xhtml page after this method returns. If the action doesn't begin with a forward slash (/), JSF assumes that it's a relative path. You can specify an absolute path by adding the slash like this "/items/list". A JSF commandLink is used to provide a link to click on to display a page with the item details. This commandLink action attribute references The catalog showDetail() method: With JSF 2.0 you can now specify parameters in method expressions. The dataTable row object associated with the selected link is passed as a parameter in the "#{catalog.showDetail(row)}" method expression. The Catalog showDetail() method gets the item data from the input parameter, and returns a string which causes the detail.xhtml page to display the item details : public String showDetail(Item item) { this.item = item; return "detail"; } The JavaServer Faces NavigationHandler adds .xhtml to the logical outcome of the action, detail and loads that file. In this case, the JavaServer Faces implementation loads the detail.xhtml page after this method returns. The detail.xhtml uses the outputText component to display the catalog ManagedBean's item properties: GlassFish v3 is a lightweight server OSGi-based; Embedded API; RESTful admin API; Lightweight and fast startup; iterative development cycle "edit-save-refresh browser": Incremental compile of all JSF 2.0 artifacts when you save. Auto-deploy of all web or Java EE 6 artifacts Session retention: maintain sessions across re-deployments Conclusion This concludes the sample application which demonstrates a pet catalog web application which uses Java EE 6, GlassFish v3 and MySQL. Running the Sample Application Download and install NetBeans IDE 6.8 M1 with GlassFish v3 b57 (Glassfish v3 preview is Java EE 6 Preview) , and MySQL Community Server . Follow these instructions to set up a jdbc-driver for MySQL. (Normally this is already setup with Glassfish, but I got an errror message with Glassfish v3 b57 that it was missing) Download the sample code. Unzip the catalog.zip file which you downloaded, this will create a catalog directory with the project code. Create the Pet Catalog database In order to run the sample code you first have to create the Pet Catalog database and fill in the Item table. Start NetBeans IDE Ensure that GlassFish is registered in the NetBeans IDE, as follows: Click the Services tab in the NetBeans IDE. Expand the Servers node. You should see GlassFish v2 in the list of servers. If not, register GlassFish v2 as follows: Right-click the Servers node and select Add Server. This opens an Add Server Instance wizard. Select GlassFish v2 in the server list of the wizard and click the Next button. Enter the location information for the server and click the Next button. Enter the admin name and password and click the Finish button. Start the MySQL or Java DB database as follows: Click the Services tab in the NetBeans IDE. Expand the databases node. You should see the Java DB database in the list of databases. If you have installed the MySQL server database, you should also see the MySQL database in the list of databases.. Note: Java DB comes bundled with Netbeans, you can download MySQL separately. Right-mouse click on the Java DB or MySQL server database and select Start. If you installed MySQL, set the properties of the MySQL server database as follows: Right-click on the MySQL server database and select Properties. This opens the MySQL Server Properties dialog box, as shown in Figure 8. Figure 8. MySQL Server Basic Properties In the Basic Properties tab, enter the server host name and port number. The IDE specifies localhost as the default server host name and 3306 as the default server port number. Enter the administrator user name, if not displayed, and the administrator password -- the default administrator password is blank. Click the Admin Properties tab. Enter an appropriate path in the Path/URL to admin tool field. You can find the path by browsing to the location of a MySQL Administration application such as the MySQL Admin Tool. Enter an appropriate path in the Path to start command. You can find the path by browsing to the location of the MySQL start command. To find the start command, look for mysqld in the bin folder of the MySQL installation directory. Enter an appropriate path in the Path to stop command field. You can find the path by browsing to the location of the MySQL stop command. This is usually the path to mysqladmin in the bin folder of the MySQL installation directory. If the command is mysqladmin, in the Arguments field, type -u root stop to grant root permissions for stopping the server. The Admin Properties tab should look similar to Figure 9. Figure 9. MySQL Server Administration Properties Click the OK button. Right-click on the MySQL server or Java DB database and select Start. Create the petcatalog database as follows: Right-mouse click on the Java DB or MySQL server database and select Create Database. This will open a create Database window. Enter the database name catalog for Java DB or petcatalog for MySQL. For Java DB enter userid password app app as shown below: Click O.K. to accept the displayed settings. Create the tables in the catalog database as follows: Underneath Databases you should see a database connection for the petcatalog database. For example MySQL: or Java DB: Right-mouse click on the petcatalog connection and select Connect. Right-mouse click on the petcatalog connection and select Execute Command. This will open up a SQL command window. Copy the contents of the catalog.sql file in the catalog directory and paste the contents into the SQL command window, as shown in below: Click the Run SQL icon (Ctrl+Shift+E) above the SQL command window. Note: It is ok to see this: "Error code -1, SQL state 42Y55: 'DROP TABLE' cannot be performed on 'ITEM' because it does not exist. Line 2, column 1" . This just means you are deleting a table that does not exist. If you need to delete and recreate the tables you will not see this message the second time. View the data in the Pet Catalog database Item table as follows: Underneath Databases you should see a database connection for the petcatalog database. For example MySQL: or Java DB: If the database connection is broken like in the following diagram: Right-mouse click on the petcatalog connection and select Connect. as shown below: if prompted for a password, for MySQL leave it blank, for JavaDB enter user app password app. Expand the Tables node below the petcatalog database in the Services window. You should see the item table under the Tables node. You can expand the item table node to see the table columns, indexes, and any foreign keys, as shown in below : Figure 12. An Expanded Table Node You can view the contents of a table or column by right-clicking the table or column and selecting View Data as shown below: Figure 13. Viewing the Contents of a Table Follow these instructions to Create a JDBC Connection pool and JDBC resource. Name the pool mysql_petcatalog_rootPool and the jndi resource jdbc/petcatalog. Note: you do not have to create a JDBC connection pool and resource if you use the Netbeans wizard to generate JPA entities from database tables as described in this article GlassFish and MySQL, Part 2: Building a CRUD Web Application With Data Persistence. Open the catalog/setup/sun-resources.xml file and verify that the property values it specifies match those of the petcatalog database and jdbc resources you created. Edit the property values as necessary. Running the Sample solution: If you want to run the sample solution, you have to create the catalog database tables first as described above. Open the catalog project as follows: In NetBeans IDE, click Open Project in the File menu. This opens the Open Project dialog. Navigate in the Open Project dialog to the catalog directory and click the Open Project button. In response, the IDE opens the catalog project. You can view the logical structure of the project in the Projects window (Ctrl-1). Run the catalog by right-clicking on the catalog project in the Projects window and selecting Run Project. The NetBeans IDE compiles the application, deploys it on Glassfish, and brings up the default page in your browser. (at http://localhost:8080/catalog/). For more information see the following resources: A Sampling of EJB 3.1 Java EE 6 Technologies JSF 2.0 Home page Project Mojarra SDN JavaServer Faces Page JSF 2 fu, Part 1: Streamline Web application development Composite UI Components in JSF 2.0 Creating Your First Java EE 6 Application Roger Kitain's Blog (co-spec lead for JSF 2.0) Ed Burns's Blog (co-spec lead for JSF 2.0) Cay Horstmann's Blog: JSF 2.0 specifying parameters in method expressions JavaServer Faces 2.0 Ref Card Jim Driscoll's Blog Top reasons why GlassFish v3 is a lightweight server Beginning Java™ EE 6 Platform with GlassFish™ 3: From Novice to Professional Book
May 23, 2023
by Carol McDonald
· 16,460 Views · 1 Like
article thumbnail
Java Developers, Don't Throw Out Your Mac Yet: Apple Will Contribute To OpenJDK
Finally, some very good news for the Java community. For those who were worried about the future of Java on OSX, don't worry: Apple have just announced that they will be working with Oracle on the OpenJDK project. Apple will contribute most of the key components, tools and technology required for Java SE 7 on Mac OS X. Following the announcement that Apple would not longer be maintaining further JDK updates on Mac OS X beyond the most recent update, this comes as very welcome news to Oracle: “We are excited to welcome Apple as a significant contributor in the growing OpenJDK community,” said Hasan Rizvi, Oracle’s senior vice president of Development. “The availability of Java on Mac OS X plays a key role in the cross-platform promise of the Java platform. The Java developer community can rest assured that the leading edge Java environment will continue to be available on Mac OS X in the future. Combined with last month’s announcement of IBM joining the OpenJDK, the project now has the backing of three of the biggest names in software.” And of course, Apple are happy to keep Java developers happy: “We’re delighted to be working with Oracle to insure that there continues to be a great version of Java on the Mac,” said Bertrand Serlet, Apple’s senior vice president of Software Engineering. “The best way for our users to always have the most up to date and secure version of Java will be to get it directly from Oracle.” Apple also confirmed that Java SE 6 will continue to be available from Apple for Mac OS X Snow Leopard® and the upcoming release of Mac OS X Lion. Java SE 7 and future versions of Java for Mac OS X will be available from Oracle. Henrick has already blogged about this, answering some of questions that are likely to be on developers minds: Q: When will JDK 7 be available for OSX? A: My expectation is that we will release on current supported platforms first, and that OSX support will follow later. The JDK 7 schedule can not easily accomodate large changes like the addition of a new platform. This is great news. Once again we're seeing Oracle listening to community comments, and it's good to see that recent pleas to Apple to contribute their work to the OpenJDK haven't fallen on deaf ears. Kudos to both companies for a continued committment to Java.
May 23, 2023
by James Sugrue CORE
· 13,406 Views · 1 Like
article thumbnail
Java Creator James Gosling Joins AWS
After a long career at Sun Microsystems and an impressive run at Liquid Robotics (a Boeing company subsidiary), the pioneer of the Java programming language has officially joined the team at AWS.
May 23, 2017
by John Vester CORE
· 44,616 Views · 52 Likes
article thumbnail
Java Annotated Monthly — September 2019
Check out the latest happenings in Java over the last month.
September 4, 2019
by Trisha Gee
· 23,775 Views · 15 Likes
article thumbnail
Java Annotated Monthly – September 2016
Come see what's new in the world of Java according to JetBrains. There is a lot going on so be sure to give this a read through!
Updated September 9, 2016
by Trisha Gee
· 3,984 Views · 4 Likes
article thumbnail
Java Annotated Monthly — October 2019
Summer is truly behind us, and it's time to get down to business.
October 8, 2019
by Trisha Gee
· 9,778 Views · 7 Likes
article thumbnail
Java Annotated Monthly — October 2018
Want to learn more about the latest happenings in Java? Check out this monthly post looking at the Java 11, news in Kotlin and Spring, conferences, and more.
Updated October 16, 2018
by Trisha Gee
· 9,545 Views · 5 Likes
  • Previous
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • ...
  • Next

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: