Quantcast
Channel: Take A Rest For A moment!
Viewing all 40 articles
Browse latest View live

Seven Deadly Sins of Database Design

$
0
0

How to avoid the worst problems in database design.
by Jason Tiret

Several factors can lead to a poor database design -- lack of experience, a shortage of the necessary skills, tight timelines and insufficient resources can all contribute. In turn, poor database design leads to many problems down the line, such as sub-par performance, the inability to make changes to accommodate new features, and low-quality data that can cost both time and money as the application evolves.
I constantly hear from data professionals that if you don’t get the data right, nothing else matters. However, many times it is the tail (i.e., the application) that’s wagging the dog rather than the dog wagging the tail. The database just comes along for the ride as the application grows in scope and functionality.
Addressing some simple data modeling and design fundamentals can greatly alleviate most, if not all, of these concerns. In this article we’ll focus on seven common database design “sins” that can be easily avoided and suggest ways to correct them in future projects:
  1. Poor or missing documentation for database(s) in production
  2. Little or no normalization
  3. Not treating the data model like a living, breathing organism
  4. Improper storage of reference data
  5. Not using foreign keys or check constraints
  6. Not using domains and naming standards
  7. Not choosing primary keys properly

Sin #1: Poor or missing documentation for database(s) in production

Documentation for databases usually falls into three categories: incomplete, inaccurate, or none at all. To make matters worse, it is almost never centralized in one place. Without proper, centralized documentation, understanding the impact of a change is difficult at best, impossible at worst. This causes developers, DBAs, architects, and business analysts to scramble to get on the same page. They are left up to their own imagination to interpret the meaning and usage of the data.
Additionally, developers may think that the table and column names are descriptive or self explanatory enough to understand the usage of the data (more on this with Sin #6). However, as the workforce turns over, if there is no documentation in place, knowledge of the systems can literally walk out the door leaving a huge void that is impossible to fill. Even starting bottom-up with just the physical information can alleviate the issue of lack of documentation tremendously.
The best approach is to place the models into a central repository and spawn automated reports because despite minimal effort everyone benefits. Producing a central store of models is only half the battle, though. Once that is done, executing validation and quality metrics will enhance the quality of the models over time. As your level of governance increases, you can extend what metadata is captured in the models.

Sin #2: Little or no normalization

There are times to denormalize a database structure to achieve optimized performance, but sacrificing flexibility will paint you in a corner. Despite the long-held belief by developers, one table to store everything is not always optimal. The “one table” approach may make data access easier, but invariably there will be many NULLs for columns that do not apply to a record, and special application code will be needed to handle it. Another common mistake is repeating values stored in a table. This can greatly decrease flexibility and increase difficulty when updating the data.
Understanding even the basics of normalization adds flexibility to a design while reducing redundant data. The first three levels of normalization are usually sufficient for most cases:
  • First Normal Form: Eliminate duplicate columns and repeating values in columns
  • Second Normal Form: Remove redundant data that apply to multiple columns
  • Third Normal Form: Each column of a table should be dependent on the primary identifier


Figure 1: Denormalized structure

Figure 2: Normalized equivalent
The first normal form tells us to break off Address and Phone information into their own tables with identifiers. Following the second normal form, we break off Zip Code information into its own table so that it is not duplicated for each address. Consideration should be made for City and State information as well, but that might be a case where performance over duplication wins. Third normal form would have us look at Organization Name and Industry in the Customer table and put those into their own tables since they are not functionally dependent on the Customer ID. The same would apply to City and State Code in the ZIP Code table.

Sin #3: Not treating the data model like a living, breathing organism

I have seen numerous examples of customers performing the modeling up front, but once the design is in production, all modeling ceases. It is always preferable to design first then build. It is proven that errors corrected in the design phase are significantly less costly than those fixed after production.
The sin arises when changes creep into the database due to critical production issues. Inevitably, the model is then left languishing on the side if there is not a process to update the model along with the database. As more changes occur in the database, the model becomes useless.
Undocumented data can also lead to security and compliance risks, poor understanding of future changes and the inability to adapt to future needs of the business. Although the design-then-build practice may be a utopia that is never reached, the changes need to find their way back to the model.

Sin #4: Improper storage of reference data

I see two main problems with reference data. It is either stored in many places or, even worse, embedded in the application code. It is almost never captured in the data model with the rest of the documentation. This causes huge problems when a reference value needs to change. Reference values provide valuable documentation which should be communicated. Your best chance is often via the model. It may not be practical to store reference values in the data model if you have large volumes, but there is no excuse not to point to them from the model. The key is to have it defined in one place and used in other places. 

 Sin #5: Not using foreign keys or check constraints

I hear customers complain all the time about the lack of referential integrity (RI) or validation checks defined in the database when reverse engineering databases. For older database systems, it was thought that foreign keys and check constraints slowed performance, thus, the RI and checks should be done via the application. This might have been the case in the past, but DBMSs have come a long way. 
 The ramifications on data quality if the data is not validated properly by the application or by the database can be substantial. If it is possible to validate the data in the database, you are better off doing it there. Error handling will be drastically simplified and data quality will increase as a result. 

 Sin #6: Not using domains and naming standards

Domains and naming standards are probably two of the most important things you can incorporate into your modeling practices. Domains allow you to create reusable attributes so that the same attributes are not created in different places with different properties. It is extremely important to have a common set that everyone can use across all models. Naming standards allow you to clearly identify those attributes consistently.
Having a set of standards also ensures consistency across systems and promotes readability of models and code. You don’t want short, cryptic names that users need to interpret. Given the advanced nature of the latest vendor releases, the days of limited column length name are over when building new databases. Always have a common set of classwords to identify key types of data and use modifiers as needed. 

 Sin #7: Not choosing primary keys properly

I was once told by a senior data architect that “When choosing a primary key, you’d better get it right because changing it down the line will be a royal pain.” Sure enough, later I worked with a different customer who had the un-enviable chore of managing a migration project because a system used Social Security number as a primary key for individuals. They found out the hard way that SSNs are not always unique and not everyone has one.
The simplest principle to remember when picking a primary key is SUM: Static, Unique, Minimal. It is not necessary to delve into the whole natural vs. surrogate key debate; however, it is important to know that although surrogate keys may uniquely indentify therecord, they do not always unique identify the data. There is a time and a place for both, and you can always create an alternate key for natural keys if a surrogate is used as the primary key. 
Jason Tiret is the director of product management for modeling and design solutions for Embarcadero (www.embarcadero.com), a provider of multi-platform database tools and developer software.

Setting cron to run a script every second

$
0
0
Even though this thread is 2 years old, it still comes up in a google search for this topic. I didn't like the solution, so I thought I'd post what I've come up with, for future google searches:

Purpose : run /usr/local/bin/scriptname every 30 seconds, where 30 is configurable


wrapper script (/usr/local/bin/wrapper)
tabs lost in posting

Quote:
#!/bin/bash
# Wrapper

# Initialisation
if [ "$1" == "" ]; then
exit 1
fi

interval=$1


next=$(date +%M | awk -v interval=$interval '{ print int($0 * 60 % interval) }')

if [ $next -gt 0 ]; then
next=$(echo $next | awk -v interval=$interval '{print interval - $0}')
fi


for i in $(seq $next $interval 59)
do
(sleep $i; /usr/local/bin/scriptname) &
done
crontab:
Quote:
*/1 * * * * /usr/local/bin/wrapper 30

explaination is bellow :

Except for the %m, which of course is kinda dumb, it works.

the value of next is the number of seconds since the last time the command ran.

If it's greater than zero, that means the next run is in (interval-next) seconds, so we calculate that
If it's zero, it runs now.

The for loop is next run to 59 seconds with 'interval' steps.

For instance, if interval is 7 (just for arguments sake, it's a too short interval, 30 or greater would start to make sense), the output of the for loop would be, depending on the moment in time:

1
8
15
22
29
36
43
50
57
So it would set backgroup sleep jobs for those numbers.

So 20 seconds would indeed be, x, x+20, x+40, where x would be 0, so 0, 20, 40
So a job every 20 seconds.

Now it's debatable if you would want to do this, but I've got a user asking to run a job every 30 seconds. It's not live yet, so not sure how the impact on the system will be.


(Copied from duplicate thread, to get them all in one...
Other thread was closed by moderator.)



maybe you could use this scritp running in background:

Code:

#!/bin/bash

###
### Sample background worker script
### for linuxquestions.org written
### by Florian Harbich (user doc.nice)
###
### Free for use or modification, even if
### useless in this variant...
###

TERMINATORFILE="/var/run/backgroundworker.ctl"
GOON=1
while [ $GOON ]; do
[ -f "$TERMINATORFILE" ] && GOON=0
# do your repeated stuff instead of logger syslog sample here
logger -t BGWorker -- "hi! I'm happy to tell you i'm still alive"
sleep 1
done
rm -f "$TERMINATORFILE"


Since it was hard for me to find a solution, I thought I'd post here.
Here is how I figured out how to do it on 80 seconds.


*/4 * * * * /scripts/80_second_script
*/4 * * * * sleep 80; /scripts/80_second_script
*/4 * * * * sleep 160; /scripts/80_second_script

Line 1 runs at 0,240,480,etc...
Line 2 runs at 80,320,560, etc...
Line 3 runs at 160,400,640, etc...

Put that all together you get
0,80,160,240,320,400,480,560,640, etc...

You can do this with any number, but the more often the multiples of your number cross the multiples of 60 the less lines you have to write.

Hope this helps someone.

Sharing Koneksi Internet Dengan Linux

$
0
0
Dengan kata lain, pada pembahasan ini akan dibahas bagaimana caranya membuat Gateway/PC Router menggunakan Ubuntu server. Pada pembahasan ini diasumsikan ubuntu telah diinstal.
Ada dua fungsi connection sharing yang berlaku dalam hal ini, yaitu:
Pertama, fungsi dimana klien/workstation dalam LAN dapat mengakses server-server yang ada di internet. Fungsi kedua yaitu yang memungkinkan server-server yang kita miliki dalam LAN untuk dapat diakses dan/atau melayani klien/workstation yang ada ditempat lain melalui satu koneksi Internet yang kita miliki.
Berikut ini langkah-langkah untuk membagi koneksi internet menggunakan ubuntu server:

1. Pastikan anda telah melakukan seting IP Address secara statis untuk kedua ethernet card.
 

Pada contoh ini ethernet card pertama (eth0) adalah ethernet card yang terhubung ke internet dengan IP Addres public 118.98.212.43, dan IP Address kedua (eth1) adalah ethernet card yang terhubung ke jaringan lokal (LAN) dengan IP Address 192.168.2.1.

2. Install DNS Server (opsional untuk pembelajaran, aslinya tidak perlu, dibahas pada modul yang lain).

3. Instal paket iptables:
$sudo apt-get install iptables

4. Edit file /etc/sysctl.conf
$sudo nano /etc/sysctl.conf
Uncomment (hapus tanda #) pada baris berikut ini:
#net.ipv4.conf.default.forwarding=1

4. Nyalakan funsi IP Forwarding pada server:
$sudo sysctl -w net.ipv4.conf.default.forwarding=1
net.ipv4.conf.default.forwarding = 1

Simpan, kemudian lakukan perintah berikut ini:
$ sudo /sbin/sysctl –p

5. ketikkan
$ echo 1> /proc/sys/net/ipv4/ip_forward


6. ketikkan
$ iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE


Kalo koneksi yang bersumber pada Wifi LAN (device yang digunakan untuk koneksi internet bersumber dari mana / Device yang terhubung langsung dengan internet.

tambahkan perintah berikut

iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE

Menggunakan Cron-nya Mysql (Event Scheduler)

$
0
0
Inti tutorial ini adalah handle periodical activity seperti yang biasanya dilakukan dengan cron

Kadang dalam sebuah aplikasi yang berhubungan dengan database (khususnya MySQL) membutuhkan sebuah query yang harus dijalankan secara periodic, misalkan setiap satu bulan sekali, Mungkin kalau pengguna LINUX bisa pake JOB CRON kalau di WINDOWS pake Schedule Task. Di MySQL versi 5.1 fitur tersebut telah ada, istilahnya adalah Event Scheduler.
Sebelum memulai membuat sebaik nya dilihat dulu apakah feature schedule nya hidup atau tidak, cara memeriksa nya.


SHOW VARIABLES LIKE ‘event_scheduler’
+—————–+——-+
| Variable_name | Value |
+—————–+——-+
| event_scheduler | ON |
+—————–+——-+
1 row in set (0.02 sec)

Untuk menghidupkan MySQL Event Schedule ketikan perintah dibawah ini
SET GLOBAL event_scheduler = 1;
dan untuk mematikan nya
SET GLOBAL event_scheduler = 0;
 
MySQL Event Schedule terdiri dari beberapa macam, antara lain di bawah ini, sebelum mulai saya akan membuat sebuat tabel terlebih dahulu untuk keperluan demo Event Schedule ini

CREATE TABLE schedule_table (
no int(11) NOT NULL AUTO_INCREMENT,
des varchar(255) DEFAULT NULL,
time datetime NOT NULL,
PRIMARY KEY (no)
) 

1. EVENT SCHEDULER Berdasarkan tanggal dan waktu yg sudah di tentukan
CREATE EVENT event_name
ON SCHEDULE
AT {DATE AND TIME)
DO
{SQL COMMAND};

contoh di bawah ini membuat insert data ke schedule_table pada tgl 1 juni 2009 jam 18:06:49
CREATE EVENT event_name_1
ON SCHEDULE AT ’2009-06-01 18:06:49′
DO insert into schedule_table values (null, ‘sch 1′, now());
hasilnya:

select * from schedule_table;
+—-+——-+———————+
| no | des | time |
+—-+——-+———————+
| 1 | sch 1 | 2009-06-01 18:06:49 |
+—-+——-+———————+

2. EVENT SCHEDULER berdasarkan pengulangan waktu

CREATE EVENT event_name
ON SCHEDULE
EVERY {x}
{SECOND | MINUTE | HOUR | DAY | MONTH | YEAR | WEEK}
DO
{SQL COMMAND};

contoh dibawah ini akan melakukan insert data ke tabel schedule_table setiap satu menit

CREATE EVENT event_name_2
ON SCHEDULE EVERY 1 MINUTE
DO insert into schedule_table values (null, ‘sch 2′, now());

Hasilnya
+—-+——-+———————+
| no | des | time |
+—-+——-+———————+
| 2 | sch 2 | 2009-06-01 18:16:27 |
| 3 | sch 2 | 2009-06-01 18:17:27 |
| 4 | sch 2 | 2009-06-01 18:18:27 |
| 5 | sch 2 | 2009-06-01 18:19:27 |
| 6 | sch 2 | 2009-06-01 18:20:27 |
| 7 | sch 2 | 2009-06-01 18:21:27 |
| 8 | sch 2 | 2009-06-01 18:22:27 |
| 9 | sch 2 | 2009-06-01 18:23:27 |
| 10 | sch 2 | 2009-06-01 18:24:27 |
| 11 | sch 2 | 2009-06-01 18:25:27 |
+—-+——-+———————+
10 rows in set (0.01 sec)

untuk EDIT event schedule, formatnya di bawah ini

ALTER EVENT event_name
[ ON SCHEDULE schedule ]
[ RENAME TO event_name2 ]
[ DO sql_statement ]

contoh dibawah ini akan mengubah nama schedule dari event_name_2 ke event_name_3
ALTER EVENT event_name_2
ON SCHEDULE EVERY 2 MINUTE
RENAME TO event_name_3
DO insert into schedule_table values (null, ‘sch 3′, now());

untuk HAPUS event schedule formatnya seperti dibawah ini

DROP EVENT event_name ;
contoh dibawah ini adalah menghapus schedule event_name_3
DROP EVENT event_name_3;

contoh penggunaan pada presensi:

DELIMITER &&
CREATE EVENT e_updateStatus
ON SCHEDULE
EVERY 1 SECOND
ON COMPLETION NOT PRESERVE ENABLE
DO
  BEGIN
    UPDATE matkul SET matkul.status=2  WHERE TIME_TO_SEC(matkul.jamcheckoff)<=TIME_TO_SEC(CURTIME()) AND (matkul.status=1);
    UPDATE matkul SET matkul.status=3  WHERE TIME_TO_SEC(matkul.jamakhir)<=TIME_TO_SEC(CURTIME()) AND matkul.status=2;
  END&&
DELIMITER;

How To Install MySQL Workbench

$
0
0

MySQL Workbench adalah sebuah perangkat aplikasi berbentuk visual yang dipergunakan untuk mengelola basis data. Perangkat aplikasi ini biasa digunakan oleh seorang arsitek basis data, pengembang basis data, serta administator basis data. MySQL Workbench menyediakan model data, pengembangan SQL, dan peralatan administrasi yang komperhensif untuk konfigurasi server basis data, administrasi pengguna, dan masih banyak lagi. MySQL Workbench tersedia pada platform Windows, Linux dan Mac OS.

$sudo apt-get update
$sudo apt-get upgrade
$sudo apt-get install mysql-workbench


Keren sekali ni aplikasi kalo sudah pernah coba phpmyadmin yang webbased, kalian akan merasakan kemudahan yang sangat joss...
yang pasti dibandingkan dengan menggunakan aplikasi webbased adalah refresh page nya yang sangat membosankan.

How To Install Eclipse Kepler On Linux Mint 13 Maya

$
0
0
Setelah ane menggunakan step ini, jadi punya anggapan kenapa koq jadi gampang gini ya install aplikasi di Linux :)

Semuanya tinggal ditempatkan didalam suatu folder sebagai tempat install, dan arah kan Launcer ke folder tersebut. Thats it,..


Step 1 » Install java JDK or JRE
sudo apt-get install openjdk-7-jdk
 
Step 2 » Download latest copy from here http://www.eclipse.org/downloads/?osType=linux

Step 3 » Move the downloaded package to /opt directory
sudo mv eclipse-SDK-4.2.2-linux-gtk.tar.gz /opt

Step 4 » Extract the package
sudo tar -xvf /opt/eclipse-SDK-4.2.2-linux-gtk.tar.gz

Step 5 » Create a new desktop file eclipse.desktop in /usr/share/applications/ and add the below lines .
[Desktop Entry]
Name=Eclipse
Type=Application
Exec=/opt/eclipse/eclipse
Terminal=false
Icon=/opt/eclipse/icon.xpm
Comment=Integrated Development Environment
NoDisplay=false
Categories=Development;IDE
Name[en]=eclipse.desktop

Step 6 » Simply drag this eclipse.desktop file to the launcher.
Check this link : install eclipse in ubuntu 12.04 ini sama dengan untuk Linux Mint 13 (Maya)

Setting up IDE and creating a cross platform Qt Python GUI application

$
0
0

Python Qt eclipse Pydev post imageThis is meant to be a comprehensive guide on how to get started coding a cross platform GUI application using python.
For achieving this we will use Eclipse with the plug-in PyDev and PyQT which is python bindings for the cross platform UI framework QT. My aim is to make this guide as thorough as possible so if you already know some of the following parts please just skip them.
If anything is missing or you find something unclear please leave a comment and I will correct it.
The outline of we are going to do is:
  • Download and install Python
  • Download and install PyQt
  • Download and install Eclipse
  • Download and install Pydev
  • Getting code completion for PyQT in Eclipse
  • Creating files and coding a tiny PyQT GUI

Download and install Python


First you need python installed on your computer. I suggest you download Python 2.6.5 because it is widely supported. For Windows users, use the windows installer suitable for your system. They will suggest you install Python in c:\python26 and I have done so aswell. Usually I don’t like cluttering my c:\ with catalogs but for this I make an exception.
After install is done it is nice to make python available in the command prompt regardless of the catalog you are using. Do this by adding “;c:\python26″ to PATH in your environment variables. You find your environment variables by right clicking on “My computer”, select properties and go to advanced settings.
You should now be able to go to your command prompt and type python to start python. This is used when you are installing new libraries and trying out python commands.

Download and install PyQt4


PyQt is a set of Python bindings for Qt. It is needed to make Qt classes available in Python. For more info on PyQt check out the What is PyQt section at Riverbank Computing.
Update – Install SIP
As Will Stich (thanks again Will!) commented below you first need to download and install SIP to get PyQt to work . Do this by downloading SIP from the Riverbanks Computing download page. In this tutorial we will use sip-4.10.5.zip.
Extract the contents of the zip where ever you please. I will put it in c:\sip-4.10.5 in this example.
When that is done you can open the command prompt (run->cmd) and go to your SIP folder (c:\sip-4.10.5). Type “c:\python26\python.exe configure.py” and SIP will be configured.
Installing PyQt is pretty straight forward. Go to the PyQt4 download page and download the windows installer for the PyQt version that corresponds to your python version you are using. In this example we use PyQt-Py2.6-gpl-4.7.3-2.exe.
The windows installer will installer should do all the work for you so if you installed Python in C:\Python26 you should be fine by just pressing next all through the installer. When done your PyQt4 installation should be saved in C:\Python26\Lib\site-packages\PyQt4.

Download and install Eclipse


Eclipse installation is pretty straight forward. I chose Eclipse IDE for Java developers but I think any version works fine for our purpose. Unpack into program files or where you wherever. Heck you could probably put it on a USB stick if you want to.

Download and install Pydev


Pydev is a great plugin for Eclipse that allows python syntax highlighting and code completion. It can be installed in two ways; either you download and unpack the files into the plug-in folder in your Eclipse directory or you use the installation manager in Eclipse. I suggest you use the installation manager!
So, start eclipse, choose a workspace you want to use and go to “Help -> Install new software…”. Press “Add…” and enter a name of the plugin (Pydev) and the pydev plugin update URL: http://pydev.org/updates/ (the url might change so if it doesn’t work, go to the pydev site). Follow the steps in the installation guide. You might get a bunch of dialog boxes warning you about stuff, I just pressed yes all the way and it worked fine.
The Eclipse intallation manager, installing PyDev
When that is done we can create our first Python project with Pydev. Your “File -> New” menu should look like the image below. Select “Pydev Project”.

A new dialog box will open. Write the name of your project in the “Project name:” field. If this is the first time you create a Python project you will need to configure your Python interpreter. Do so by clicking on the “Click here to configure an interpreter not listed” link. A new dialog box will open that looks like the one in the image below.
Before finding the Python interpreter
Press the “Auto Config” box and Pydev will (hopefully) find your installed python interpreter. The auto config dialog findings should open in a new dialog that looks like the one below. Select the ones selected in the figure below and click “OK”.
Auto finding the Python Interpreter
Now this might be over pedagogical but your Python Interpreters box should look like the figure below. Press OK we are done with the interpreters!
The Python Interpreters found
Now press “Finish” to create your Pydev project. Eclipse and Pydev will create a src folder and show the referenced Python interpreter.

Getting code completion for PyQT in Eclipse

Not having code completion while learning something new or using a new library is a pain so lets try to avoid that! To get code completion for your PyQT library we need to add it to the external libraries included in the project. Go to the menu Project -> Properties -> PyDev PYTHONPATH -> External Libraries -> Add source folder. Add the path where you have installed your PyQT files. They are most likely, if you used the windows installer, locaded in C:\Python26\Lib\site-packages\PyQt4. If all is well you should have something that looks like the figure below.
Setting up the PyQT in external libraries

Creating files and coding a tiny PyQT GUI

Now we are done with the development environment things! Lets try if this thing works! First thing we need to do is to add a main module. Do this by right clicking on your src-folder select new -> Pydev Module. In the “Name” field enter “Main”  and in the template. You could name the file anything you like, it will work either way, but it is in my opinion always nice to have a startup file called Main. It should look like the image below.
Creating a new PyDev Project
This will create a new main module for you with the code below
Now, since this just is a small example I will put all the code in this file. If you would to start a bigger project you would probably want to create a new file for your user interface.
Anyway, we want to create a QT GUI so lets start doing that! I’m going to describe this process by first showing you the end result and then I’m going to describe what the different rows do afterwords. Here is what we will end up with:
The tiny PyQT GUI running in Windows
And this is the code you need to get it working:
Now lets see what that means. Lets start from the top!
This imports the Qt libraries needed for this little application. We only needed the QtGui so that is what we imported.
This is your Main class. This line creates the class called HelloPython and says that it should inherit from QtWidget which is the base Qt class for all user interface objects.
This is the class constructor and it will be called when you instantiate the object. These two rows will make this class have no parent and thus making it the main class.
These lines are QT specific. First one Label is instantiated for displaying text and then one LineEdit for entering text in. Then a GridLayout is set up where we put the Label and LineEdit. Lastly we set the layout in on the QWidget and set the window title.
This is the main python module and this line of code makes this a standalone application.
sys is a necessary import for sys.exit(app.exec_()) later in this file.
A QT application must have a application object. The sys.argv are command line arguments passed on to the application.
Instantiation of the QtWidget and displaying it for the user.
Here we enter the main loop and all events are handled. On exit() the loop ends and sys.exit() makes sure the exit of the application is handled correctly by the system.

Conclusion

With this guide I hope you can easily get started programming GUI applications in Python. Again, if you find that something is unclear, missing or plain wrong please leave a comment or contact us in some other way and we will fix it. I will continue posting solutions I use for the problems I encounter while developing in QT so please subscribe to our RSS feed or follow us on twitter.
If you want to read more visit the learning python blog or read zetcode’s python tutorials. You should also visit the PyQT class reference library at www.riverbankcomputing.co.uk.

Updates

5 May 2010

There is a great set of tutorials (and a link to this post) that you can use for further learning at the diotavelli PyQTWiki

Ref : http://popdevelop.com/2010/04/setting-up-ide-and-creating-a-cross-platform-qt-python-gui-application/

Connection To Microsoft SQL Server Database From Python

$
0
0

Free tools are great, but the world ain't all sunshine and rainbows. Sometimes, we may need to connect to a Microsoft SQL Server database from one of our Python applications running under Linux. Fortunately, there are ways to achieve this.
I am assuming we got this:
  • • A Microsoft SQL Server installation running under Windows. I tested this using Microsoft SQL Server 2008 R2 Express, but hopefully this will work with other versions as well.
  • Ubuntu Linux. I am using 12.04 LTS.
Without further ado, here are the steps you should follow to get this working.

1. SQL Server setup

Your SQL Server installation must be setup to allow external connections. If the DB is not administered by you this might not be a problem, but in case you do have administrator level access and need to do it yourself, read here.
Now you must have setup a port in which SQL Server is listening. Remember it.
Make sure you are not blocked by Windows firewall or such when you attempt to connect to the Windows computer. Attempting a telnet will help us check if there are connection problems. For example, try running telnet from Ubuntu and check the connection doesn't fail.
Regarding authentication, I have only tried this with the sa login enabled (ie. not using Windows Authentication). You may read on how to do that here.

2. Install required packages under Ubuntu

These are the things we are going to need:
  • FreeTDS is is a set of libraries that allows programs to natively talk to Microsoft SQL Server databases. It's what we usually call a driver.
  • UnixODBC acts as a driver manager and is the implementation of the ODBC API.
  • pyodbc is a Python 2.x and 3.x module that allows you to use ODBC to connect to almost any database.
From a terminal, run:
sudo apt-get install unixodbc unixodbc-dev freetds-dev tdsodbc
From the Virtualenv of our Python application (if you are not using one, you should!) run pip install pyodbc.

3. Setup server in FreeTDS's settings

Edit the file /etc/freetds/freetds.conf and replace placeholders appropriately. Note that we are calling our server sqlserver.
[sqlserver]
    host =
    port =
    tds version = 7.0
After this you can test the connection with this command:
tsql -S sqlserver -U  -P 
note : tsql not build in freetds, you can add with apt-get install freetds-bin

Then run some SQL Server command to make sure everything works fine. For example you may run a DB query like this:
select * from .dbo.
go

If it worked, it will print the results of the query. Quit with Ctrl+D.

4. Setup unixODBC to use FreeTSD & add a data source

First, run odbcinst -j to know where our configuration files are located. We will need to edit two files: the "drivers" and "system data source". I assume they are /etc/odbcinst.ini and /etc/odbc.ini respectively, but the output of the command will tell you this.

Edit /etc/odbcinst.ini like this:
[FreeTDS]
Description = TDS driver (Sybase/MS SQL)
# Some installations may differ in the paths
#Driver = /usr/lib/odbc/libtdsodbc.so
#Setup = /usr/lib/odbc/libtdsS.so
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
CPTimeout =
CPReuse =
FileUsage = 1
If the paths for Driver and Setup do not work in your installation, you can find where these files are located by running find / -name "libtds*".
Edit /etc/odbc.ini like this, to add a data source named sqlserverdatasource:
[sqlserverdatasource]
Driver = FreeTDS
Description = ODBC connection via FreeTDS
Trace = No
Servername = sqlserver
Database =
Now you may test the connection to out data source works by running isql -v sqlserverdatasource .

5. Connect to our data source from a Python application

If everything is fine, with the help of pyodbc it should be really easy! You may try the following snippet:
importpyodbc
dsn ='sqlserverdatasource'
user =''
password =''
database =''
con_string ='DSN=%s;UID=%s;PWD=%s;DATABASE=%s;'%(dsn, user, password, database)
cnxn =pyodbc.connect(con_string)


That should be it :-)

ref : http://www.tryolabs.com/Blog/2012/06/25/connecting-sql-server-database-python-under-ubuntu/

Allowing SQL Server Connection From Network

$
0
0
Upon database modeling with the ORM feature, you always need to connect to the server. However, you may encounter problem in connecting to the SQL server, which is great obstruction to your modeling. In this article, we will provide ways to help you to check whether your configurations for connecting to SQL Server are correct.
There are three significant aspects that uses may neglect, leading the failure of the connection to the SQL Server.

Server Settings

Enable TCP/IP

  1. Open your SQL Server Configuration Manager.
    open sql config manager
  2. Expand SQL Server Network Configuration and select Protocols for SQLEXPRESS.
    sql network config express
  3. Take a look at TCP/IP, which requires to be Enabled. If yours is Disabled, right-click on it and select Enable in the popup menu.
    enable tcp ip
  4. Also, you may take a look at the Port setting of your server. Right-click on TCP/IP and select Properties in the popup menu.
    right click tcp ip properties
  5. Click the IP Address tab in the TCP/IP Properties dialog box.
    click ip address tab
  6. Under IPAll section, you can see the TCP Port (default: 1433) and you can edit the port of your server.
    tcp port

Correct Hostname and Port

Back to your VP application, have a check in your database configuration and see if you have entered the Hostname and Port correctly.
  1. Select Tools > Object-Relational Mapping (ORM) > Database Configuration in the VP application.
    tool orm db config
  2. Select the Language, server and the driver in the Database Configuration dialog box.
    select lang server driver
  3. Enter Hostname, which must be either the IP address of your computer or your computer name.
    db config hostname
  4. Enter the port of your SQL Server. It's 1433 by default, but if you have edited the port for your SQL Server or running on other named instance, you need to enter the corresponding port.
    db config port

Allow Remote Connection

Your need to make sure that remote connection to your SQL Server is enabled.
  1. Startup your SQL Server.
    start sql server
  2. Right-click on the server and select Properties in the popup menu.
    right click sql server properties
  3. In the Server Properties dialog box, select Connections.
    select connection
  4. Check the checkbox of Allow remote connections to this server.
    check allow remote connection

Diagnosis of Connection in Command Line

You can diagnose whether your SQL Server is in-use by the command line. For Windows Vista, Telnet is not installed by default, you need to install it before running the telnet command.

Install Telnet Client in Windows Vista

  1. Open Control Panel from the Start Menu.
    control panel
  2. Select Programs in the Control Panel.
    select programs
  3. Under Programs and Features, select Turn Windows features on or off.
    select turn on off win features
  4. Scroll down to find the option Telnet Client, check this option and press OK.
    select telnet client

Run Telnet Command

  1. Shutdown your SQL Server first and launch the command prompt.
  2. Enter telnet %host% %port% in the command prompt, where %host% and %port% are the host and port of your SQL Server.
    enter telnet msg in command
  3. Press Enter to see if it can call the SQL Server. If telnet can communicate with the host and port you specified, it will show a blank dialog box. This means your SQL Server is able to be connected.
    telnet succeed connect to sql
    If it fails to connect to your SQL Server, there will be message of the failure.
    telnet cannot connect to sql

Authentication Method

Make sure that you are using the appropriate authentication method in connecting to your SQL Server.
  1. Startup your SQL Server.
    start sql server
  2. Right-click on the server and select Properties in the popup menu.
    right click sql server properties
  3. In the Server Properties dialog box, select Security.
    select security
  4. Normally, the Server Authentication is set to SQL Server and Windows Authentication Method.
    select sql and win auth
  5. If you are using the Windows Authentication Method, you will need another connection URL in order to connect to the SQL Server.
    • Java (SQL Server 2005 Microsoft Driver)
      jdbc:sqlserver://localhost;databaseName=AdventureWorks;integratedSecurity=true;
    • Java (jDTS)
      jdbc:jtds:://[:][/];domain=XXX
      where = sqlserver
      ** Domain Server is required. If no domain server is available, please try domain=workgroup
    • .NET:
      Server=%HOST%,%PORT%;Database=%DATABASE%;User ID=%USER_ID%;Password=%PASSWD%;Trusted_Connection=Yes;Domain=%WINDOW_DOMAIN%
  6. Get back to the VP application and enter the URL in the Connection String section in the Database Configuration dialog box.
    enter url in connection string

Adapter File

While you are using can non-compatible adapter file, you will not be able to connect to the server.
The simplest way to get the compatible adapter file is let our application download it for you:
  1. Select Tools > Object-Relational Mapping (ORM) > Database Configuration.
    tool orm db config
  2. After you have chosen the language, server and driver, click the Download and Update button beside the Adapter file field.
    dl adapter file
  3. VP will download the adapter file for you.
    adapter file downloaded
If your still fail to connect to SQL server with all the above steps of checking, please contact support-team@visual-paradigm.com for technical suppot.

How to Create Scheduled Events in MySQL

$
0
0
This is the third and last article in a series about database automation with triggers and events. If you’ve not done so already, please read How to Create Triggers in MySQL which introduces many of the concepts discussed here.
An event is similar to a trigger. However, rather than running in response to a data change, events can be scheduled to run any number of times during a specific period. In effect, it’s a database-only cron job.
Events have been supported in MySQL since version 5.1. They are ideal for maintenance tasks such as data archiving or report generation which can be scheduled during off-peak times.

Our Database Plan

Our blog database has a problem. Old posts are marked as deleted rather than being removed from the `blog` table. Our table will grow indefinitely and become slower over time. We could purge the old posts but that would remove them forever. Therefore, we’ll move posts and their associated audit records to archive tables. The archive tables can grow without affecting the speed of the main web application and we can undelete old posts if necessary.
Two archive tables are required:
  • `blog_archive`: identical to the `blog` table except it does not require a deleted flag or an auto-incrementing ID.
  • `audit_archive`: identical to the `audit` table except the timestamp is not automatically generated and it does not require an auto-incrementing ID.
The following SQL creates both tables:

CREATE TABLE `blog_archive` (
`id` mediumint(8) unsigned NOT NULL,
`title` text,
`content` text,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Blog posts archive';
--
CREATE TABLE `audit_archive` (
`id` mediumint(8) unsigned NOT NULL,
`blog_id` mediumint(8) unsigned NOT NULL,
`changetype` enum('NEW','EDIT','DELETE') NOT NULL,
`changetime` timestamp NOT NULL,
PRIMARY KEY (`id`),
KEY `ix_blog_id` (`blog_id`),
KEY `ix_changetype` (`changetype`),
KEY `ix_changetime` (`changetime`),
CONSTRAINT `FK_audit_blog_archive_id` FOREIGN KEY (`blog_id`) REFERENCES `blog_archive` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Starting MySQL’s Event Scheduler

MySQL events are executed by a special event scheduler thread. It’s disabled by default so use the following MySQL command can determine whether it’s running:

SHOW PROCESSLIST;
If the scheduler is running, at least two rows will be shown and one will have its user field set to “event_scheduler”. If only one row is returned, the scheduler is disabled and events will not run.
You can ensure the scheduler starts when MySQL is launched with the command-line option --event-scheduler=ON or setting event_scheduler=ON in your MySQL configuration file (my.cnf or my.ini on Windows).
Alternatively, you can start the scheduler from the MySQL command line:

SET GLOBAL event_scheduler = ON;

Creating an Event

We require a scheduled event which:
  • Copies posts from `blog` to `blog_archive` when the deleted flag is set to 1.
  • Copies the associated audit entries for those posts from `audit` to `audit_archive`.
  • Physically deletes archived posts from the `blog` table. Referential integrity has been defined with a foreign key so all associated audit entries for those posts will also be removed.
Assuming you have MySQL rights to create events, the basic syntax is:

CREATE EVENT `event_name`
ON SCHEDULE schedule
[ON COMPLETION [NOT] PRESERVE]
[ENABLE | DISABLE | DISABLE ON SLAVE]
DO BEGIN
-- event body
END;
The schedule can be assigned various settings, e.g.
  • Run once on a specific date/time:
    AT ‘YYYY-MM-DD HH:MM.SS’
    e.g. AT ’2011-06-01 02:00.00′
  • Run once after a specific period has elapsed:
    AT CURRENT_TIMESTAMP + INTERVAL n [HOUR|MONTH|WEEK|DAY|MINUTE]
    e.g. AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
  • Run at specific intervals forever:
    EVERY n [HOUR|MONTH|WEEK|DAY|MINUTE]
    e.g. EVERY 1 DAY
  • Run at specific intervals during a specific period:
    EVERY n [HOUR|MONTH|WEEK|DAY|MINUTE] STARTS date ENDS date
    e.g. EVERY 1 DAY STARTS CURRENT_TIMESTAMP + INTERVAL 1 WEEK ENDS ’2012-01-01 00:00.00′
An event is normally dropped once its schedule has expired (ON COMPLETION NOT PRESERVE). Set ON COMPLETION PRESERVE to prevent that behavior. The MySQL CREATE EVENT Syntax documentation provides further details.
We can now define our event (remembering to set the DELIMITER first). We’ll set it to run every week starting on a Sunday morning:

DELIMITER $$

CREATE
EVENT `archive_blogs`
ON SCHEDULE EVERY 1 WEEK STARTS '2011-07-24 03:00:00'
DO BEGIN

-- copy deleted posts
INSERT INTO blog_archive (id, title, content)
SELECT id, title, content
FROM blog
WHERE deleted = 1;

-- copy associated audit records
INSERT INTO audit_archive (id, blog_id, changetype, changetime)
SELECT audit.id, audit.blog_id, audit.changetype, audit.changetime
FROM audit
JOIN blog ON audit.blog_id = blog.id
WHERE blog.deleted = 1;

-- remove deleted blogs and audit entries
DELETE FROM blog WHERE deleted = 1;

END */$$

DELIMITER ;
This is a simple example but you could add more functionality, e.g. only move posts which were deleted at least 1 month ago and purge all archieved posts over 1 year old. I hope you’ve enjoyed this series and are considering database triggers and events in your next project.


Reference : http://www.sitepoint.com/how-to-create-mysql-events/

How to show Datepicker on Twitter Bootstrap

$
0
0

twitter bootstrap akhir-akhir ini mulai digemari untuk membangun sebuah website template, pada perkembangannya saat ini twitter bootstrap telah mencapai versi 3.0.3 dan anda bisa mendapatkannya di official sitenya getbootstrap.com. twitter bootstrap juga menyediakan datepicker dengan menggunakan jquery, dengan begitu akan lebih mudah mempercantik tampilan website kita dengan banyak fitur yang diberikan twitter bootstrap.
akan tetapi tahukah anda bahwa perbedaaan versi pada bootstrap 2 dan bootstrap versi 3 membuat datepicker tidak bekerja?. berikut cara menangani dan tutorial menambahkan datepicker pada bootstrap
untuk masalah kebutuhan, ketika ingin menggunakan datepicker bootstrap anda membutuhkan file berikut :
  1. jquery.js
  2. datepicker.js
  3. bootstrap.css
  4. datepicker.css
jika sudah ready, mari kita lihat kodenya ketika telah disisipkan file-file diatas :
 Datepicker author by @Andgaa <!--this css for bootstrap 

Date picker for Bootstrap

-->
dengan kode html sederhana diatas anda sudah bisa menampilkan datepicker pada halaman template berbasis bootstrap anda, akan tetapi hal tersebut tidak berlaku pada versi bootstrap yang berbeda. jika anda menggunakan bootstrap 3 maka tutorial tersebut kemungkinan tidak akan berjalan pada bootstrap 2, karena terdapat perubahan class pada css dan javascript pada bootstrap. berikut merupakan cara yang dapat anda ikuti untuk menamplikan bootstrap dari bootstrap versi 2 ke bootstrap versi 3
perubahan bootstrap versi 2 ke versi 3
1. Css
buka file datepicker.css, temukan line 176 -177 seperti berikut :
.input-append.date .add-on i,
.input-prepend.date .add-on i {
lakukan berubahan pada line 176-177 dengan kode sebagai berikut :
.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {
2. Javascript
buka file datepicker-bootstrap.js, temukan line 34 seperti berikut :
this.component = this.element.is('.date') ? this.element.find('.add-on') : false;
lakukan berubahan pada line 34 dengan kode sebagai berikut :
this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;
3. Markup
setelah itu, untuk bootstrap versi 2 anda dapat memanggilnya dengan contoh seperti diberikut:
buat fungsi javascript untuk disisipkan di halaman html seperti contoh berikut

kemudian tampilkan datepicker dengan menyisipkan tag input yang diberi id=”datepicker”, dimana ID ini akan mereferensi kefungsi javascript yang sudah kita buat diatas, seperti berikut :

sedangkan, untuk bootstrap versi 3 anda dapat memanggilnya dengan contoh seperti diberikut:
buat fungsi javascript untuk disisipkan di halaman html seperti contoh berikut

kemudian tampilkan datepicker dengan menyisipkan tag div dengan class=”input-group date”, dimana class ini akan mereferensi kefungsi javascript yang sudah kita buat diatas, seperti berikut :




sebagai bahan percobaan, anda dapat mendownload cara menampilkan datapicker pada bootstrap disini

Referensi

Trick Paly With Whatsapp

$
0
0
Instant messaging has played a big role in the Android ecosystem with more and more apps coming up everyday. The undisputed leader in the market though is WhatsApp, which allows you to chat with friends across borders and within for free, just as long as you have internet. The Facebook-owned IM is leading its competitors by a huge margin. But while you may be using WhatsApp, are you sure you know its tricks? See if you knew these!

WhatsApp, Android, Google, Google Play, Play Store, WhatsApp tricks, tips and tricks on WhatsApp, hide last seen on WhatsApp, WhatsApp mobile number

1. How To Install WhatsApp On Mobile Without Mobile Number

There are three steps for doing this,

- First make sure that your device is connected to the internet using the modem or the WiFi. Use the internet connection to download WhatsApp from the Play Store.

- Next you will be presented with the welcome screen. Follow the instructions that show on your screen until it asks you to confirm your mobile number.

- Put in a different mobile number and wait for Whats App to tell you that verification has failed. You will have to wait for 15 minutes or so before you get the text message on the mobile. Choose call me to validate Whats App on that mobile.

2. How to Send .apk & .exe, .pdf And More Files

If you download an app called CloudSend, you can send apk, exe, pdf and other files that are otherwise not allowed for sharing on Whats App.

3. How to Change Your WhatsApp Phone Number

Open the WhatsApp application on your phone and go to Settings. Here choose 'Change number on your WhatsApp'. All you need to do now is type in the old number and then the new number.

4. How to Stop Automatic Media Download in WhatsApp

You can do this by going to Settings, then choosing Chat Settings and then the Media auto-download option. It's easier now, but earlier you would have had to download an entire app to do this.

5. How to Disable WhatsApp Last Seen Time Stamp

This is one of the newest additions to WhatsApp. You need to go to Settings, Choose Privacy and then Last Seen. It allows you to show your last seen time stamp to contacts, everyone or no one.

6. How to Backup And Restore WhatsApp Chats

Although WhatsApp creates automatic backups of your chat conversations, you can also do this manually from the app's Settings menu. Go to Settings and choose Chat Settings. Here you will find the Backup Conversations option. Whats App also restores your messages when you use a new device. 


source : efy

How To Check MySQL Was Running With Python Script

$
0
0
Sering pertanyaan kita hinggap dipikiran kita, semakin dipikirkan semakin gak ngerti seringnya, apalagi sesuatu yang gak kliatan kerjanya seperti master kita satu ini MySQL Database. Awalnya ini script digunakan untuk keperluan deteksi pakah mysql jalan atao kagak, Kalo mysqlnya gak jalan tinggal dikasih script buat jalanin si doi, jadi kalo misalnya ada aplikasi yang mau masukin n baca data tinggal cek dulu apa mysql ini jalan ato kagak. 

Aplikasi yang baru dikembangin kebetulan pake python n jalan di Raspberry Pi Rev B, dan rencanya ini nanti dikasih di crontab nya cron buat di cek setiap menit untuk memastikan database jalan dengan sempurna, karena ane juga gak ngerti script python mungkin sering juga gua browse sana sini, eee gua nemu juga di internet script ajaib ini.

Manfaatin subprocess yang ada di Python langsung memberikan perintah melalui shell/terminal. Di raspberry penggunaan perintah ini gak perlu pake memasukkan pasword dari sudo yang dilakukan kalo memang dibutuhkan untuk menjalakn proses dengan authorisasi Super user.

Cara paling mudah untuk membuat ini bekerja adalah sebagai berikut

Script :

import subprocess
import string

msqlr = subprocess.Popen("sudo /usr/sbin/netstat -al".split(), stdout=subprocess.PIPE).stdout
grep = subprocess.Popen(["/usr/bin/grep", "mysql"], stdin=msqlr, stdout=subprocess.PIPE).stdout
msqlrLines = grep.read().split("\n")
vals = map(string.strip, msqlrLines[0].split())
print vals
if vals[-1] in ("LISTENING", "LISTEN"):
    print "OK - MySQL is running."
else:
    print "Not OK - MySQL is not running."


Yang dibawah ini mungkin agak berbeda, kalo kalian ingin mereset MySQL jalankan peritah berikut dengan cript python :

Shell script to restart MySQL server if it is killed or not workin


    #!/bin/bash
    # Shell script to restart MySQL server if it is killed or not working
    # due to ANY causes.
    # When script detects mysql is not running (it basically sends ping request
    # to MySQL) it try to start using /etc/init.d/mysql script; and it sends an
    # email to user indicating the status.
    # This script must be run from Cron Job so that it can monitor mysql server.
    # For more info visit following url:
    # http://www.cyberciti.biz/nixcraft/vivek/blogger/2005/08/linux-mysql-server-monitoring.html
    # --------------------------------------------------------------------------
    # Copyright (C) 2005 nixCraft project
    # This script is licensed under GNU GPL version 2.0 or above
    # -------------------------------------------------------------------------
    # This script is part of nixCraft shell script collection (NSSC)
    # Visit http://bash.cyberciti.biz/ for more information.
    # -------------------------------------------------------------------------
    # mysql root/admin username
    MUSER="root"
    # mysql admin/root password
    MPASS="SET-ROOT-PASSWORD"
    # mysql server hostname
    MHOST="localhost"
    #Shell script to start MySQL server i.e. path to MySQL daemon start/stop script.
    # Debain uses following script, need to setup this according to your UNIX/Linux/BSD OS.
    MSTART="/etc/init.d/mysql start"
    # Email ID to send notification
    EMAILID="notification@somewhere-corp.com"
    # path to mail program
    MAILCMD="$(which mail)"
    # path mysqladmin
    MADMIN="$(which mysqladmin)"
    #### DO NOT CHANGE anything BELOW ####
    MAILMESSAGE="/tmp/mysql.fail.$$"
    # see if MySQL server is alive or not
    # 2&1 could be better but i would like to keep it simple and easy to
    # understand stuff :)
    $MADMIN -h $MHOST -u $MUSER -p${MPASS} ping 2>/dev/null 1>/dev/null
    if [ $? -ne 0 ]; then
    echo "">$MAILMESSAGE
    echo "Error: MySQL Server is not running/responding ping request">>$MAILMESSAGE
    echo "Hostname: $(hostname)">>$MAILMESSAGE
    echo "Date & Time: $(date)">>$MAILMESSAGE
    # try to start mysql
    $MSTART>/dev/null
    # see if it is started or not
    o=$(ps cax | grep -c ' mysqld$')
    if [ $o -eq 1 ]; then
    sMess="MySQL Server MySQL server successfully restarted"
    else
    sMess="MySQL server FAILED to restart"
    fi
    # Email status too
    echo "Current Status: $sMess">>$MAILMESSAGE
    echo "">>$MAILMESSAGE
    echo "*** This email generated by $(basename $0) shell script ***">>$MAILMESSAGE
    echo "*** Please don't reply this email, this is just notification email ***">>$MAILMESSAGE
    # send email
    $MAILCMD -s "MySQL server" $EMAILID < $MAILMESSAGE
    else # MySQL is running :) and do nothing
    :
    fi
    # remove file
    rm -f $MAILMESSAGE

Sekian cerita ane ntar nyambung lagi...

HTML Editor Powerfull

$
0
0


WYSIWYG html editor adalah sebuah teks/konten editor yang biasanya ada pada sebuah website dinamis, biasanya wysiwyg html editor ini berada di halaman administrator, wysiwyg html editor memiliki fitur yang mirip dengan microsoft word, dimana kita bisa membuat teks yang miring, tebal, garis bawah, mengatur paragraph, membuat bullet & numbering, dan lainnya yang berguna untuk mengelola konten website.
Wysiwyg html editor yang paling terkenal yaitu TinyMCE (bahkan dignakan oleh wordpress), Berikut ini ada beberapa wysiwyg editor gratis lain yang bisa anda gunakan untuk website anda.

1. Simplified WYSIWYG Editor (Bootstrap): Summernote

Website : http://hackerwins.github.io/summernote/
Download : https://github.com/HackerWins/summernote/

2. Full-Featured Markdown Editor – StackEdit
Website : http://benweet.github.io/stackedit/
Download : https://github.com/benweet/stackedit/
3. A Lovely JavaScript WYSIWYG Editor – Redactor

Website : http://redactorjs.com/
Download : http://redactorjs.com/examples/
4. WYSIHTML5 – A Lightweight Rich Text Editor With Valid HTML5 Markup


Website : http://xing.github.com/wysihtml5/
Download : https://github.com/xing/wysihtml5
5. HTML5-Powered WYSIWYG Editor: Mercury

Website : http://jejacks0n.github.com/mercury/
Download : https://github.com/jejacks0n/mercury
6. WYSIWYG Editor With A File Manager: elRTE

Website : http://elrte.org/
Download : http://elrte.org/demo
7. Extensible jQuery WYSIWYG Editor – CLEditor


Website : http://premiumsoftware.net/cleditor/


Ane bahas yang Summernote gan ye, setelah dibuat gak bisa tidur untuk nentuin Editor mana yang mau dipakai dan kesesuaian integrasi dengan menggunakan Bootstrap 3.2.x dan CodeIgniter 2.4.x.

Dokumentasi dari summernote sendiri sudah cukup lengkap jika inginn belajar dari nol pun gak ada masalah. yang paling ane suka tu gambar langsung bisa di tambahkan secara langsung dalam editor, tanpa harus setting sana sini.

Download dulu dari sumbernya langsung

Website : http://hackerwins.github.io/summernote/
Download : https://github.com/HackerWins/summernote/
Asumsi Themes yang digunakan agan semua minimal yang sudah support dengan Bootstrap 3.x dan membutuhkan jQuery yang terakhir.

Hal yang perlu disiapkan:

1. Instalasi css & js paket summernote

Extract dan tambahkan dittempat biasa agan semua naruh js dan css, tiap orang punya style sendiri. Kalo ane cenderung dipisahkan antara css dan js jadi kalo nyari gampang. Library pada paket summernote ada summernote.css dan summernote.min.js

2.Pemanggilan form summernote

yang akan dieksekusi di pengalaman ane sih jQuery harus ditempatin paling atas soalnya dipake summernote untuk operasi fungsi yang ada dalam summernote.


"summernote.min.js">
 
kedua script utama yang harus ditambahkan dalam pemanggilan.



Buat manggil summernote, dengan mengacu pada class textarea atau ID atau nama textarea yang digunakan.

                                $(function() {
                                     $('.summernote').summernote({
                                         height: 400
                                     });

                                     $('form').on('submit', function (e) {
                                         var myValueEditor = $('.summernote').code();       
                                                                    
                                         //alert(myValueEditor);

                                         //if(myValueEditor='') {alert('Konten masih kosong');}                           
                                       
                                         document.getElementById('myEditorId').value = myValueEditor;
                                         // document.getElementById('myForm');
                                     });
                                });


3.Parsing data form summernote dan validasi di Codeigniter

yang parsingnya menggunakan hidden variabel yang dalam memasukan valuenya dengan menggunakan perintah javascript dengan mengacu pada id document pada form yang dibuat.


4. Tampilkan hasil dalaman halaman

htmlspecialchars($str);  



 

composer error : laravel cann't install

$
0
0

 [Composer\Repository\RepositorySecurityException]                           
  The contents of http://packagist.org/p/symfony/browser-kit$7243ec71a1525094 
  0c9d6c520acf1894c56aed85abb53ce09abb1ddf7702855a.json do not match its signature. This should indicate a man-in-the-middle attack. Try running composer again and report this if you think it is a mistake.


type this command :

composer config -ge

add this script



"repositories": {
"packagist": { "url": "https://packagist.org", "type": "composer" }
}
 
 
be like this
 



 Ref : https://github.com/composer/composer/issues/2835#issuecomment-38678249


 

Nyemplungin Project PHP ke Github (Install + Konfigurasi Git dan Upload Project)

$
0
0
1. Silahkan buat akun terlebih dahulu di situs github.com.
2. Setelah selesai, kita lanjutkan dengan mendownload software git di alamat ini http://git-scm.com/downloads. Sesuaikan dengan sistem operasi yang rekan-rekan gunakan. Disini saya menggunakan linux Mint sebagai sistem operasinya, jadi tinggal menginstallnya lewat terminal saja. Untuk OS Windows & Mac, gunakan pengaturan default seperti yang sudah tertera di panduan instalasi.
3. Seusai proses instalasi, buka aplikasi Git Bash (CLI version) jika rekan-rekan menggunakan OS Windows atau OS Mac. Jika menggunakan Linux seperti saya, cukup buka aplikasi terminal. Let’s go…
4. Masuk ke direktori aplikasi kita
Untuk versi Windows
1cd C:/repo/direktori_aplikasi
Untuk Linux & Mac
1cd /repo/direktori_aplikasi
5. Lakukan inisialisasi repositori
1git init
Akan keluar tulisan :
1Initialized empty Git repository in /home/lumbung/repo/psb/.git/
6. Masukkan semua aplikasi ke dalam antrian repositori, kalo error tambahkan saja -f jadi git add -f * ( memaksa file dimasukkan)
1git add *
7. Lihat status progresnya
1git status
Akan muncul hasil seperti ini :
1# On branch master
2#
3# Initial commit
4#
5# Changes to be committed:
6# (use "git rm --cached ..." to unstage)
7#
8# new file: admin/daftar-siswa.php
9# new file: admin/daftar-user.php
10# new file: admin/edit-pesan.php
11# new file: admin/edit-petugas.php
8. Lakukan commit terhadap file-file yang sudah masuk ke dalam daftar repo
1git commit -m "Commit Pertama"
Akan muncul progress seperti di bawah ini :
1[master (root-commit) 7b73710] Commit Pertama
2
375 files changed, 2611 insertions(+), 0 deletions(-)
4create mode 100644 admin/daftar-siswa.php
5create
6
7mode 100644 admin/daftar-user.php
9. Sekarang saatnya login ke akun github yang telah rekan-rekan buat. Buat sebuah repo dengan meng-klik link di pojok kanan atas “Create New Repo”.

10. Kita akan mendapatkan akses url untuk alamat repo yang baru kita buat. Contohnya pada tutorial ini ialah https://github.com/gedelumbung/OptionMenu.git
11. Kembali ke terminal atau Git Bash, ketikkan perintah berikut untuk menginisialisasi alamat repo / melakukan remoting pada repo yang akan kita gunakan :
12. Kemudian ketik perintah selanjutnya untuk melakukan Pull dari Github ke lokal repo komputer kita

1git pull origin master
2
3Akan muncul hasil seperti berikut :
4
51
6warning: no common commits
7remote: Counting objects: 6, done.
8remote: Compressing objects: 100% (2/2), done.
9remote: Total 6 (delta 0), reused 0 (delta 0)
10Unpacking objects: 100% (6/6), done.
12* branch master -> FETCH_HEAD
13Merge made by recursive.
14README.md | 3 +++
151 files changed, 3 insertions(+), 0 deletions(-)
16create mode 100644 README.md
13. Dan yang terakhir, kita akan melakukan Push folder project aplikasi kita ke situs Github
1git push origin master
Kita akan diminta untuk memasukkan username dan password dari akun Github yang kita gunakan. Hasilnya seperti di bawah ini :
1Username:
2Password:
3Counting objects: 82, done.
4Delta compression using up to 4 threads.
5Compressing objects: 100% (81/81), done.
6Writing objects: 100% (81/81), 194.61 KiB, done.
7Total 81 (delta 8), reused 0 (delta 0)
95b641f5..0b590a9 master -> master
14. Setelah itu, mari kita cek direktori repo yang telah kita buat. Jika berhasil, maka akan terlihat daftar file-file dan folder aplikasi kita sudah nangkring di sana.

15. Selesai

Cukup mudah kan?? Hehe, kelihatannya memang mudah, tetapi sebenarnya lumayan rumit juga jika kita belum mengerti konsep dari cara Git ini. Kata-kata gaul kalau kita sudah bermain-main dengan github ialah, “Fork Me” :D. Istilah Fork adalah menyalin repo dari milik seseorang, dimana kita bisa berkontribusi dalam pengembangan source code dari si pemilik repo asli. Beginilah cara kerja team yang baik dalam pengembangan software-software besar seperti software-software open source maupun sistem operasi open source. 

Ref : http://gedelumbung.com/git-tutorial-cara-installkonfigurasi-git-dan-upload-project-aplikasi-ke-github/

Create Simple Blog With Laravel

$
0
0
In couple amount ago very interst to complete the test of the newest Framework on PHP Project. As discuss on group n social media laravel is great, can erase your pain of  an other Framework like Yii, CI and Zend, etc. Too many if i list in here, laravel is fenom. The route is very greate, composer, migrate, ORM, artisan and much great thing on Laravel.


Create Template


Create Post


Create Comment


All of code can download : https://github.com/loliktry/laravel-blog

Create Your own hosting name website on local server with apache2

$
0
0
One of the most common Apache2 questions I've seen on Debian mailing lists is from users who wonder how to host multiple websites with a single server. This is very straightforward, especially with the additional tools the Debian package provides.

We've previously discussed some of the tools which are included in the Apache2 package, but what we didn't do was show they're used from start to finish.

There are many different ways you can configure Apache to host multiple sites, ranging from the simple to the complex. Here we're only going to cover the basics with the use of the NameVirtualHost directive. The advantage of this approach is that you don't need to hard-wire any IP addresses, and it will just worktm. The only thing you need is for your domain names to resolve to the IP address of your webserver.

For example if you have an Apache server running upon the IP address 192.168.1.1 and you wish to host the three sites example.com, example.net, and example.org you'll need to make sure that these names resolve to the IP address of your server.

(This might mean that you need example.com and www.example.com to resolve to the same address. However that is a choice you'll need to make for yourself).

Since we'll be hosting multiple websites on the same host it makes a lot of sense to be very clear on the location of each sites files upon the filesystem. The way I suggest you manage this is to create a completely seperate document root, cgi-bin directory, and logfile directory for each host. You can place these beneath the standard Debian prefix of /var/www or you may use a completely different root - I use /home/www.

If you've not already done create the directories to contain your content, etc, as follows:

root@irony:~# mkdir /home/www

root@irony:~# mkdir /home/www/www.example.com
root@irony:~# mkdir /home/www/www.example.com/htdocs
root@irony:~# mkdir /home/www/www.example.com/cgi-bin
root@irony:~# mkdir /home/www/www.example.com/logs

root@irony:~# mkdir /home/www/www.example.net
root@irony:~# mkdir /home/www/www.example.net/htdocs
root@irony:~# mkdir /home/www/www.example.net/logs
root@irony:~# mkdir /home/www/www.example.net/cgi-bin

root@irony:~# mkdir /home/www/www.example.org
root@irony:~# mkdir /home/www/www.example.org/htdocs
root@irony:~# mkdir /home/www/www.example.org/logs
root@irony:~# mkdir /home/www/www.example.org/cgi-bin

Here we've setup three different directory trees, one for each site. If you wanted to have identical content it might make sense to only create one, and then use symbolic links instead.

The next thing to do is to enable virtual hosts in your Apache configuration. The simplest way to do this is to create a file called /etc/apache2/conf.d/virtual.conf and include the following content in it:

#
#  We're running multiple virtual hosts.
#
NameVirtualHost *

(When Apache starts up it reads the contents of all files included in /etc/apache2/conf.d, and files you create here won't get trashed on package upgrades.)

Once we've done this we can create the individual host configuration files. The Apache2 setup you'll find on Debian GNU/Linux includes two directories for locating your site configuration files:

/etc/apache2/sites-available

    This contains configuration files for sites which are available but not necessarily enabled.
/etc/apache2/sites-enabled

    This directory contains site files which are enabled.

As with the conf.d directory each configuration file in the sites-enabled directory is loaded when the server starts - whilst the files in sites-available are completely ignored.

You are expected to create your host configuration files in /etc/apache2/sites-available, then create a symbolic link to those files in the sites-enabled directory - this will cause them to be actually loaded/read.

Rather than actually messing around with symbolic links the Debian package includes two utility commands a2ensite and a2dissite which will do the necessary work for you as we will demonstrate shortly.

Lets start with a real example. Create /etc/apache2/sites-available/www.example.com with the following contents:

#
#  Example.com (/etc/apache2/sites-available/www.example.com)
#

        ServerAdmin webmaster@example.com
        ServerName  www.example.com
        ServerAlias example.com

        # Indexes + Directory Root.
        DirectoryIndex index.html
        DocumentRoot /home/www/www.example.com/htdocs/

        # CGI Directory
        ScriptAlias /cgi-bin/ /home/www/www.example.com/cgi-bin/
       
                Options +ExecCGI
       



        # Logfiles
        ErrorLog  /home/www/www.example.com/logs/error.log
        CustomLog /home/www/www.example.com/logs/access.log combined


Next create the file www.example.net:

#
#  Example.net (/etc/apache2/sites-available/www.example.net)
#

        ServerAdmin webmaster@example.net
        ServerName  www.example.net
        ServerAlias example.net

        # Indexes + Directory Root.
        DirectoryIndex index.html
        DocumentRoot /home/www/www.example.net/htdocs/

        # CGI Directory
        ScriptAlias /cgi-bin/ /home/www/www.example.net/cgi-bin/
       
                Options +ExecCGI
       



        # Logfiles
        ErrorLog  /home/www/www.example.net/logs/error.log
        CustomLog /home/www/www.example.net/logs/access.log combined


Finally create the file www.example.org:

#
#  Example.org (/etc/apache2/sites-available/www.example.org)
#

        ServerAdmin webmaster@example.org
        ServerName  www.example.org
        ServerAlias example.org

        # Indexes + Directory Root.
        DirectoryIndex index.html
        DocumentRoot /home/www/www.example.org/htdocs/

        # CGI Directory
        ScriptAlias /cgi-bin/ /home/www/www.example.org/cgi-bin/
       
                Options +ExecCGI
       



        # Logfiles
        ErrorLog  /home/www/www.example.org/logs/error.log
        CustomLog /home/www/www.example.org/logs/access.log combined


Now we've got:

    Three directories which can be used to contain our content.
    Three directories which can be used to contain our logfiles.
    Three directories which can be used to contain our dynamic CGI scripts.
    Three configuration files which are being ignored by Apache.

To enable the sites simply run:

root@irony:~# a2ensite www.example.com
Site www.example.com installed; run /etc/init.d/apache2 reload to enable.

root@irony:~# a2ensite www.example.net
Site www.example.net installed; run /etc/init.d/apache2 reload to enable.

root@irony:~# a2ensite www.example.org
Site www.example.org installed; run /etc/init.d/apache2 reload to enable.

This will now create the symbolic links so that /etc/apache2/sites-enabled/www.example.org, etc, now exist and will be read.

Once we've finished our setup we can restart, or reload, the webserver as the output above instructed us to do with:

root@irony:~# /etc/init.d/apache2 reload
Reloading web server config...done.
root@irony:~#

Add Comment XML logo


<<< Debian and Apache2 as an OWA Front-end website screenshot server on debian stable >>>



    not connected to Facebook
    Facebook "Like"-Dummy
    not connected to Google+
    "Google+1"-Dummy
    not connected to LinkedIn
    "LinkedIn"-Dummy
    not connected to StumbleUpon
    "Stumble!"-Dummy
    not connected to Twitter
    "Tweet this"-Dummy



Why are these adverts here?
#
Re: Hosting multiple websites with Apache2
Posted by trollll (64.128.xx.xx) on Thu 6 Jul 2006 at 23:19
[ View Weblogs ]

I found it very easy to add webmail to all domains given this sort of setup, by adding the following to each conf:

        ServerAdmin webmaster@example.org
        ServerName  webmail.example.org

        # Indexes + Directory Root.
        DirectoryIndex index.html
        DocumentRoot /home/www/www.example.org/webmail/

        # Logfiles
        ErrorLog  /home/www/www.example.org/logs/error.log
        CustomLog /home/www/www.example.org/logs/access.log combined

Then, you can install Horde (for example, as I did) in /home/www/webmail, have it use the hostname as part of the login, and make a symbolic link by doing the following:

$ ln -s /home/www/webmail /home/www/www.example.org/webmail

I made symbolic links rather than defining the path directly in the conf, because that way I can easily change webmails without restarting the server. Especially handy if a few domains should have a different set of modules enabled or use different authentication methods, etc.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (193.195.xx.xx) on Fri 7 Jul 2006 at 08:51
Can you not just use Alias as part of the main config to achieve the same thing?

And you can just reload the server instead of restarting it if you change the config.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by trollll (24.153.xx.xx) on Sat 8 Jul 2006 at 18:21
[ View Weblogs ]

    Can you not just use Alias as part of the main config to achieve the same thing?

You could, but I don't like having webmail as (essentially) a subdirectory. Also, this way you can apply different configurations to each webmail as necessary.

    And you can just reload the server instead of restarting it if you change the config.

Heh...I haven't used reload in so long after having odd behavior early on that I forgot about it completely. I don't restart webservers often so it doesn't come up a whole lot.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Steve (62.30.xx.xx) on Fri 7 Jul 2006 at 09:19
[ View Steve's Scratchpad | View Weblogs ]

I guess with that setup, since the webmail is "inside" the document root you can access it either via either of the links:

    webmail.example.org
    www.example.org/webmail

For me I'd tend to only use the webmail.example.org site available and I'd do it with:

mkdir /home/www/webmail.example.org/
mkdir /home/www/webmail.example.org/logs

ln -s /home/www/webmail /home/www/webmail.example.org/htdocs

(No need for a CGI directory in this case I guess!)

Still I guess this is personal preference really..

Steve

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by trollll (64.128.xx.xx) on Fri 7 Jul 2006 at 14:18
[ View Weblogs ]
Yeah, it just comes down to personal preference - I just like having the logs, etc. in the same directory for a domain (just different prefixes when it comes to the logs).

With a webmail document root of /home/www/www.example.org/webmail/ it would sit outside of the /home/www/www.example.org/htdocs/ directory, though. I wouldn't want the overlap either.

[ Parent | Reply to this comment ]

#
dynamically configured mass virtual hosting
Posted by cfry (68.170.xx.xx) on Fri 7 Jul 2006 at 02:38
It can be even simpler than that. You can configure apache once, then add domain directories on the fly with something like:

UseCanonicalName Off
VirtualDocumentRoot /var/www/%0/public_html
VirtualScriptAlias /var/www/%0/cgi-bin

as explained in detail at http://httpd.apache.org/docs/2.0/vhosts/mass.html

[ Parent | Reply to this comment ]

#
Re: dynamically configured mass virtual hosting
Posted by Steve (62.30.xx.xx) on Fri 7 Jul 2006 at 08:59
[ View Steve's Scratchpad | View Weblogs ]

Like I said there are multiple ways to do this and using your method is a neat approach if you have lots of simple sites which don't need anything special.

The advantage of the method shown here is that it allows you to customize each different site very easily, (since there is a configuration file for each host), that might allow you to do things like install mailman on one host, and add custom redirects, etc.

In my server I have around 10 domains, and each has different customizations - for example the configuration file for this site enables lots of mod_rewrite magic so that all our URLs are pretty - but I don't want those customisations applied globally which I think I would have to do if I used the mass-virtual hosting you suggest.

Steve

[ Parent | Reply to this comment ]

#
Re: dynamically configured mass virtual hosting
Posted by cfry (128.2.xx.xx) on Fri 7 Jul 2006 at 12:35
I personally use both. I have the generic configuration for anyone who doesn't need anything special, then on top of that I add custom VirtualHost sections for anyone who needs more. The small difference is that the VirtualHost sections don't need to redefine DocumentRoot and ScriptAlias. Also, because of the generic Virtual Root and Alias settings, each VirtualHost can use ServerAlias to configure the same configuration settings for physically different websites. For example, the mailing lists for all of my domains are all simultaneously configured with:

  
       ServerName lists.example.com
       ServerAlias lists.*

       RedirectMatch permanent ^/$ /mailman/listinfo

       RewriteEngine on
       RewriteRule ^/mailman(/.*)?$ /cgi-bin/mailman$1 [PT,L]
  


[ Parent | Reply to this comment ]

#
Re: dynamically configured mass virtual hosting
Posted by trakic (130.226.xx.xx) on Fri 7 Jul 2006 at 13:45
[ View Weblogs ]
To cfry: - How do you achieve that (customize VirtualHost sections on top of dyn mass virtual hosting)? - Is it possible with Apache 1.3? My dyn mass virtual hosting work ok, but I want to constumize them accordingly. My last lines httpd.conf:

UseCanonicalName Off
LogFormat "%V %h %l %u %t \"%r\" %s %b" vcommon
VirtualDocumentRoot /Library/WebServer/Hosts/%0/Documents
VirtualScriptAlias /Library/WebServer/Hosts/%0/CGI-Executables

- My costumised virtual host bits are like this:


VirtualHost
   ServerName          svn.domain.ltd
    ServerAlias         svn
    RewriteEngine On
    Redirect            /       http://10.0.0.0:8080/
    #ProxyPreserveHost   On
    #ProxyPass           /       http://10.0.0.0:8080/
    #ProxyPassReverse    /       http://10.0.0.0:8080/
VirtualHost

On my error log I still get like:

... File does not exist: /Library/WebServer/Hosts/svn.domain.tld/Documents/

- Any hints? Regards Admir ~

[ Parent | Reply to this comment ]

#
Re: dynamically configured mass virtual hosting
Posted by cfry (128.2.xx.xx) on Fri 7 Jul 2006 at 14:22
You still need to manually create the directories (in your case /Library/WebServer/Hosts/svn.domain.tld/Documents/ ).

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (213.164.xx.xx) on Fri 7 Jul 2006 at 08:19
This setup breaks under php safe mode. You want to use /var/www for holding the sites.

[ Parent | Reply to this comment ]

#
Posted by Anonymous (193.195.xx.xx) on Fri 7 Jul 2006 at 08:52
Just change your DocumentRoot to /home

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Steve (62.30.xx.xx) on Fri 7 Jul 2006 at 09:15
[ View Steve's Scratchpad | View Weblogs ]

I tend to regard PHPs safe mode as still-broken.

For my PHP I use mod_security/mod_ifier + suphp.

Steve

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (213.164.xx.xx) on Fri 7 Jul 2006 at 11:48
I don't mean php safe mode. Oops. I mean suexec.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (202.7.xx.xx) on Mon 24 Jul 2006 at 05:00
Nice article. I had been looking for a clear, non confusing howto on this for ages, but had no luck until I found this one. Thanks Steve!

I've got two concerns though:
1) when users enter blahblahblah.example.com, they get taken to the directory above the htdocs directory, with access to log files and stuff, which is somewhat of a security hole. How do you close that one off?

2) I get the following warning when I restart apache (I'm running Apache 2.0.55):

[warn] NameVirtualHost *:0 has no VirtualHosts

How do I make the warning go away?

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Steve (62.30.xx.xx) on Mon 24 Jul 2006 at 06:39
[ View Steve's Scratchpad | View Weblogs ]

For your first question I'm unsure - I can't see how that could ever happen in the setup I described. Each site is only "example.com", or "www.example.com" - the name "blahblah.example.com" wouldn't even resolve, and if it did shouldn't be visible - unless you have a default virtual host setup for /var/www and you're storing your sites beneath that?

In that case move the virtual hosts beneath /home/www, like I do, or comment out the default entry.

For the second I'd just remove the line "NameVirtualHost *:0" since it isn't relevant.

Run "rgrep -li NameVirtualHost /etc/apache2" to find where it is set.

Steve

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by xoctor (202.7.xx.xx) on Mon 24 Jul 2006 at 15:36
Yep - forgot to disable the default account! Removing the default account fixed the warning, but now going to 'http://something.example.com' produces a very odd result. I have 3 virtual domains, say alpha.com, beta.com and delta.com. If I point my browser at nonsense.alpha.com (or nonsense.beta.com) I get the delta.com directory. alpha.com and www.alpha.com work as expected. btw - they're all defined under /home/www

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Steve (80.68.xx.xx) on Mon 24 Jul 2006 at 15:43
[ View Steve's Scratchpad | View Weblogs ]

I think that what is happening is that the host you're requesting is pointed to the IP of the server, but you don't have a virtual setup explicity setup for it.

So instead Apache passes it to the first available virtual host (ie. the file in /etc/apache2/sites-enabled which is first will be used.)

To fix this either:

    Add a new ServerAlias to the relevant file.
    Ensure that 00-default is used for the site which you wish to be used for unknown hosts.

Really I can't see this being a problem in general since people don't often use wildcard dns.

I'd suggest you add the folloing to www.alpha.com:

ServerName www.alpha.com
ServerAlias alpha.com
ServerAlias *.alpha.com

That will ensure that blah.alpha.com is handled by the Alpha.com virtual host. Add similar wildcard settings to beta.com, etc.

Steve

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by xoctor (202.7.xx.xx) on Mon 24 Jul 2006 at 16:14
Thanks for your help Steve. Now I'm cookin' with gas!

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by gmcneal (66.92.xx.xx) on Wed 6 Sep 2006 at 02:01
I created four virtual websites on a single server as outlined in the article.
The sites show up as expected on Win2k OS, but only the default site
displays on my Linux(Ubuntu distribution) OS.
The results are the same with IE and Firefox.
The URLs are of the format http://example.com, http://website1.example.com,
http://website2.example.com, http://website3.example.com, etc.
http://example.com is the default.

I must be missing something simple.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (219.64.xx.xx) on Fri 22 Jul 2011 at 11:25
Hope all your 4 websites are giving different results. Actually, I also want to do similar. But I can't use "NameVirtualHost *", its giving error. Currently I am running two websites. One at openssl configured and other running at virtual host. I want to add one more website in the virtual host. How I will do that please guide me.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by sphaero (83.160.xx.xx) on Wed 20 Sep 2006 at 15:56
[ View Weblogs ]
To enable virtual hosts using the default debian setup make sure the default site in /etc/apache2/sites-available contains a ServerName directive containing the hostname of your server. That's the only thing that needs to be edited to get virtual hosts working correctly on Debian Sarge.

It makes me wonder why it's not setup by the debian installer of apache2.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by jimbabwe (69.140.xx.xx) on Sun 24 Sep 2006 at 04:02
I've used this site a number of times; it's great.

Had a slight issue with a2ensite.

In working with Apache 2.0.54 on Debian 2.6.8-3-686-smp, I couldn't get a2ensite to run as shown above.

I followed all instructions, but when I ran a2ensite as shown in the example "a2ensite www.example.com" (putting in my site, of course, the message came back "This site does not exist!"

I tried next to run the a2ensite command alone, without any additional info. behind the command (i.e., just typed 'a2ensite' as root) and it worked fine, prompting me for information and at the end, enabled the site.

Thanks again for the help!

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (165.155.xx.xx) on Mon 19 Mar 2007 at 16:49
thank you jimbabwe. I had to do that too.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by pvince (70.60.xx.xx) on Mon 22 Feb 2010 at 16:49
I have a problem with the a2ensite command too. I comes up as "command not found" for me. I'm running Apache2 on Fedora 12

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (190.148.xx.xx) on Fri 2 Apr 2010 at 18:05
Hi. I'm cancuengt.
Debian (and based distros) has a very special way to handle virtual hosts with apache2. This is not the same with Fedora (and based distros). I recommend that you visit http://www.mjmwired.net/resources/mjm-apache-virtual-sites.html. This might help you.
Greetings.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by olden (193.34.xx.xx) on Sun 29 Apr 2007 at 17:05
[ View Weblogs ]
I would like to share scenario for Perl
that can help in the virtual domain for Apache2.
Indeed the script:
=====================
#!/usr/bin/perl -w

use strict;
use English;

my $etc = "/etc/apache2/sites-available/";
my $log = "/var/log/apache2/";
my $www = "/var/";
my $a2ensite = "/usr/sbin/a2ensite";
my $a2 = "/etc/init.d/apache2";
my ($login,$pass,$uid,$gid) = getpwnam("www-data");

exit unless defined @ARGV;
my $site = $ARGV[0];
my $wwwsite = "www.".$site;

open FTEMPLATE, "<$etc/TEMPLATE" or die "Can't open file: $!\n";
my @tmpl = ;
close FTEMPLATE;

mkdir "$log$wwwsite", 0755;
mkdir "$www$wwwsite", 0755;
chown $uid, $gid, "$www$wwwsite";

open FSITE, ">$etc$wwwsite" or die "Can't write file: $!\n";
foreach (@tmpl) {
s!!$site!g;
print FSITE;
}
close FSITE;

open FTIINDEX, "<$etc/TINDEX" or die "Can't open file: $!\n";
open FOIINDEX, ">$www$wwwsite/index.php" or die "Can't write file: $!\n";
while () { print FOIINDEX }
close FOIINDEX;
close FTIINDEX;
chown $uid, $gid, "$www$wwwsite/index.php";

system($a2ensite,$wwwsite);
system($a2,"reload");
=====================

Template TEMPLATE:
=====================
#
# (/etc/apache2/sites-available/www.)
#

ServerAdmin postmaster@olympus.net.ua
ServerName www.
ServerAlias
DirectoryIndex index.html index.htm index.php
DocumentRoot /var/www./
ErrorLog /var/log/apache2/www./error.log
CustomLog /var/log/apache2/www./access.log combined

=====================

Template TINDEX:
=====================


=$_SERVER["HTTP_HOST"]?>

The web server
is not available or under development.

For more information contact
">;.
;
=====================

Indeed all.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Steve (62.30.xx.xx) on Sun 29 Apr 2007 at 17:38
[ View Steve's Scratchpad | View Weblogs ]

Not bad.

I have something similar for adding, removing, and listing sites for Apache2 and mail handling with Exim4... :)

Steve

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (15.195.xx.xx) on Thu 17 May 2007 at 08:24
Hi,

I have followed you tutorial and I get this...:

Keeper:/home# /etc/init.d/apache2 reload
Reloading web server config...2464
apache2: Could not reliably determine the server's fully qualified domain name, using 192.168.0.187 for ServerName
[Thu May 17 10:01:40 2007] [warn] NameVirtualHost *:0 has no VirtualHosts
.
the server's ip adress is 192.168.0.187 (it's behind a router that forwardes needed ports to this machine)

any suggestion ?

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by roncarney (24.120.xx.xx) on Thu 21 Jun 2007 at 19:20
I get the same msg, as well, except instead of the box's IP I get the loopback. But I do get the
[Thu May 17 10:01:40 2007] [warn] NameVirtualHost *:0 has no VirtualHosts
msg and nothing is web accessible, I just get a timeout in the browser.

Any Help?

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (76.177.xx.xx) on Wed 11 Jul 2007 at 07:09
For the record I am using Ubuntu Feisty Fawn to do all of this.

I followed the tutorial and but did this for my sites-available instead. I have 6 sites set up and all work. I still however get the same message as you. the message indicates that your using the wildcard instead of an IP address. If you used this you shouldn't need to create the /etc/apache2/conf.d/virtual.conf


NameVirtualHost *
#
# Example.com (/etc/apache2/sites-available/www.example.com)
#

ServerAdmin admin@example.com
ServerName example.com
# Putting *. in front of the name of the website makes things like webmail or www work
ServerAlias *.example.com

# Indexes + Directory Root.
DirectoryIndex index.html
DocumentRoot /var/www/example/htdocs/

# CGI Directory
ScriptAlias /cgi-bin/ /var/www/example/cgi-bin/

Options +ExecCGI



# Logfiles
ErrorLog /var/www/example/logs/error.log
CustomLog /var/www/example/logs/access.log combined


[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (78.144.xx.xx) on Sun 25 Nov 2007 at 18:39
Hi i have done a little guide on this using the virtual.con in apache conf folder and it works flawlessly with no errors.

check it out at http://brandan.no-ip.info/forum/ i have just started the forum so i can keep all my tips and tricks but everyone is welcome to put up some tuts to help out. AND THANKS TO THE GUY WHO MADE THIS TUTORIAL AND ALL OTHER TUTORIALS.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by cvtrig (74.10.xx.xx) on Wed 9 Jan 2008 at 05:59
So let me ask:

If I'm on a local intranet, as I'm setting up a server for my lab to use a wiki for documentation purposes.

I've had our IT Dept reserve the IP on their WINS box so that the internal IP resolves to the URL http://wiki

Since I'm not dealing with FQDN, and not using www or .com, do I just use an IP address or the name of the server itself?

I see the configuration you have but when I try to do that without the FQDN or www or .com or I get the error that no virtual hosts can be found.

Any ideas? Since this is on an internal intranet, will this even work without a FQDN?

Many thanks in advance.

cvtrig

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (213.140.xx.xx) on Fri 11 Jan 2008 at 15:02
I had the same message and some (not all) of my virtual hosts weren't accessible. What worked for me:
1. disable the default host - a2dissite default
2. make sure that only one NameVirtualHost * is included in your configuration. On ubuntu server I placed
NameVirtualHost *
right before
Include /etc/apache2/sites-enabled/
found at the end of /etc/apache2/apache2.conf, and removed all NameVirtualHost * lines from files in /etc/apache2/sites-enabled
3. reload apache2 /etc/init.d/apache2 reload

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (208.17.xx.xx) on Fri 19 Feb 2010 at 09:07
Thank you so much. I am using Ubuntu 8.04LTS Apache 2.2. I only had one hair left to pull out until I found your post. Everything works now. Thanks again!!!

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (87.184.xx.xx) on Tue 12 Jul 2011 at 00:12
Thank you so much for your solution. Everything works fine now. This has helped me a lot! Thank you!

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (83.71.xx.xx) on Fri 4 Jan 2013 at 14:46
On LinuxMint Debian this solved my issue as NameVirtualHosts were not being found. Thank you.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by tltan88 (218.111.xx.xx) on Sat 12 Jan 2008 at 02:39
Everything worked fine for my two sites. But the first site would
not read firstsite.com but when I typed www.firstsite.com
it showed my index.html page. The second site, I had no
problems at all. The first site showed error message of: The requested URL/apache2-default/was not found on the server. What did I do wrong?

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Steve (82.32.xx.xx) on Sat 12 Jan 2008 at 15:13
[ View Steve's Scratchpad | View Weblogs ]

Probably you forgot the alias. Something like this:


        ServerName  firstsite.com
        ServerAlias www.firstsite.com
        ...
        ...

Failing that is that you forgot to delete the 000-default site which is enabled.

Steve

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (213.100.xx.xx) on Sat 2 Feb 2008 at 23:25
Thanks for the article, short and clear as usual. However I am still a bit confused about my server configuration. Untill today I didn't have a registered domain name, I just published a few pages for friends and family...these pages were accessed as http://my.server.ip.addr/pageX/
These pages were located in /var/www , like /var/www/pageX/ and in /etc/apache2/sites-available/ I have created a file for each page by just copying the default file which was there from the very beginning, like this:
$cp default pageX

and I didn't edit these files at all.

in the /etc/apache2/sites-enabled/ I have only one symlink:
000-default -> /etc/apache2/sites-available/default

In apache2.conf I didn't find the NameVirtualHost directive, but I saw I have this:
Include /etc/apache2/sites-enabled/

the server is behind a router, its IP is 192.1681.6 and it has

nameserver 192.168.1.1

in the /etc/resolv.conf file (192.168.1.1 is of course the IP of the router)

in /etc/hosts I have this:
127.0.0.1 localhost
192.168.1.6 monica.mcrae monica


...I think these are the details. Now my questions.

Fisrt, why the pages are accessible though their configurations files are in sites-available instead in sites-enabled?

Is Include /etc/apache2/sites-enabled/ in apache2.conf substituting (in a way) the NameVirtualHost directive (which presents in each page conf file in sites-available).

And the most important - today I've bought a domain name and I want to host it on my server. I this howto enough..I mean the virtual host configuration is more or less clear for me, but what about /etc/hosts and /etc/resolv.conf files. Do I have to set something different in them.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by mjh2000 (72.89.xx.xx) on Mon 31 Mar 2008 at 22:26
Great example.
But i have the following issue:
i want to create a lot of subdomains with keywords. etc. keyword1.mysite.com , keyword2.mysite.com, keyword3.mysite.com, keyword4.mysite.com, etc.


If i use both methods list on the site with this: ServerAlias *.mysite.com

I would still have to create a link to the real web directory, is there another way of doing this ??? that i do not have to create so many soft links back to the original web direcotory ???
thanks
mjh

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Steve (82.32.xx.xx) on Mon 31 Mar 2008 at 22:41
[ View Steve's Scratchpad | View Weblogs ]

If the keywords all point at the same directory then you could do it without having to make any symlinks. Just use a config file like this:


  ServerName mysite.com
  ServerAlias *.mysite.com
  ..
  DocumentRoot /home/www/mysite.com/

You just need to add the DNS entries and it will work as expected.

Steve

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (72.89.xx.xx) on Mon 31 Mar 2008 at 23:09
i did try this but it seems not to work for me.

my www.mysite.com file looks like this:


ServerAdmin webmaster@mysite.com
ServerName mysite.com
ServerAlias *.mysite.com

# Indexes + Directory Root.
DirectoryIndex index.php index.html
DocumentRoot /var/www/html/websites/mysite.com/public_html/

# CGI Directory
ScriptAlias /cgi-bin/ /var/www/html/websites/mysite.com/cgi-bin/

Options +ExecCGI



# Logfiles
ErrorLog /var/log/apache2/www.mysite.com/logs/error.log
CustomLog /var/log/apache2/www.mysite.com/logs/access.log combined






I get this in the error log :
File does not exist: /var/www/html/websites/www.mysite.com

i get this on the webpage:
Not Found

The requested URL / was not found on this server.
Apache/2.2.3 (Debian) mod_python/3.2.10 Python/2.4.4 PHP/5.2.0-8+etch10 mod_perl/2.0.2 Perl/v5.8.8 Server at www.mysite.com Port 80




[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Steve (82.32.xx.xx) on Mon 31 Mar 2008 at 23:19
[ View Steve's Scratchpad | View Weblogs ]

The obvious question: Your error says:

    File does not exist: /var/www/html/websites/www.mysite.com

Does it? If not make it via :

mkdir -p /var/www/html/websites/www.mysite.com
echo "test">> /var/www/html/websites/www.mysite.com/index.html

Steve

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by mjh2000 (72.89.xx.xx) on Mon 31 Mar 2008 at 23:53
i am sorry..but i am loosing you...

I get the error:

File does not exist: /var/www/html/websites/www.mysite.com


because in the browser i types WWW.mysite.com


i also get this error:

File does not exist: /var/www/html/websites/rid.mysite.com

again...because i typed in RID.mysite.com


and that is why it is not working ---once i create a soft link to the main dir --it works no problems. I have the * wildcard in the file..but no affect..

I must be missing something reall simple here :)

thanks
mjh

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Steve (82.32.xx.xx) on Mon 31 Mar 2008 at 23:59
[ View Steve's Scratchpad | View Weblogs ]

If you have the configuration file as you suggested above you shouldn't be seeing this error.

You shouldn't have *any* other virtual hosts defined for mysite.com - just the one with the "*" in it. Did you leave the old ones in place?

If so remove them, and restart Apache2.

Steve

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by mjh2000 (72.89.xx.xx) on Tue 1 Apr 2008 at 02:04
can it be the .htaccess file that is causing an issue ?
i am running joomla.with sef option enabled...is something special that has to be part of the htacces file.???
thanks
mjh

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Steve (80.68.xx.xx) on Tue 1 Apr 2008 at 10:49
[ View Steve's Scratchpad | View Weblogs ]

Could be, I don't know.

I know that if the configuration file that you've pasted is the only configuration file, and you're not using any mass-hosting modules it should work as expected - it does for me.

I guess you'll need to ask for assistance on the debian-user mailing list.

Steve

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by mjh2000 (72.89.xx.xx) on Tue 1 Apr 2008 at 15:45
i copied in a fresh new apache2.conf configuration file...very generic.

I got the following error below, could this have something to do with my problem ????



Forcing reload of web server (apache2)...apache2: Could not reliably determine the server's fully qualified domain name, using 192.168.X.XX for ServerName
waiting apache2: Could not reliably determine the server's fully qualified domain name, using 192.168.X.XX for ServerName


thanks
mjh

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Steve (80.68.xx.xx) on Tue 1 Apr 2008 at 16:02
[ View Steve's Scratchpad | View Weblogs ]

Add 'ServerName mysite.com' to a file /etc/apache2/conf.d/local and restart and all will be well.

Steve

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by peopleunit (70.249.xx.xx) on Wed 22 Jul 2009 at 23:15
I followed this step and in doing so it got rid of the Apache startup error that many others were having...

"Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName"

Now I get a clean error free startup... :-)

[Wed Jul 22 17:00:34 2009] [notice] Graceful restart requested, doing restart
[Wed Jul 22 17:00:34 2009] [notice] Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.1 with Suhosin-Patch configured -- resuming normal operations

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by mjh2000 (72.89.xx.xx) on Mon 31 Mar 2008 at 23:55
if i make this directory...i will defeat the purpose...i do not want to create soft link directories.
thanks
mjh

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by mjh2000 (72.89.xx.xx) on Tue 1 Apr 2008 at 00:15
i am still getting the same error.
If i create the dir, i do not get the error.
could there be an issue with the virtual.conf ???
can there be anything special in the main apache.conf file that i have to check??

thanks
mjh

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by mjh2000 (72.89.xx.xx) on Tue 1 Apr 2008 at 00:15
i am still getting the same error.
If i create the dir, i do not get the error.
could there be an issue with the virtual.conf ???
can there be anything special in the main apache.conf file that i have to check??

thanks
mjh

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (24.219.xx.xx) on Tue 27 May 2008 at 08:07
Hosting multiple sub-domains:

Hello everyone, great article and it worked very well for me except that I have three total sites:

1) www.my-domain.com
2) something.my-domain.com
3) www.another-domain.com

Both 1 and 3 worked well just by following this tutorial but I was unable to get number 2 to work. My problem was that I had added a CNAME entry pointing to my my-domain.com instead of an "A" record pointing to the actual IP address. After I changed it, it worked like a charm.

Also another tip: Whatever you put as the argument to the NameVirtualHost MUST be the same as what you put as the argument to VirtualHost in the .conf files.

I hope this helps someone else who has the same problems.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (80.193.xx.xx) on Wed 13 Aug 2008 at 17:06
Hi I followed these instructions, they are the best Ive come across.
I have a ubuntu lamp server, ubuntu client on a local network.
everything worked except I couldnt call www.mikespoetry.com, it was the default on the server so came up anyway. my other site just wasnt showing.

add 192.168.1.5 www.mikespoetry.com
and 192.168.1.5 www.suze-an.com

to both the server and client hosts files and everything works including php

so thank you for stopping my head bleeding from all the cratching

michael

mikejenkinson@yahoo.com

im away to try and set up email now

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (86.134.xx.xx) on Sat 20 Dec 2008 at 23:24
I'm giving up

Right loads of virtual hosts BUT

[Sat Dec 20 23:05:42 2008] [error] (13)Permission denied: could not open transfer log file /lalrlalrlalala

or the Errorlog !!

I;ve switch to the apache user id and can create file in the logs direcorty

But apache still wont work !!!!!!!!!


AAAAAAAAARRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR

Giz

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (134.58.xx.xx) on Mon 9 Feb 2009 at 13:19
Hi All,

I have another little problem with multiple sites configuration.

I have setup 2 sites. Everything works fine.
e.g. I have www.example.com and www.example.org set.

But now, if I want to load for example graphics from another directory.

eg. www.example.com/gfx/1.jpg

Than apache does not find the directory gfx although it is in the home directory of www.example.com.

anyone any idea how to fix this?

warm regards

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (71.196.xx.xx) on Sat 28 Feb 2009 at 14:11
I get this output when reloading:

sudo /etc/init.d/apache2 reload
* Reloading web server config apache2 [Sat Feb 28 09:06:27 2009] [error] VirtualHost *:80 -- mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results
[Sat Feb 28 09:06:27 2009] [warn] NameVirtualHost *:80 has no VirtualHosts
[ OK ]

One website works perfectly and the other brings me to the root directory for my two websites so in a browser I see two directorys which are my two websites. I checked, double checked and triple checked my files for errors and all paths are correct.

I hope this makes sense to someone.

Thanks!
-Nausser

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by peopleunit (70.249.xx.xx) on Wed 22 Jul 2009 at 23:24
[error] VirtualHost *:80 -- mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results

I had that error for a while also, I removed the port designation... :80

...and the error disappeared.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (189.144.xx.xx) on Sat 4 Apr 2009 at 06:07
hi i try to set virtual host with out sucess the thing is also i need to make a connection with tomcat6, appearly i doing all rigth but when i put in the browser appears forbiden error 403 and small letters the name of the connector how i know if the connector is working also i try to make a connector but i cant find the apache extension tool another thing i have to set dns for example.com example.net for this works or doesnt matter. i really appreciate the help bye

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by rexuk (189.144.xx.xx) on Wed 8 Apr 2009 at 23:43
hi i found this article very usefull but somebody help me to configure apache2 to work with tomcat6 and postgresql
bye

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (80.192.xx.xx) on Thu 7 May 2009 at 17:44
Guys this guide dosen't work, when I restart apache2 I get; Forcing reload of web server (apache2)...[Thu May 07 17:29:33 2009] [warn] NameVirtualHost www.jibend.co.uk:0 has no VirtualHosts, and if I run the command to create the link it tells me the site dosen't exist.
Does Apache actually work?!

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (67.88.xx.xx) on Thu 14 May 2009 at 19:23
I followed the guide to the key on ubuntu and it worked perfect for me. I did have to login as root to create files in the apache2 directory.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (125.238.xx.xx) on Mon 18 May 2009 at 04:32
Then you are a moron. You don't have to login as root, just use sudo.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (99.194.xx.xx) on Tue 2 Jun 2009 at 19:27
PERFECT!!! Helped my buddy setup Virtual Hosting, hosting 4 websites so far using this TuT. Thanks!!!!

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (88.107.xx.xx) on Fri 10 Jul 2009 at 18:55
I was trying to do multiple vhosts but whatever url I used went to the default folder, I had everything setup except virtual.conf. once I had that in, it all worked ! thanks for the tutorial!

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (24.241.xx.xx) on Wed 19 Aug 2009 at 22:17
I still cant figure out how to use multiple pages on one server with apache and havent been able to find any information as to how to do that, im using apache 2.2.x, my site is jiwtech.dynalias.com and i have all of the pages coded but i cant link them to the main page.... someone help me out? send me an email if u have answers (jiwtech@ymail.com)

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (69.140.xx.xx) on Tue 3 Nov 2009 at 21:13
If you're still struggling to host multiple sites:

    Make sure your etc/apache2/ports.conf contains these two lines

      NameVirtualHost *:80
      Listen 80

    if NOT issue this command: (assuming you're in apache2 folder as shown below) and add those two line

     ruvan@ubuntu:/etc/apache2$ sudo gedit apache2.conf

    And secondly, add a file containing all your top and sub.domains to /sites-enabled folder as shown below by issuing the following command which should create and empty virtualhost file for our sites named website(.com/.net etc):

     ruvan@ubuntu:/etc/apache2$ sudo touch sites-enabled/website

    And add these lines(the minimal version) to the file we just created.

    #Add top domains as many as you need
   
              ServerName  website.com
        DocumentRoot /home/ruvan/www/website.com
        DirectoryIndex index.php index.html
   


   
              ServerName  website.net
        DocumentRoot /home/ruvan/www/website.net
        DirectoryIndex index.php index.html
   


    #And a sub domain for website.com (add as many as you require)
   
              ServerName  my.website.com
       
        #set subdomain folder created inside main domain website.com
        DocumentRoot /home/ruvan/www/website.com/my
       
        DirectoryIndex index.php index.html
   


    Note: You don't really need separate files for each and every domain. So to keep things simple I added one virtual host file to website.com (but you can ad as many as you need)
    Finally, the most imprtant step: you need to do is to map all the site names we just created in the etc/hosts to an IP (127.0.0.1 in this case), or unless you won't be able to access your named sites on the browser.

     127.0.1.1    website.com
     127.0.1.1    my.website.com
     127.0.1.1    website.net

Tested to work on Ubuntu9.1-x64 running VMWare Player on XPSP3.

ruvan@http://dealbit.com

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (70.43.xx.xx) on Fri 4 Dec 2009 at 16:22
Can


NameVirtualHost *:80
Listen 80


be


NameVirtualHost xxx.xxx.xxx.xxx:80
Listen 80


I would then assume that my ports.conf file would have to include the same as well as my sites-available file.

Thanks,
cdb

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (93.134.xx.xx) on Mon 26 Jul 2010 at 17:10
I have a question that is probably quite simple for most of the guys here, but it's been bugging the hell out of me for the past 2 days. I have enabled wildcard DNS on my server, and now want to create a redirect such that all subdomains and subdirs of those subdomains get redirected. So if someone puts in

subdomain.example.com/sub/dir

I want them to see the content that I have in this directory:

public_html/~subdomain/sub/dir

Thanks for the help :)

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by aditi (59.95.xx.xx) on Tue 17 Aug 2010 at 14:42
Hi,

I have three different sites with the same IP address using Name Virtual Host. My conf settings in httpd.conf redirects first two sites properly. But for the third Virtual Host block, it always redirects to the first address.

Please let me know if I am missing any settings. I have tried it a lot but www.code3.com always opens up the index page of www.code1.com.

Code:

NameVirtualHost 74.188.20.115


DocumentRoot "C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\Code1"
ServerName www.code1.com
DirectoryIndex Index.php



DocumentRoot "C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\Code2"
ServerName www.code2.com
ServerAlias code2.com
DirectoryIndex index.php



DocumentRoot "C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\Code3"
ServerName www.Code3.com
ServerAlias Code3.com
DirectoryIndex index.php


Any help will be highly appreciated. Thanks

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (180.216.xx.xx) on Thu 19 May 2011 at 16:31
Did you ever get a fix to this?
Mine is the same (with :80 at the end) and it does the same.

Tried everything!

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Dziamid (77.74.xx.xx) on Sun 29 Aug 2010 at 16:34
Unless I manually add entry '127.0.0.1 mydomainname' to /etc/hosts nothing works. But there's nothing about this file in the tutorial. What I am doing wrong? What does your /etc/hosts file looks like?

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (68.37.xx.xx) on Mon 12 Mar 2012 at 15:23
Yeah, I am having issues with this tutorial too. It only works if I add entries to the /etc/hosts file. Either I am missing something or the author forgot to add info about /etc/hosts or they assumed it was common knowledge.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (68.37.xx.xx) on Mon 12 Mar 2012 at 16:19
K, I was reading this again and in fairness to the author, they do say this in a non-explicit way.

"The only thing you need is for your domain names to resolve to the IP address of your webserver."

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (86.25.xx.xx) on Sun 14 Nov 2010 at 15:59
So I have follows the guide and still have come a few issues. Bellow is my setup

virtual.conf
#
# We're running multiple virtual hosts.
#
NameVirtualHost *:80

root@demigod:/home/usr# cat /etc/apache2/conf.d/virtual.conf
#
# We're running multiple virtual hosts.
#
NameVirtualHost *:80

root@demigod:/home/usr# cat /etc/apache2/sites-available/www.readmypcap.co.uk
#
# readmypcap.co.uk (/etc/apache2/sites-available/www.readmypcap.co.uk)
#

ServerAdmin webmaster@readmypcap.co.uk
ServerName www.readmypcap.co.uk
ServerAlias readmypcap.co.uk

# Indexes + Directory Root.
DirectoryIndex index.php index.html
DocumentRoot /var/www/www.readmypcap.co.uk/htdocs/

# CGI Directory
ScriptAlias /cgi-bin/ /var/www/www.readmypcap.co.uk/cgi-bin/

Options +ExecCGI



# Logfiles
ErrorLog /var/www/www.readmypcap.co.uk/logs/error.log
CustomLog /var/www/www.readmypcap.co.uk/logs/access.log combined


However when I try to browse this virtual domain I keep getting directed to my first default site. Have I over looked anything??

Thanks

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by chris (213.187.xx.xx) on Sun 14 Nov 2010 at 17:42
[ View Weblogs ]
Have you enabled the site (in other words - is the file www.readmypcap.co.uk also available under /etc/apache2/sites-enabled ? If not - you can use a2ensite www.readmypcap.co.uk to enable it.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (86.25.xx.xx) on Sat 4 Dec 2010 at 13:23
The site had been enabled. I ended up jumping on irc and asking some nice people there. After too many changes to remember I have apache2 and vhosts working as they should but thanks for the advises none the less

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by webminder (94.229.xx.xx) on Fri 11 Feb 2011 at 23:13
That guide in not complete, partially useful, but i lost a lot of time trusting this guide... as is made it doesn't work...i tested it on Debian Squeeze and i doesn't work... in order to let this guide work add:
- /etc/apache2/ports.conf configuration file.
- /etc/hosts file.
- and site-available are not configured correctly, please follow this guide instead:
http://serverfault.com/questions/1405/apache2-startup-warning-nam evirtualhost-80-has-no-virtualhosts

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by webminder (94.229.xx.xx) on Fri 11 Feb 2011 at 23:17
sorry the correct guide is this:
http://library.linode.com/web-servers/apache/installation/debian- 5-lenny#basic_system_configuration

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (207.34.xx.xx) on Sat 7 May 2011 at 01:40
Hi I have another config question scenario for you.
We have an Apache web server in a screened network
The server had 2 NICs in it. One used for Administration Management and the other for the Web traffic


The standard set up includes mulitple sites
1) admin
2) sponsor
3) guest

each of these sites allows differnt access rights.
Unfortunately Apache is running on All NIC interfaces.

I would like to know how I can configure Apache to run
1) Admin on the Management NIC
2) Sponsor on the Management NIC
and
3) Guest on the Web Traffic Nic

Is this possible with a single instance of Apache running, or do I have to run two separate instances on different NICs using the Listen directive

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (121.72.xx.xx) on Wed 1 Jun 2011 at 06:58
Thank you for the step by step. I had looked for a while on how to do this and yours is the clearest, most straight forward and working example I found.

Many thanks.
Shane

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by mitho7 (122.105.xx.xx) on Sun 17 Jul 2011 at 05:37
hello friends,

I'm using Debian GNU/Linux 6.0.2 (squeeze) and Apache 2.2. I have set the virtual hosting as per the example.

My site comes if i type full url (www.example.com/index.html) but if i do not use index.html (www.example.com/) comes up page cannot display. I have default site set up which works ok. if i type the ip address (http://192.168.1.3/) it can read the index.html.

I have dir module loaded. also have set up the DirectoryIndex index.html

under sites-available i have default:


ServerName no_vhost_entry:80
ServerAdmin webmaster@localhost

DocumentRoot /var/www/html/default


Options FollowSymLinks
AllowOverride None


Options Indexes FollowSymLinks MultiViews
AllowOverride Limit
Order allow,deny
allow from all


Header set Cache-Control no-cache


# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog /var/log/apache2/access.log combined
ErrorLog /var/log/apache2/error.log


under sites-available i have www.example.com:


ServerAdmin webmaster@example.com
ServerName www.example.com
ServerAlias example.com

# Indexes + Directory Root.
DirectoryIndex index.html
DocumentRoot /home/www/www.example.com/htdocs/

# CGI Directory
ScriptAlias /cgi-bin/ /home/www/www.example.com/cgi-bin/

Options +ExecCGI

# Logfiles
ErrorLog /home/www/www.example.com/logs/error.log
CustomLog /home/www/www.example.com/logs/access.log combined


please need some direction here.

Regards,
Bip

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by mitho7 (122.105.xx.xx) on Sun 17 Jul 2011 at 10:31
i feel so stupid now. it is working file. It's my browser mozilla, i clear the cache and working ok.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by alkhader (213.132.xx.xx) on Thu 20 Oct 2011 at 12:58
Thank you for this very helpful article.

I have done all the mentioned steps.

I have my own server and a static IP address and I want to show my websites on the browser and I want to access it via IP address? example: xxx.xxx.xxx.xxx/mywebsite/index.php

Kind Regards,

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (79.97.xx.xx) on Tue 29 Nov 2011 at 23:04
Fantastic article, even better are the questions and answers below. A wonderful resourse that is very hard to find elsewhere. The way you put it makes it clear. Thanks.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (109.232.xx.xx) on Tue 24 Jan 2012 at 05:49
If you added NameVirtualHost *:80 to virtual.conf, delete this string in file ports.conf

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (217.129.xx.xx) on Wed 14 Mar 2012 at 16:56
To all my Anonymous cousins who say this is not working and because I'm a bit pi**ed with some comments like "this guide doesn't work", on behalf of newcomers I'm here to tell

This way of doing multiple virtualhost websites WORKS even as per today (see my post date above).

It's almost P&P if you have the correct domains or virtual domains working well - don't expect having google.com pointing to any site you create; just take the time to read a bit all answers already posted on ways of doing things, then Plug & Pray. If you don't like then just unPlug & Pay other options in the "market" and do not post negative comments.

Thank you Steeve for your time and patience.

LuizCB

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by RTamas (176.63.xx.xx) on Sun 13 May 2012 at 16:37
I did everything correctly that the article mentioned, but I'm having some issues here. First of all when I try to open example.com or www.example.com my browser redirects me to an external webpage.

Any idea what might causing this issue?
Note: Do I have to set anything in /etc/hosts?

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (207.182.xx.xx) on Mon 31 Dec 2012 at 15:13
tnx a milllllliooooooon

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (86.173.xx.xx) on Thu 23 May 2013 at 10:49
Brilliant, many thanks for that.

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (74.215.xx.xx) on Sat 10 Aug 2013 at 02:32

When I go to example.com it shows up all working BUT
When I go to example2.com it shows up the same as example.com when it should be different

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Agen_Terminator (82.25.xx.xx) on Sat 19 Oct 2013 at 18:30
As obvious as it is, before anyone spends as much time as I did scratching their head and placing/removing NameVirtualHost in loads of files to get it to work, remember you need to setup etc/hosts!

[ Parent | Reply to this comment ]

#
Re: Hosting multiple websites with Apache2
Posted by Anonymous (212.110.xx.xx) on Fri 4 Apr 2014 at 18:03
I had trouble setting up virtual hosts on Debian. Here are my conf files so you don't have to fix it like I did with brute force!!!
Maybe this will help if you get problems setting this up. Good luck

################################################################# ##################
#Last end of apache2.conf file No changes were made here
################################################################# ##################
.
.
.

# Include of directories ignores editors' and dpkg's backup files,
# see the comments above for details.

# Include generic snippets of statements
Include conf.d/

# Include the virtual host configurations:
Include sites-enabled/

################################################################# ##################
#virtual.conf (Notice it is disabled, I changed alot of items and now it all works not changing anything now)
################################################################# ##################

#
# This is the virtual hosts configuration file
#
#NameVirtualHost *


################################################################# ##################
# ports.conf
################################################################# ##################
# ports.conf

# If you just change the port or add more ports here, you will likely also
# have to change the VirtualHost statement in
# /etc/apache2/sites-enabled/000-default
# This is also true if you have upgraded from before 2.2.9-3 (i.e. from
# Debian etch). See /usr/share/doc/apache2.2-common/NEWS.Debian.gz and
# README.Debian.gz

NameVirtualHost *
Listen 80


# If you add NameVirtualHost *:443 here, you will also have to change
# the VirtualHost statement in /etc/apache2/sites-available/default-ssl
# to
# Server Name Indication for SSL named virtual hosts is currently not
# supported by MSIE on Windows XP.
Listen 443



Listen 443


################################################################# ##################
#sites-available directory
################################################################# ##################

default www.example.com www.example.net default-ssl


################################################################# ##################
#Default
################################################################# ##################



ServerAdmin webmaster@localhost

DocumentRoot /var/www

Options FollowSymLinks
AllowOverride None


Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all


ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/

AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all


ErrorLog ${APACHE_LOG_DIR}/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog ${APACHE_LOG_DIR}/access.log combined


################################################################# ##################
# www.example.com (/etc/apache2/sites-available/www.example.com)
################################################################# ##################

#
# www.example.com (/etc/apache2/sites-available/www.example.com)
#

ServerAdmin webmaster@example.com
ServerName www.example.com
ServerAlias example.com

# Indexes + Directory Root.
DirectoryIndex index.html
DocumentRoot /var/www/www.example.com/htdocs/

# CGI Directory
ScriptAlias /cgi-bin/ /var/www/www.example.com/cgi-bin/

Options +ExecCGI


# Logfiles
ErrorLog /var/www/www.example.com/logs/error.log
CustomLog /var/www/www.example.com/logs/access.log combined


################################################################# ##################
# www.example.net (/etc/apache2/sites-available/www.example.net)
################################################################# ##################

#
# www.example.net (/etc/apache2/sites-available/www.example.net)
#

ServerAdmin webmaster@example.net
ServerName www.example.net
ServerAlias example.net

# Indexes + Directory Root.
DirectoryIndex index.html
DocumentRoot /var/www/www.example.net/htdocs/

# CGI Directory
ScriptAlias /cgi-bin/ /var/www/www.example.net/cgi-bin/

Options +ExecCGI


# Logfiles
ErrorLog /var/www/www.example.net/logs/error.log
CustomLog /var/www/www.example.net/logs/access.log combined

Send Email With CodeIgniter

$
0
0
Send your email forwarding from guestbook maybe or ticketing support with CodeIgniter Email Library or using third party server.
case if using Mandrill
Sending Email from CodeIgniter with Mandrill
The last time I used CodeIgniter in my project was about two years ago. It was an online property marketplace where people can collectively buy expensive houses by sharing ownership of the house and, of course, sharing the mortgage. There was these times when I had my dead-end building an application module to send email to customers, some sort of news letter. The dead-end was actually due to google SMTP limitation on relaying email from my application. If you are on a project that still rely on Google's SMTP to send email, I suggest you migrate to Mandrill.
Mandrill
Mandrill is a transactional email platform from MailChimp. By definition Mandrill is a transactional email platform, which can use to relay emails from our application. Of course there is a price for their services, but as long as we are sending less than 12,000 emails per month we are eligible for free services. It is easy though to scale up if we need to send more than 12,000 emails in a month. Just upgrade your package without re-signing-up your account.
CodeIgniter Mail Library

In order to get our mailing module work, we need to register to mandrill to get our SMTP credentials. To do so, go ahead and open your favorite browser (mine is Chrome) and enter http://www.mandrill.com at the address bar.
Click the Sign Up button to create a new account on Mandrill. This is very easy because all you need to fill is just your email address and your Mandrill password. Note that your mandrill password is not your SMTP password.
After signing up, there is going to be an optional profile form that you may or may not fill. I will skip this form for now by clicking the No, Thanks button on the left bottom of the form.
Next step is to click the Get SMTP Credentials button.
 And then type in your Mandrill password when prompted.
Mandrill will create and display your SMTP account detail afterward. Now, to get your SMTP password, click on the + Add API Key button below your SMTP credentials.
Up to this point you should see a new API key. This key (or one of these keys, if you have more than one) can be your SMTP password.
Go on and replace those hash-tags on our email configuration. Go to directoryapplication/config/ and open file email.php, then edit the file matching your Mandrill SMTP credentials.
$config['smtp_host'] = 'smtp.mandrillapp.com';
$config['smtp_user'] = 'my-email@address.com';
$config['smtp_pass'] = 'th1s-1s-y0ur-p4ssw0rd!';
$config['smtp_port'] = '587';
That's it!
Now try to run your script on your browser, and give a comment below if you're having trouble. By the way, to prove you that this tutorial works (even from http://localhost setup on your computer), this what it looks like when I checked my email:
Sample script on Controller Mandrill ThirdParty :

Sample script on Controller with Email Library CI :

note :
If you used Codeigniter, Library can colaborate automatically with config at folder application/config just with 1 condition = file name of library n config is same.If you used hosting for your app or app is gone public, please check your setting on server hosting to combine/allowed port that used (465 google or 587 mandrill)
x

How to create and execute JAR file in Java – Command line Eclipse Netbeans

$
0
0
Creating JAR file in java from command prompt is always been little tricky for many of us even if IDE like Netbeans and Eclipse provide support to export java program as JAR file simply because we don’t create jar often and not familiar with manifest file or jar command as whole. JAR file in Java is a kind of zip file which holds all contents of a Java application including Class files, resources such as images, sound files and optional Manifest file. JAR stands for Java Archive and provides a platform independent deliverable for java programs, libraries and framework. you can execute same jar file in any operating system e.g. Windows 7, windows 8, Macintosh or Linux. Apart from platform independence and standard delivery method jar file also provides compression of contents which results in faster download if you are downloading java program from internet specially in case of mobile devices where you install Java program by OTA. In this article we will some JAR command examples and learn how to create and execute jar filehow to view contents of jar file from command prompt and Eclipse and Netbeans.

How to create jar file in Java form command prompt

Example to create and execute JAR file in Java from Command line Eclipse and Netbeansjar command in Java allows you to create jar file from command prompt, what is required is that you must have jar command included in System PATH variable. you can check this by typing "jar" in command prompt if it doesn't throw error as "jar is not recognized as an internal or external command" they you are ready to go. When you create jar file in Java, command also creates Manifest file which is optional and you can control whether to create it or not by jar command line options, but if you want to create executable jar file they you must need Manifest file which we will discuss in further sections. Now here is jar command example to create jar file from command prompt, this will work both in windows and Linux operating system.

JAR command Examples in Java


javin@localhost:~/Java jar -cvf HelloWorld.jar HelloWorld.class
added manifest
adding: HelloWorld.class(in = 450) (out= 311)(deflated 30%)

This command will crate Helloworld. jar which contains Helloworld.class file. this will also create manifest file but without Main-Class entry as shown below:

javin@localhost:~/Java cat MANIFEST.MF
Manifest-Version: 1.0
Created-By: 1.6.0-beta2 (Sun Microsystems Inc.)

This jar can not be executed and you will get error when you try to run this jar file:

javin@localhost:~/Java java -jar HelloWorld.jar
Failed to load Main-Class manifest attribute from HelloWorld.jar

You just need to provide Main-Class entry to get rid of this error which we will see in coming Section.

How to Create an executable JAR file in Java

To create an executable JAR in Java, you need to provide a manifest file and include your Main Class in Manifest. When you create jar file , jar command also creates manifest file inside META-INF as MANIFEST.MF but doesn't create Main-Class entry which is required for executable jar file. You can create executable jar file in Java by two ways either provide a self created Manifest file or specify entry point using "-e" jar option. If you provide external Manifest file than you need to use jar -m option to include that manifest file inside jar. Let's see example of both ways to create executable jar file in Java.

Executable JAR File Example with External Manifest

1.Create MANIFEST.MF file by using any text editor e.g. notepad in windows or Vim in Unix and add following entry in file, remember last line must end with either new line or carriage return:

Manifest-version: 1.0
Main-Class: HelloWorld

Important thing to remember is that we need to specified full classified class name here. suppose if our main class was inside com/example/HelloWorld than we should have to specify com.example.HelloWorld here, don't put .class extension here its not required. Apart from specifying Main-Class you can also specify Java Classpath in Manifest file which is important if your application is depended on external library jars. "Classpath" entry supersede both -cp and CLASSPATH environment variable. to learn more see How ClassPath works in Java.

2.Execute following jar command to create executable jar

javin@localhost:~/Java jar -cvfm HelloWorld.jar MANIFEST.MF HelloWorld.class
added manifest
adding: HelloWorld.class(in = 450) (out= 311)(deflated 30%)

here -m is used for including manifest file and remember specify name of manifest file after jar name. now you have an executable jar file in java which you run by command specified earlier.

Creating Executable JAR File By entry point

This seems to me an easy way to create executable jars in Java, as you need not have to create manifest file explicitly and it will be create by jar command itself along with Main-Class entry. What you need to provide is a new jar option "-e" and you main class name while running jar command. here is example of jar command with entry option:

javin@localhost:~/Java jar -cvfe HelloWorld.jar HelloWorld HelloWorld.class
added manifest
adding: HelloWorld.class(in = 450) (out= 311)(deflated 30%)

jar -e for entry point and entry point or main class name should come after jar file name and before directory or file needs to be included in JAR. You can now run your executable jar file by issuing "java -jar" command as shown in following example:

javin@localhost:~/Java java -jar HelloWorld.jar
Executing Java Program from JAR file


How to execute Java Program from Jar file

Executing jar program from jar archive is very easy one thing required is jar must be executable and must have Main-Class entry in MANIFEST.MF file. here is a Java command example for running java program from jar file:

javin@localhost:~/Java java -jar HelloWorld.jar
Executing Java Program from JAR file

here we have specified jar file name with -jar option and it will run main class declared as “Main-Class” attribute in manifest file.

How to view contents of a JAR file in Java

jar command in Java allows you to view files and directories inside of a jar file without extracting or unzipping original jar. "-t" jar option is used to list files from jar archive as shown in jar command example below:

javin@localhost:~/Java jar -tvf HelloWorld.jar
0 Wed Dec 07 22:36:12 VET 2011 META-INF/
95 Wed Dec 07 22:36:12 VET 2011 META-INF/MANIFEST.MF
450 Wed Dec 07 21:36:04 VET 2011 HelloWorld.class

here "-t" for listing and "-v" and "-f" for verbose and jar file name.

How to extract contents of JAR File

use jar option "-v" for extracting files form JAR files as shown in jar command example below:

javin@localhost:~/Java jar -xvf HelloWorld.jar
created: META-INF/
inflated: META-INF/MANIFEST.MF
inflated: HelloWorld.class

here -x for extracting , -v is for verbose and -f specify jar file name.

How to create jar file in Eclipse

Creating JAR file in  Eclipse IDE is a cakewalk once you know the process. here is step by step guide of creating JAR file from Eclipse IDE: In Jar file main class is specified as “Main-Class” attribute inside manifest file and used as program entry point if you double click on JAR or run jar from java command.

1) Select Project for which you want to create jar file.
2) Go to File Menu and select Export
3) Expand Java folder and select JAR file

Now you just need to click next and follow instruction as displayed. you can select what contents you want to export to jar file and specify Main Class entry as well. If you like Eclipse IDE then you may like my earlier post on eclipse as well e.g. Java debugging tips in Eclipse and  How to setup java remote debugging in Eclipse.


How to create jar file in Netbeans

In Netbeans to create jar file you need to build the project which execute project ant file and creates JAR file inside dist folder. You can go on properties of project and specify main class there which will be run when you run the project and same will be used to create “Main-Class” attribute in JAR file.

jar is not recognized as an internal or external command

if you get this error while executing jar command from command prompt in Windows or Unix it means your Java Path is not set properly. JAR command is a binary which resides in JDK_HOME/bin folder where JDK_HOME is JDK installation directory. In order to use jar command from command prompt this bin folder must be in your System's PATH variable. Don't worry if its not there in PATH you can check this link to Set PATH for Java in Windows and Unix.It shows how you can do it in both Windows and Unix. Once your PATH is property set, you will see following output when you execute jar command from command  line:

javin@localhost:~ jar
Usage: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...
Options:
-c  create new archive
-t  list table of contents for archive

and now you are ready to use jar from command prompt.


WAR and EAR -  related JAR like fies in Java


WAR file
WAR file in Java stands for Web application archive and it is used to package a Java application together you can package all your ServletJSP, CSS, images, html in one WAR file and then deploy it to any Java web or application server like Tomcat, Weblogic or webshere. WAR files provide a clean and faster way to package and deploy Java web application just like JAR file provides for core java apps. Since WAR file also compacts resources inside it is comparatively download faster than downloading individual components.

EAR file
EAR file stands for Enterprise Java Archive and used to package an Enterprise Java application, like earlier WAR and JAR file. What separates EAR archive to WAR file is inclusion of Enterprise Java Beans(EJB). EAR file contains all web resources including Servlet, JSP, html, javascript, css, images along-with EJB. You can not deploy EAR files into web servers like Tomcat because it doesn't support EJB and can only be deploy-able in Application servers like WebSphere or Weblogic.

JAR File format in Java

Few words about java jar file format, its similar to zip format and use .jar extension. you can open JAR file in windows by using either winzip or winrar zip utilities.

That’s all on how to create jar file from command line, Eclipse, Netbeans. How to extract contents, how to run Java program from jar file etc. Let me know if you face any issue while creating JAR file in java.


Read more: http://javarevisited.blogspot.com/2012/03/how-to-create-and-execute-jar-file-in.html#ixzz3aSfGLiyW



Viewing all 40 articles
Browse latest View live


Latest Images