Bagi yang pengen membuat calculator dengan menggunakan bahasa java silahkan download sorce code nya disini:
http://www.ziddu.com/download/8242962/calculator.rar.html
Aplikasi ini dibuat dengan menggunakan NetBeans.
Selamat Berkreasi
Calculator dengan Java - NetBeans
by Son Rokhaniawan Perdata, S.T | 2:15 PM in Java, Netbeans, Project | comments (0)
Java and MySQL Store Prosedure Programming I
by Son Rokhaniawan Perdata, S.T | 10:25 AM in Java, Netbeans | comments (0)
Pada DBMS MySQL ada sebuah service dimana kita dapat membuat sebuah prosedur tersimpan di MySQL sendiri serta menjalankan prosedure tersebut kapan sesuai keinginan kita.
Ketika mata kuliah PBO. Aku sering mengamati dosen-dosen mengajarkan tentang koneksi Java ke MySQL. Dan pertanyaanku, mengapa sintaq SQL selalu diketik di list program java? mengapa tidak di tulis di MySQL sendiri?
Jadi kita bisa memisahkan pemrograman Java dan pemrograman MySQL sendiri-sendiri.
di atas adalah uraian singkat dari store prosedure.
*>>Ok. kita masuk ke MySQL. Bagaimana cara membuat sebuah store prosedure dengan parameter inputan.
Buatlah sebuah Form seperti pada gambar di bawah.
*>>pertama kita import libary jdbc MySQL.
masuk ke halaman source
setelah itu ketik pada awal program.
import java.sql.*;
import javax.swing.JOptionPane;
*>>lanjut......pada "Public F_input" silakan di ketik code di bawah.(F_Input adalah nama class yang kalian buat)
public F_input() {
initComponents();
try
{
//meload driver
Class.forName("com.mysql.jdbc.Driver");
//membuat koneksi
conn=DriverManager.getConnection("jdbc:mysql://locahost/db","root","");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
*>>Mari kita buat sebuah method dengan nama "masukan_data" seperti code di bawah.
void masukan_data(){
try{
CallableStatement sp_inputbarang =
conn.prepareCall("{call SP_InputBarang(?,?,?,?,?,?,?)}");
sp_inputbarang.setString(1, txtkodebarang.getText());
sp_inputbarang.setString(2, txtnama.getText());
sp_inputbarang.setDouble(3, Double.parseDouble(txthargabeli.getText()));
sp_inputbarang.setDouble(4, Double.parseDouble(txtdiskon.getText()));
sp_inputbarang.setDouble(5, Double.parseDouble(txthargaprivate.getText()));
sp_inputbarang.setDouble(6, Double.parseDouble(txthargajual.getText()));
sp_inputbarang.setInt(7, Integer.parseInt(txtstock.getText()));
sp_inputbarang.execute();
JOptionPane.showMessageDialog(null, "Simpan data berhasil");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
*>> Buat Method Kosong untuk mengosongkan textField.
void kosong()
{
txtkodebarang.setText("");
txtnama.setText("");
txthargabeli.setText("");
txtdiskon.setText("");
txthargaprivate.setText("");
txthargajual.setText("");
txtstock.setText("");
}
*>> Klik Kanan pada textField Diskon-->Events-->Focus-->FocusLost. Dan Ketikkan code di bawah.
private void txtdiskonFocusLost(java.awt.event.FocusEvent evt) {
double hargabeli = Double.parseDouble(txthargabeli.getText());
double diskon = Double.parseDouble(txtdiskon.getText());
double hargaprivate = (hargabeli - (hargabeli * (diskon/100)));
txthargaprivate.setText(""+hargaprivate);
}
*>> Klik Kanan pada button Save-->Action-->ActionPerformed. Dan Ketik code di bawah.
private void btsaveActionPerformed(java.awt.event.ActionEvent evt) {
masukan_data();
kosong();
}
*>> Begitu juga pada button Cancel.
private void btcancelActionPerformed(java.awt.event.ActionEvent evt) {
kosong();
}
*>>Dan pada button Close.
private void btcloseActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
}
untuk lebih jelasnya bisa download source code di sini.
cara penggunaan :
- file mysql.sql di import dari SQLYog. (SQLYog bisa didownload di sini)
- folder test_StoreProsedure open lewat Netbeans.
!!!---SELAMAT BEREKSPERIMEN---!!!
SumberGlassFish Project - Java Persistence Example
by Son Rokhaniawan Perdata, S.T | 12:30 AM in Project | comments (0)
Overview
This is a very simple example that uses only 2 entities - a Customer and an Order, with OneToMany relationships between them. The Customer and the Order classes are Plain Old Java Classes (POJOs). These classes, as well as the code that manipulates POJO instances, can be used without any changes in Java SE or Java EE environment.
Accessing an EntityManagerFactory and an EntityManager depends on the environment and is described in more details below.
We will create a customer and two related orders, find the customer, and navigate from the customer to its orders, and then merge and remove all the objects. All these operation will be performed using Java Persistence API and require JDK 5.0.
Click here to get the ZIP file with the complete Java SE example as a netbeans project. This example works with Java DB or with Oracle.
Click here to get the ZIP file with the complete Java SE example. This example works with Oracle.
Click here to get the ZIP file with the complete Java EE example.
Refer to Java Persistence API document of JSR-220: Enterprise JavaBeansTM 3.0 Specification for further details on annotations and APIs.
Check example sources for the necessary import statements.
Mapping to Existing Tables
In the first example we will use only two tables:CUSTOMER |
ID |
NAME |
ORDER_TABLE |
ORDER_ID |
SHIPPING_ADDRESS |
CUSTOMER_ID |
CUSTOMER_ID column in the ORDER_TABLE is the Foreign Key (FK) to the ID column from the CUSTOMER table. The files sql/tables_oracle.sql and sql/tables_derby.sql in the example contains DDL to create both tables for Oracle and Apache Derby.
POJO Classes
Now let's look at the corresponding persistence classes. Both entities in this example use property based persistence. There is no access annotation element on the entity, so it defaults to access=PROPERTY. This is the reason why @Column annotation is specified for the get methods and not for the fields. The classes that are used as an argument or a return type between a remote client and a container must implement java.io.Serializable interface.The POJO classes in the examples belong to an entity package.
Customer
The Customer entity is mapped to the CUSTOMER table, and looks like this:@Entity
public class Customer {
private int id;
private String name;
private Collection
orders;
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public
String
getName() {
return name;
}
public void setName(String
name
) {
this.
name
=
name
;
}
@OneToMany(cascade=ALL, mappedBy="customer")
public Collection getOrders() {
return orders;
}
public void setOrders(Collection newValue) {
this.orders = newValue;
}
}
Note that there are no @Table and @Column annotations. This is possible because the persistence provider will use the default rules to calculate those values for you. See chapter 9 of the Java Persistence API Specification for detailed rules of the mapping annotations.
Order
The Order entity is mapped to the ORDER_TABLE table. It requires both @Table and @Column mapping annotations because table and column names do not match class and properties names exactly. @Column annotations are specified for the corresponding get methods:@Entity
@Table(name="ORDER_TABLE")
public class Order {
private int id;
private String address;
private Customer customer;
@Id
@Column(name="ORDER_ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="SHIPPING_ADDRESS")
public
String
get
Address
() {
return
address
;
}
public void set
Address
(String
address
) {
this.
address
=
address
;
}
@ManyToOne()
@JoinColumn(name="CUSTOMER_ID")
public Customer getCustomer
() {
return
customer
;
}
public void setCustomer
(
Customer
customer
) {
this.
customer
=
customer
;
}
}
Note that Customer and Order have bidirectional relationships between the entities.
Persisting POJO Entities
Now, let's create new instances, set up the relationships and persist all of them together using the CASCADE option that we set on the Customer entity. This code must be executed in a context of an active transaction.
// Create new customer
Customer customer0 = new Customer();
customer0.setId(1);
customer0.setName("Joe Smith");
// Persist the customer
em.persist(customer0);
// Create 2 orders
Order order1 = new Order();
order1.setId(100);
order1.setAddress("123 Main St. Anytown, USA");
Order order2 = new Order();
order2.setId(200);
order2.setAddress("567 1st St. Random City, USA");
// Associate orders with the customer.
Note that the association must be set on both sides of the relationship: on the customer side for the orders to be persisted when transaction commits, and on the order side because it is the owning side:
customer0.getOrders().add(order1);
order1.setCustomer(customer0);
customer0.getOrders().add(order2);
order2.setCustomer(customer0);
When this transaction commits, all three entities will be persisted in the database.Query and Navigation
We'll use a new EntityManager to do the query, but will execute the query without an active transaction:// Create new EntityManager
em = emf.createEntityManager();
Query q = em.createQuery("select c from Customer c where c.name = :name");
q.setParameter("name", "Joe Smith");
Our query is supposed to return a single customer, so we will use the Query method getSingleResult() to execute the query. This method would throw an exception if there is no or more than one matching customers.
Customer c = (Customer)q.getSingleResult();
Now let's verify that the orders were also created by navigating from the Customer.
You can print the orders, but we'll just check the size:
Collection orders = c.getOrders();
if (orders == null || orders.size() != 2) {
throw new RuntimeException("Unexpected number of orders: "
+ ((orders == null)? "null" : "" + orders.size()));
}
Merge and Removal of Persistent Instances
To remove an instance, it must be managed by this EntityManager. The code below uses a customer 'c' that had been detached from its persistence context. Removal of the Customer also removes related orders because of the CASCADE option set on the corresponding relationship. This code must be executed in a context of an active transaction. // Merge the customer to the new persistence context
Customer c0 = em.merge(c);
Note that merge() is not a void operation. It returns back a managed copy of the argument (and its related objects). Only this copy can be used for EntityManager operations.
// Delete all records
em.remove(c0);
Putting It All Together
Using in Java SE
First, we need to create an EntityManagerFactory that we will use in the example. An EntityManagerFactory is created once for each PersistentUnit. Persistent unit in this example is called "pu1". // Create EntityManagerFactory for persistent unit named "pu1"
// to be used in this test
emf = Persistence.createEntityManagerFactory("pu1");
For each business method in the example, a new EntityManager is created:
// Create new EntityManager
em = emf.createEntityManager();
If a transaction required, it is started: // Begin transaction
em.getTransaction().begin();
And then the business logic is executed in a separate business method:// Business logic
mybusinessmethod(...);
If transaction has been started it must be committed:
// Commit the transaction
em.getTransaction().commit();
And EntityManager should always be closed if it won't be used again:
// Close this EntityManager
em.close();
Java SE client code in this example is located in the class client.Client.To run the test, you need to create META-INF/persistence.xml file in the classpath. Copy META-INF/persistence.xml.template file from the classes directory in the example to META-INF/persistence.xml and populate the values of the corresponding properties with the database settings that you are using. Note that persistence-unit name is set to "pu1" and all entity classes are explicitly listed.
Add your database driver and classes directory from the unzipped example to the classpath, load the tables into the database, then run:
java -javaagent:${glassfish.home}/lib/toplink-essentials-agent.jar client.Client
Using the Java SE Example in Netbeans
- Download Netbeans 5.5 and install the bundle
- Download and install Java DB/Derby if you plan on using Java DB/Derby instead of Oracle.
- Configure Netbeans to use Java DB/Derby by following the steps in this tutorial .
- Install the JAVA SE Persistence Example project .
Configuring the JDBC driver
To configure the JDBC driver to be used when running the project, right-click on the project, select properties. Click on the libraries and then click on the 'Add JAR/Folder' button to add the jars for the JDBC driver being used. In the example below, the Java DB/Derby JDBC Client Driver is added.
Creating the tables
Scripts are provided to create the tables needed for the example for either Java DB/Derby or Oracle.
Note:If you are using Oracle, go to the runtime tab, click databases and then right click drivers to add the Oracle driver so that it can be used with the SQL Editor.
- Create a connection to the database
- expand the drivers folder and right click on the Oracle or Java DB/Derby driver and create a connection to the database. For Java DB/Derby you can enter: jdbc:derby://localhost:1527/testDB;create=true and enter APP for the username and password.
- If you are using Java DB/Derby and the server is not started, Select Tools->Java DB Database ->Start Java DB server
- Open the appropriate sql script by typing Ctrl-O or selecting 'Open File' from the file menu. The SQL scripts are in the sql directory of the project.
- Select the connection to use (for Java DB/Derby you can use jdbc:derby://localhost:1527/testDB;create=true [APP on APP] .
- Click the Run SQL icon on the right of the Connection drop-down box. This will open the Connect dialog. Enter the password for your connection. . Click OK to connect and run the SQL script.
Configuring the persistence unit
To configure the persistence unit for the sample, click on source packages and then click on META-INF. Double click on persistence.xml. Your configuration should look like the following if you are using Java DB/Derby:
Running the project:
To run the the sample application. Right click on the project and select 'Run Project'.
Using in Java EE
In a Java EE container, the client code will not create an EntityManagerFactory - it is done by the container.There are several option to get a hold of an EntityManager:
- An EntityManagerFactory or an EntityManager can be injected by the container or looked up in JNDI.
- An EntityManager instance can be acquired from an EntityManagerFactory via the corresponding API call.
- A JTA EntityManager participates in the current JTA transaction that is either controlled by the container or by a user via javax.transaction.UserTransaction API.
- A resource-local EntityManager uses the same Java Persistence API as in Java SE environment to control its transactions.
@PersistenceContext(unitName="pu1")
private EntityManager em;
Transaction boundaries set to container-managed defaults.
The client code from the Java SE example is now divided between a Stateless Session Bean ejb.TestBean (implements ejb.Test remote business interface), which contains the business logic (i.e. exactly the same business methods as the Java SE client), and an application client client.AppClient that calls the corresponding methods and prints the output:
// Persist all entities
System.out.println("Inserting Customer and Orders... " + sb.testInsert());
// Test query and navigation
System.out.println("Verifying that all are inserted... " + sb.verifyInsert());
// Get a detached instance
Customer c = sb.findCustomer("Joe Smith");
// Remove all entities
System.out.println("Removing all... " + sb.testDelete(c));
// Query the results
System.out.println("Verifying that all are removed... " + sb.verifyDelete());
In the Java EE environment META-INF/persistence.xml does not need to list persistence classes, or the
To test the example, unzip it and deploy ex1-ee.ear file:
${glassfish.home}/bin/asadmin deploy --retrieve . ex1-ee.ear
Then execute the appclient script:
${glassfish.home}
/bin/appclient -client ./ex1-eeClient.jar -mainclass client.AppClient
The Result
This is the output (after several extra log messages) that will be printed:Inserting Customer and Orders... OK
Verifying that all are inserted... OK
Removing all... OK
Verifying that all are removed... OK
- 26 January 2009 - Apache Cactus 1.8.1 Released
- 14 June 2008 - Apache JMeter 2.3.2 Released
- 11 April 2008 - Apache Cactus 1.8.0 Released
- 30 November 2007 - Apache JMeter 2.3.1 final Released
- 15 November 2007 - HttpComponents TLP move
- 07 November 2007 - HttpComponents HttpClient 4.0-alpha2 Released
- 03 November 2007 - Slide is retired
- 09 October 2007 - HttpComponents HttpCore 4.0-alpha6 Released
- 29 September 2007 - Apache JMeter 2.3 final Released
- 05 September 2007 - Apache JMeter 2.3RC4 Released
- 22 August 2007 - Jakarta Commons HttpClient 3.1 Released
- 20 July 2007 - HttpComponents HttpClient 4.0-alpha1 Released
- 11 July 2007 - Apache JMeter 2.3RC3 Released
- 08 July 2007 - Commons CLI 1.1 Released
- 04 July 2007 - HttpComponents HttpCore 4.0-alpha5 Released
- 02 July 2007 - Commons IO 1.3.2 Released
- 18 June 2007 - Jakarta Commons JCI 1.0 Released
- 08 June 2007 - POI TLP move
- 07 June 2007 - Turbine TLP move
- 06 June 2007 - Jakarta JCS 1.3 Released
The sample test is modeled on the Sun Certification for JavaTM 2 Programmer exam. The test has 59 questions and needs to be executed in 2 hours. The real exam may be a little tougher than this. You need to score 36 correct answers to clear the real exam. The first 50 questions of the mock exam are valid for both 1.2 and 1.4 versions of the exam. The remaining 9 questions are only useful if you are taking the SCJP 1.2 exam. Please let me know if you find any issues with the test. The site also offers another mock exam. The remaining questions are related to AWT, event classes, and layout managers. These topics are not included in 1.4 version of the exam.
public class xyz {
public static void main(String args[]) {
for(int i = 0; i < 2; i++) {
for(int j = 2; j>= 0; j--) {
if(i == j) break;
System.out.println("i=" + i + " j="+j);
}
}
}
}
java test 2
Select the one correct answer. public class test {
public static void main(String args[]) {
Integer intObj=Integer.valueOf(args[args.length-1]);
int i = intObj.intValue();
if(args.length > 1)
System.out.println(i);
if(args.length > 0)
System.out.println(i - 1);
else
System.out.println(i - 2);
}
}
public class test {
public static void main(String args[]) {
int i, j=1;
i = (j>1)?2:1;
switch(i) {
case 0:
System.out.println(0);
break;
case 1:
System.out.println(1);
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
}
}
}
public class test {
public static void main(String args[]) {
int i=0, j=2;
do
{
i=++i;
j--;
}
while(j>0);
System.out.println(i);
}
}
public class test {
public static void main(String args[]) {
int i=1, j=1;
try {
i++;
j--;
if(i/j > 1)
i++;
}
catch(ArithmeticException e) {
System.out.println(0);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(1);
}
catch(Exception e) {
System.out.println(2);
}
finally
{
System.out.println(3);
}
System.out.println(4);
}
}
public class test {
public static void main(String args[]) {
int i=1, j=1;
try {
i++;
j--;
if(i == j)
i++;
}
catch(ArithmeticException e) {
System.out.println(0);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(1);
}
catch(Exception e) {
System.out.println(2);
}
finally {
System.out.println(3);
}
System.out.println(4);
}
}
public class test {
public static void main(String args[]) {
String s1 = "abc";
String s2 = "abc";
if(s1 == s2)
System.out.println(1);
else
System.out.println(2);
if(s1.equals(s2))
System.out.println(3);
else
System.out.println(4);
}
}
public class test {
public static void main(String args[]) {
String s1 = "abc";
String s2 = new String("abc");
if(s1 == s2)
System.out.println(1);
else
System.out.println(2);
if(s1.equals(s2))
System.out.println(3);
else
System.out.println(4);
}
}
public class test {
public static void main(String args[]) {
int i = 1;
do {
i--;
}
while (i > 2);
System.out.println(i);
}
}
void method X() {
String r = new String("abc");
String s = new String("abc");
r = r+1; //1
r = null; //2
s = s + r; //3
} //4
Assuming the above declaration, which of the following statements would compile. Select the one correct answer.
void method() { }
Which of the following are legal prototypes in a derived class of this class. Select the two correct answers.
int i = 0, j = 1;
public class test {
public static void main(String args[]) {
int i;
float f = 2.3f;
double d = 2.7;
i = ((int)Math.ceil(f)) * ((int)Math.round(d));
System.out.println(i);
}
}
public class test {
public static void main(String args[]) {
String str1="abc";
String str2="def";
String str3=str1.concat(str2);
str1.concat(str2);
System.out.println(str1);
}
}
Answers to Sample Test 1
Making Http Simple Server With Java
by Son Rokhaniawan Perdata, S.T | 12:16 AM in Java, Tutorial | comments (2)
Praktikum's task Network and Apparatus Mathematics moves secondly be make one http simple server at localhost. With utilize SocketServer's function, therefore gets to be made one server which will wait “panggilan†on port 80 (HTTP). And will send html's code while called.
SocketServer works in one looping that perpetual to wait marks sense connection to go to port 80 on localhost. There is 4 constructor on SocketServer for example:
- public ServerSocket(int port) throws BindException, IOException
- public ServerSocket(int port, int queueLength) throws BindException, IOException
- public ServerSocket(int port, int queueLength, InetAddress bindAddress) throws IOException
- public ServerSocket( ) throws IOException // Java 1.4
n Java, to make one server gets to be done by trick as follows:
- One serverSocket a new one is made deep one given port (in this case port 80) utilizing constructor of one SocketServer.
- Then serverSocket waits until mark sense coming connection through port has already is determined previous utilize accept's function().
- Then depends from server type, well utilize getInputStream's function(), getOutputStream's function(), or both of ala function goes together to get input and output stream in order to gets communication with client.
- Server and client gets communication / get interaction until its time hang up connection.
- Server, Client or both hangs up connection
- Server returns to to step 2 and waiting until marks sense succeeding connections.
And attachment source's following code that I takes from praktikum's module meagrely modifies to be able to qualify as one http server.