TechnoBase |
DBMS | MySQL | Oracle | Microsoft .NET |
Mainframes
![]() |
Unix/Linux |
total-vm total virtual memory used by the process (in 4kB pages) rss resident memory used (RAM) anon-rss resident anonymous memory file-rss resident file mappings shmem-rss resident shmem memory
/usr/bin/ additional user commands /usr/include/ standard system header files /usr/lib/ more programming and system call libraries /usr/local/ typically a place where local utilities are placed /usr/man the manual pages are kept here
/dev/ where special files are kept /bin/ executable system utilities, like sh, cp, rm /lib/ operating system and programming libraries /tmp/ system scratch files (all users can write here) /lost+found/ where the file system checker puts detached files
Back
/etc/ - system configuration files and databases /etc/hosts - IP to hostname mappings /etc/httpd.conf - has information about the Apache HTTP server (httpd) /etc/group - contains the names of valid groups and the usernames of their members. This file is owned by root and only root may modify it /etc/passwd - is the password file. Each line in the file holds all the information on a single user /etc/security/limits.conf - allows setting resource limits for users /etc/syslogd.conf - has information about the syslog daemon (syslogd), which helps to manage system and application logsHardware configuration
mount - display all currently attached file systems mount device directory - attach a file system umount device or directory - detach a mounted file system
* hard nofile 65535 * soft nofile 8192To increase the number of file descriptors for a specific user, use
mysql hard nofile 100000 mysql soft nofile 10000If systemd is used, then the following line needs to be appended in the [service] section of /usr/lib/systemd/system/mysqld.service
LimitNOFILE=100000
mount -t auto /dev/cdrom /mnt/cdrom - mounting a CDROM driveThe contents of the CD appears in the directory /mnt/cdrom.
umount /media/cdrom - unmountlsblk
lsblkConfiguring a sound card in Linux
cdplay - play CD cdplay stop - stop CD cdplay play 4 - play 4th track eject - stop and eject the CDSoftware Configuration
BASH - path of the BASH executable file BASH_ENV - path of the BASH environment file, which specifies BASH options BASH_VERSION - version of BASH COLUMNS - width, in characters, of console window EUID - effective user ID HISTFILE - path of the BASH command history file HISTSIZE/HISTFILESIZE - maximum number of commands/lines recorded in history file HOME - path of user's home directory HOSTNAME - name of the host IFS - field separator (white space) characters LINES - length, in lines, of console window LOGNAME - user's login name LS_COLORS - color options for ls command MAIL - specifies where mail is put OSTYPE - operating system name ('Linux') PATH - specifies directories where commands are to be located PPID - process ID of the shell's parent process PRINTER - tells Unix what to use as a default printer PS1 - command prompt string PS2 - continuation prompt string PS4 - execution trace string PWD - current working directory SHELL - path of the shell executable SHLVL - number of nested shell invocations TERM - terminal type UID - user ID USER - user name
#include <stdlib.h> char *getenv(const char *name);Setting the value of an environment variable is done by using putenv().
#include <stdlib.h> int putenv(char *string);Obtaining the whole list of environment variables
#include <stdio.h> extern char **environ; int main() { char **ep = environ; char *p; while ((p = *ep++)) printf("%s\n", p); return 0; }Viewing system information
cat /proc/cpuinfo show CPU info cat /proc/meminfo show memory info cat /proc/version show version infosystemd
Unit Type File Extension Description --------- -------------- ----------- Service unit .service A system service Target unit .target A group of systemd units Automount unit .automount A file system automount point Device unit .device A device file recognized by the kernel Mount unit .mount A file system mount point Path unit .path A file or directory in a file system Scope unit .scope An externally created process Slice unit .slice A group of hierarchically organized units that manage system processes Snapshot unit .snapshot A saved state of the systemd manager Socket unit .socket An inter-process communication socket Swap unit .swap A swap device or a swap file Timer unit .timer A systemd timerSystemd Unit Files Locations
Directory Description --------- ----------- /usr/lib/systemd/system/ Systemd unit files distributed with installed RPM packages. /run/systemd/system/ Systemd unit files created at run time. This directory takes precedence over the directory with installed service unit files. /etc/systemd/system/ Systemd unit files created by systemctl enable as well as unit files added for extending a service. This directory takes precedence over the directory with runtime unit files.
Back
KERN_EMERG 0 system is unusable KERN_ALERT 1 action must be taken immediately KERN_CRIT 2 critical conditions KERN_ERR 3 error conditions KERN_WARNING 4 warning condition KERN_NOTICE 5 normal but significant condition KERN_INFO 6 informational KERN_DEBUG 7 debug-level messagesThe messages typically go to the appropriately named files in the directory /var/log/kernel
Back
! elif fi in while case else for then {* do esac if until } doneIn some systems, function, select, [[ and ]] are also considered as reserved words.
dircolors -p output defaults Default colors bright red - compressed/archive files green - executables blue - directory cyan - symbolic linkls - lists all files in a directory
ls -a - includes files beginning with a period in the list ls -R - produces a recursive listing of all files and subdirectories under the current directory ls -l - includes additional information (mode, number of links, owner, group, size and last modified time) for each file ls |more - lists files page by page (use Space key to move to next page)mkdir - creates a new directory
mv currentfile newfilepwd - show present working directory
scp [-P port] /path/to/file username@destserver:/path/to/destinationViewing and editing files
cat filename | more - view a textfile, one page at a time cat filename | less or less filename - scroll through text file one line at a time, press q to exithead - print first 10 lines of the text file
head filenametail - print last 10 lines of the text file
tail filenamepico - edit a text file using the pico editor
pico filenamemore - view file, page by page (use space key to move)
more filenametouch - create a new empty file
touch filenameProcess control commands
bg 2<Control Z> - suspends a foreground process
fg 2jobs - list background or stopped processes with their job numbers
jobskill - used to kill a job or a process
kill -l - list all available signals kill -9 <pid> - use SIGKILL (cannot be handled by the receiving process and forcefully terminates it)lsof - list all opened files
lsof -c mysql - list all files opened by mysql process lsof -p <pid>nice - run program name adjusting its priority
nice program_namepidof - find the process id of a running program
pidof mysqldpmap - report the memory map of a process
pmap <pid> pmap -x <pid> - show the extended formatps - lists the process ids of the processes being run, along with the terminal controlling the process, current process status and time spent
ps displays two processes, the shell and the ps command ps -efl view all processes ps -efl | grep mysql show processes of specific user ps -p <pidlist> show processes given in pidlist ps ax list all processes (using BSD syntax) ps -u <user> list processes associated with a user PROCESS STATE CODES D uninterruptible sleep (usually IO) R running or runnable (on run queue) S interruptible sleep (waiting for an event to complete) T stopped, either by a job control signal or because it is being traced W paging (not valid since the 2.6.xx kernel) X dead (should never be seen) Z defunct ("zombie") process, terminated but not reaped by its parentstop - suspends a background process
find / - name 'filename'grep - searches the named input files (or standard input if no files are named, or the file name - is given) for lines containing a match to the given pattern. By default, grep prints the matching lines
grep [options] PATTERN [FILE...] grep [options] [-e PATTERN | -f FILE] [FILE...]In addition, two variant programs egrep (same as grep -E) and fgrep (grep -F) are available.
locate filenamewhich - shows the full path of an executable that can be run from the command file
which executablefilenamewhereis - prints the location of the source, binary and manual pages for the command
whereis commandSystem information commands
df -h show disk free space in GB df -m show disk free space in MBfree - displays the total amount of free and used physical and swap memory in the system, as well as the buffers and caches used by the kernel, gathered by parsing /proc/meminfo
free free -m display in MB free -g display in GB free -h show all output fields scaled to shortest three digit unit and display the units free -m -s 5 display system memory usage every 5 seconds (Ctl+c to exit)hostnamectl - used to query and change the system hostname and related settings
hostnamectl or hostnamectl status show system hostname and related info hostnamectl hostname if no argument is given, prints the hostname. If argument is given, changes the hostnameiostat - used for monitoring system I/O statistics for devices and partitions
iostat -c display the CPU utilization report iostat -d display the device utilization report iostat -m display statistics in MB iostat -x display extended statistics %iowait - percentage of time the CPUs were idle during which the system had an outstanding disk I/O request tps - I/O requests issued to the device per second await - average time (in milliseconds) for I/O requests issued to the device to be served r_await/w_await - average time (in milliseconds) for read/write requests to be servedlocale - displays information about the current locale
locale locale -a list all available locales locale -k LC_CTYPE display values of all keywords in a locale categorytop - displays system information and list of processes in real time
top press q to quit top -n 10 quit after 10 refreshes top -u root display specific user processesuname - displays the system information such as hardware platform, system name and processor, OS type
uname -a show Linux version details uname -r display kernel versionuptime - gives a one line display of the current time, how long the system has been running, how many users are currently logged on and the system load averages for the past 1, 5, and 15 minutes
uptime -s system up sinceUser management commands
chmod [reference][operator][mode] file chmod [OPTION]... OCTAL-MODE file chmod [OPTION]... --reference=RFILE file
chmod o=rw file1.c - assign read/write access to otherspasswd - change password
passwdsudo - execute a command as a superuser or another user, as specified by the security policy. The security policy determines what privileges, if any, a user has to run sudo. The policy may require that users authenticate themselves with a password or another authentication mechanism.
sudo <command>Miscellaneous commands
echo Hello - writes Hello on the screen echo $var - displays the value of variable var echo $PATH - show user's path environment variable echo "create database tempdb" | mysql - creates a db in mysql serverread - read a line from the standard input and split it into fields
$ read Variable1 Variable2 Variable3 ... VariableNenv - list environment variables
env - list all environment variablesssh - start the ssh client program that enables secure connections to remote machines
ssh remote.host.com ssh alternateuser@remote.host.com - use a different usernamesync - writes any data buffered in memory out to disk by exercising the sync(2) system call. This can include modified superblocks, modified inodes and delayed reads and writes. This is implemented by the kernel
-a all current limits are reported -n the maximum number of open file descriptors -t the maximum amount of cpu time in seconds -u the maximum number of processes available to a single user -v the maximum amount of virtual memory available to the shell and to its children -T the maximum number of threads -H set the hard limit -S set the soft limit
Back
$ cd docs; mkdir old_docs; mv *.* old_docs - executed in order $ cp big_file new_dir& rm *.o& who - executed concurrentlyAborting a shell command
command &The job number is printed on the screen so the command can be brought to the foreground, if desired.
Back
user=fred box=m000 acct=mh0000The value of a variable is substituted by preceding its name with $
echo $user - echos fredCreating environment variables
set steps=39 echo $steps - see value
foreach var ( worddlist ) commandlist endThe commandlist is executed once for each word in the wordlist, and each time the variable var will contain the value of that word. For e.g, the following script can search all immediate subdirectories of the current directory for a given file (and then quit if it finds one)
#! /bin/csh -f set f = $1 foreach d (*) if (-e $d/$f) then echo FOUND: $d/$f exit(0) endif end echo $f not found in subdirectories
goto label1where label1 is a label on a line (by itself) somewhere in the script in the form
label1:
if ( expr ) simple-command OR if ( expr ) then commandlist-1 [else commandlist-2] endifExample
if ($#argv <> 2) then echo "you must give exactly two parameters" else set name1 = $argv[1] set name2 = $argv[2] endifswitch
switch (str) case string1: commandlist1 breaksw case string2: commandlist2 breaksw default commandlist endswControl flow is switched to where the first match occurs. As in file name expansion, a case label may be a literal string, or contain variable substitution, or contain wild-card character such as *,? etc.
while (expr) commandlist endThe commandlist will be executed until the expr evaluates to false.
break [n]Exits from the smallest enclosing for, while or until loop, if any, or from the nth enclosing loop if n is specified. The value of n is an unsigned integer >= 1 and the default is equivalent to n=1. If n is greater than the number of enclosing loops, the last enclosing loop is exited from. Execution will continue with the command immediately following the loop.
for i in * do if test -d "$i" then break fi done
: [argument ...]This utility will only expand command arguments. It is used when a command is needed, as in the then condition of an if command, but nothing is to be done by the command.
: ${X=abc} if false then : else echo $X fi abcAs with any of the special built-ins, the null utility can also have variable assignments and redirections associated with it, such as
x=y : > zwhich sets variable x to the value y (so that it persists after the null utility completes) and creates or truncates file z.
continue [n]The continue utility will return to the top of the smallest enclosing for, while or until loop, or to the top of the nth enclosing loop, if n is specified. This involves repeating the condition list of a while or until loop or performing the next assignment of a for loop, and reexecuting the loop if appropriate. n is an integer >= 1 and the default is n=1. If n is greater than the number of enclosing loops, the last enclosing loop is used.
for i in * do if test -d "$i" then continue fi done
. fileThe shell will execute commands from the file in the current environment. If file does not contain a slash, the shell will use the search path specified by to find the directory containing file. Unlike normal command search, however, the file searched for by the dot utility need not be executable. If no readable file is found, a non-interactive shell will abort; an interactive shell will write a diagnostic message to standard error, but this condition will not be considered a syntax error.
cat foobar foo=hello bar=world . foobar echo $foo $bar hello worldeval - construct command by concatenating arguments
eval [argument ...]The eval utility will construct a command by concatenating arguments together, separating each with a space character. The constructed command will be read and executed by the shell.
foo=10 x=foo y='$'$x echo $y $foo eval y='$'$x echo $y 10exec - execute commands and open, close or copy file descriptors
exec [command [argument ...]]The exec utility will open, close or copy file descriptors as specified by any redirections as part of the command. If exec is specified without command or arguments, and any file descriptors with numbers > 2 are opened with associated redirection statements, it is unspecified whether those file descriptors remain open when the shell invokes another utility. Scripts concerned that child shells could misuse open file descriptors can always close them explicitly. If exec is specified with command, it will replace the shell with command without creating a new process. If arguments are specified, they are arguments to command. Redirection will affect the current shell execution environment.
exec 3< readfile -- Open readfile as file descriptor 3 for reading exec 4> writefile -- Open writefile as file descriptor 4 for writing exec 5<&0 -- Make unit 5 a copy of unit 0 exec 3<&- -- Close file unit 3 exec cat file01 -- Cat the file file01 by replacing the current shell with the cat utilityexit - cause the shell to exit
exit [n]The exit utility causes the shell to exit with the exit status specified by the unsigned integer n. If n is specified, but its value is not between 0 and 255 inclusively, the exit status is undefined.
126 - a command to be executed was found, but the file was not an executable utility 127 - a command to be executed was not found > 128 - a command was interrupted by a signalA trap on EXIT will be executed before the shell terminates, except when the exit utility is invoked in that trap itself, in which case the shell will exit immediately.
exit 0 -- Exit with a true value exit 1 -- Exit with a false valueexport - set export attribute for variables
export name[=word]... export -pThe shell will give the export attribute to the variables corresponding to the specified names, which will cause them to be in the environment of subsequently executed commands.
"export %s=%s\n", name,valueThe -p option allows portable access to the values that can be saved and then later restored using, for instance, a dot script. The shell will format the output, including the proper use of quoting, so that it is suitable for reinput to the shell as commands that achieve the same exporting results. When no arguments are given, the results are unspecified.
export PWD HOME --> Export variables export PATH=/local/bin:$PATH --> Set and export the variable export -p > temp-file ---> Save and restore all exported variables unset a lot of variables ... processing . temp-filereadonly - set read-only attribute for variables
readonly name[=word]... readonly -pThe variables whose names are specified will be given the readonly attribute. The values of these variables cannot be changed by subsequent assignment, nor can those variables be unset by the unset utility. Some versions of the shell exist that preserve the read-only attribute across separate invocations.
"readonly %s=%s\n", name,valueThe shell will format the output, including the proper use of quoting, so that it is suitable for reinput to the shell as commands that achieve the same attribute-setting results. The -p option allows portable access to the values that can be saved and then later restored using, for instance, a dot script.
readonly HOME PWDreturn - return from a function
return [n]The return utility will cause the shell to stop executing the current function or dot script. If the shell is not currently executing a function or dot script, the results are unspecified. The results of returning a number greater than 255 are undefined because of differing practices in the various implementations. Some shells AND out all but the low-order 8 bits; others allow larger values, but not of unlimited size.
set [-abCefmnuvx][-h][-o option][argument...] set [+abCefmnuvx][+h][-o option][argument...] set --[argument...] set -[argument...]If no options or arguments are specified, set will write the names and values of all shell variables in the collation sequence of the current locale. Each name will start on a separate line, using the format
"%s=%s\n", name, valueThe value string will be written with appropriate quoting so that it is suitable for reinput to the shell, setting or resetting, as far as possible, the variables that are currently set. Read-only variables cannot be reset.
"[%d]%c %s%s\n", job-number, current, status, job-name-e - Exit if a command yields a nonzero exit status
set - Write out all variables and their values set c a b - Set $1, $2 and $3 and set $# to 3 set -xv - Turn on the -x and -v options set - - - Unset all positional parameters set - - "$x" - Set $1 to the value of x, even if x begins with - or + set - - $x - Set the positional parameters to the expansion of x, even if x expands with a leading - or +
shift [n]The positional parameters will be shifted. Positional parameter 1 will be assigned the value of parameter (1+n), parameter 2 will be assigned the value of parameter (2+n), and so on. The parameters represented by the numbers $# down to $#-n+1 will be unset, and the parameter "#" will be updated to reflect the new number of positional parameters. The value n will be an unsigned integer less than or equal to the value of the special parameter "#". If n is not given, it will be assumed to be 1. If n is 0, the positional and special parameters will not be changed.
$ set a b c d e $ shift 2 $ echo $* c d etimes - write process times
timesWrite the accumulated user and system times for the shell and for all of its child processes, in the following POSIX locale format
"%dm%fs %dm%fs\n%dm%fs %dm%fs\n", shell user minutes, shell user seconds, shell system minutes, seconds, children user minutes, seconds, children system minutes, secondsThe four pairs of times correspond to the members of the XSH specification
$ times 0m0.43s 0m1.11s 8m44.18s 1m43.23strap - trap signals
trap [action condition ...]If action is '-', the shell will reset each condition to the default value. If action is null ("), the shell will ignore each specified condition if it arises. Otherwise, the argument action will be read and executed by the shell when one of the corresponding conditions arises. The action of the trap will override a previous action (either default action or one explicitly set). The value of '$?' after the trap action completes will be the value it had before the trap was invoked.
Signal# Name 1 SIGHUP 2 SIGINT 3 SIGQUIT 6 SIGABRT 9 SIGKILL 14 SIGALRM 15 SIGTERMThe environment in which the shell executes a trap on EXIT will be identical to the environment immediately after the last command executed before the trap on EXIT was taken.
"trap - - %s %s ...\n", <action>, <condition>The shell will format the output, including the proper use of quoting, so that it is suitable for reinput to the shell as commands that achieve the same trapping results. For e.g
save_traps=$(trap) ... eval "$save_traps"Each time the trap is invoked, the action argument will be processed in a manner equivalent to
eval '$action'Signals that were ignored on entry to a non-interactive shell cannot be trapped or reset, although no error need be reported when attempting to do so. An interactive shell may reset or catch signals ignored on entry. Traps will remain in place for a given shell until explicitly changed with another trap command. When a subshell is entered, traps that are not being ignored are set to the default actions.
trap - write out a list of all traps and actions trap '$HOME/logout' EXIT or trap '$HOME/logout' 0 - set a trap so the logout utility in the directory will execute when the shell terminates trap - INT QUIT TERM EXIT - unset traps on INT, QUIT, TERM and EXITunset - Unset values and attributes of variables and functions
unset [-fv] name ...Each variable or function specified by name will be unset.
unset -v VISUAL - unset variable unset -f foo bar - unset the functions foo and bar
Back
#! /bin/csh -f foreach name ($argv) if ( -f $name ) then echo -n "delete the file '${name}' (y/n/q)?" else echo -n "delete the entire directory '${name}' (y/n/q)? " endif set ans = $< switch ($ans) case n: continue case q: exit case y: rm -r $name continue endsw endInvoking Shell scripts
sh filename [arg ...]
#! /bin/csh or #! /bin/csh -fThe file must be made executable using chmod ($ chmod u+x filename). Then it can be invoked in the same way as any other command, i.e., by typing the script file name on the command line.
Back
vi - start the vi editor vi file1 - open an existing file or create a new onevi has three modes of operation - command, insert and command line(escape). In the command mode, letters or sequence of letters interactively command vi and in the insert mode text is inserted. The escape mode is invoked by typing ':' while vi is in command mode and the cursor jumps to the last line and vi will wait for a command.
a append, enters insert mode and moves one position to the right i enter insert mode o enter insert mode, insert a blank line under the current cursor position and move the cursor to that line Esc switch back to command mode : enter command line modeMoving through the text is possible with the arrow keys or
h move the cursor to the left l move it to the right k move up j move down SHIFT-G puts the prompt at the end of the documentEditing commands
dd delete line n dd delete n lines starting from the current cursor position dw delete word n dw delete n words to the right side of the cursor x delete the character on which the cursor is positioned yy copy current line into storage buffer p paste after current line n p paste it n times :n moves to line n of the file :w save (write) the file :q exit the editor :q! forces the exit when quitting a file containing unsaved changes :wq save and exit :w newfile save the text to newfile :wq! overrides read-only permission (if user has the permission to override permissions, for instance when using the root account) :recover recover a file after an unexpected interruption :1, $s/word/anotherword/g replace word with anotherword throughout the fileSearch commands
/astring search the string in the file and position the cursor on the first match below its position / perform the same search again, moving the cursor to the next match
Back
22 SSH 25 SMTP 80 HTTP 1433 SQL Server DBMS 3306 MySQL DBMS 3389 Microsoft RDP 5432 PostgreSQL DBMS 8080 Alternative port for HTTPTelnet
telnet 203.117.234.45 3389 - connect to a host and port Ctl + ] - to go to telnet prompt quit - exit telnetPuTTY
perror [options] errcode
Error# Error code 110 ETIMEDOUT Connection timed out 111 ECONNREFUSED Connection refused 112 EHOSTDOWN Host is down 113 EHOSTUNREACH No route to host
Back
Blue - low priority processes (nice > 0) Green - normal (user) processes Red - kernel processes Yellow - IRQ time Magenta - soft IRQ time Grey - IO Wait timeMemory usage:
Green - used memory pages Blue - buffer pages Yellow - cache pagesProcesses:
S for sleeping (idle) R for running D for disk sleep (uninterruptible) Z for zombie (waiting for parent to read its exit status) T for traced or suspended (e.g by SIGTSTP) W for pagingVIRT - virtual memory used by the process
Back
char or signed char Character or integer 8-bits long Range -128 to 127 1 byte unsigned char Range 0 to 255 1 byte int unsigned or signed length depends on OS, 2 bytes or 4 bytes long int or long 4 bytes long short int or short 2 bytes long float floating point number 4 bytes double double precision floating point number 8 bytes long double long double precision floating point number 10 bytes bool boolean value true or false 1 byte wchar_t 2-bytes-wide character designed to store international characters
int a,b,c;Variables can be initialized in two ways
float a = 2.5; int a = 0; float a (2.5); int a (0);Integer data types (char, short, long and int) can be signed or unsigned. By default, they are signed. signed and unsigned may also be used as a simple types, meaning the same as signed int and unsigned int respectively.
signed x; //signed int x; unsigned y; //unsigned int y;Declaring and using constants
707 // unsigned integer constant -273 // signed integer 75 // decimal 0113 // octal(preceded by 0) 0x4b // hexadecimal(preceded by 0x) 3.14159 // floating point 6.02e23 // exponential constant 1.6e-19 // negative exponential constant 'z' // character "Hello world" // stringConstants can be declared by using a const prefix in front
const int width = 100; const char tab = '\t'; const zip = 12440;If type is not specified int is assumed.
\n newline \r carriage return \t tabulation \v vertical tabulation \b backspace \f page feed \a alert (beep) \' single quotes (') \" double quotes (") \? question (?) \\ inverted slash (\)
int i=12; size_t var = sizeof (i); size_t var = sizeof (int);
type name [elements]; int sockets [5]; //declares an integer array of five elements
int ports [5] = { 16, 2, 77, 40, 12071 }; char fname [5] = {'a','c','m','o','p'};
bool is_true() { return true; } int x = 10; int main() { if (is_true()) { cout << "b is true!\n"; } else { cout << "b is false!\n"; } if (x == 10) { x = 0; } }for statement
for (initialization; condition; increase) statement;The for statement works as follows
// countdown using a for loop #include <iostream.h> int main () { for (int n=10; n>0; n--) { cout << n << ", "; // outputs 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! } cout << "FIRE!"; return 0; }
switch (expression) { case constant1: block of instructions 1 break; case constant2: block of instructions 2 break; . . . default: default block of instructions }
while (condition) statement do statement while (condition);The functionality of both loops is exactly the same except that condition in the do-while is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled.
int divide (int a, int b) { return (a/b); } float divide (float a, float b) { return (a/b); }
char *ptr1; var1 = *ptr1;The address dereference operator (&) is used to assign a memory address to a pointer variable.
ptr1 = &var1; -- assign to pointer variable ptr1 the address of variable var1
// integer increaser void increase (void* data, int type) { switch (type) { case sizeof(char) : (*((char*)data))++; break; case sizeof(short): (*((short*)data))++; break; case sizeof(long) : (*((long*)data))++; break; } } int main () { char a = 5; short b = 9; long c = 12; increase (&a,sizeof(a)); increase (&b,sizeof(b)); increase (&c,sizeof(c)); cout << (int) a << ", " << b << ", " << c; return 0; } --> outputs 6, 10, 13
#ifndef __cplusplus #error A C++ compiler is required #endif /*abort the compilation process if the defined constant __cplusplus is not defined*/#include - When the preprocessor finds an #include directive it replaces it by the whole content of the specified file. There are two ways to specify a file to be included
#include "file" #include <file>#pragma - used to specify diverse options to the compiler. These options are specific for the platform and the compiler used
struct products { char name [30]; float price; } apple; products orange, melon;
struct movies_t { char title [50]; int year; }; movies_t amovie; movies_t * pmovie;Here amovie is an object of struct type movies_t and pmovie is a pointer to point to objects of struct type movies_t.
#include <iostream.h> #include <stdlib.h> int main () { char buffer[50]; movies_t amovie; movies_t * pmovie; pmovie = & amovie; cout << "Enter title: "; cin.getline (pmovie->title,50); cout << "Enter year: "; cin.getline (buffer,50); pmovie->year = atoi (buffer); cout << "\nYou have entered:\n"; cout << pmovie->title; cout << " (" << pmovie->year << ")\n"; return 0; }
Back
#include <iostream.h> int main () { char myarray[10]; try { for (int n=0; n<=10; n++) { if (n>9) throw "Out of range"; myarray[n]='z'; } } catch (char * str) { cout << "Exception: " << str << endl; } return 0; }
exception bad_alloc (thrown by new) bad_cast (thrown by dynamic_cast when fails with a referenced type) bad_exception (thrown when an exception doesn't match any catch) bad_typeid (thrown by typeid) logic_error domain_error invalid_argument length_error out_of_range runtime_error overflow_error range_error underflow_error ios_base::failure (thrown by ios::clear)
Back
#include <iostream.h> #include <fstream.h> int main() { char name[80]; ofstream outFile("junk.txt", ios::out); // Check if there was an error opening the file if (!outFile) { cout << "Unable to open the file\n"; return 1; } cout << "Enter your name: "; cin >> name; outFile << "This file was created by " << name << endl; outFile.close(); return 0; }Reading a sequential file is a simple case of opening the file and using the extraction operator to read the contents. The following example opens the file for reading, reads each word from the file, and writes each word read on a new line.
#include <iostream.h> #include <fstream.h> int main()
{ char buffer[80];
ifstream inFile("junk.txt", ios::in); // Check if there was an error opening the file if (!inFile) { cout << "Unable to open the file\n"; return 1; } while (inFile >> buffer) cout << buffer << endl; inFile.close(); return 0; }
pid_t pid; switch (pid = fork()) { case -1: /*the fork failed, some possible reasons are lack of process slots or virtual memory */ perror("The fork failed!"); break; case 0: /* pid of zero is the child */ /* child process functions go here */ /* ... */ _exit(0); default: /* pid greater than zero is parent getting the child's pid */ printf("Child's pid is %d\n",pid); }
Back
javac -classpath "." filename.javaCompilation produces the output bytecode file with a .class extension. To run the class, use
java -classpath "." classnameDisassembling java classes - The "javap" program included in the JDK disassembles .class files into reasonably legible, assembly like code.
javap -c HelloWorldClasspath
jar cf jar-file input-file(s) - creates a jar file jar tf jar-file - view contents of a jar file jar xf jar-file - extract contents of a jar file jar xf jar-file archived-file(s) - extracts specific files from a jar file java -jar app.jar - runs an application packaged as a jar file <applet code=AppletClassName.class archive="JarFileName.jar" width=width height=height> </applet> - invokes an applet packaged as a jar fileComparison of Java and C++
char | v byte -> short -> int -> long -> float -> double
class StringConvert { public static void main (String args[]) { String str = "25"; int i = Integer.valueOf(str).intValue(); System.out.println(i); long l = Long.valueOf(str).longValue(); System.out.println(l); str = "25.6"; float f = Float.valueOf(str).floatValue(); System.out.println(f); double d = Double.valueOf(str).doubleValue(); System.out.println(d); } }
x = 5; y = 0; y = x++; //Result will be x = 6, y = 5 x = 5; y = 0; y = ++x; //Result will be x = 6, y = 6Implicit narrowing conversion is done, when applied to byte, short or char.
outer: while (true) { inner: while (true) { break; // Exits the innermost loop break inner; // Also exits the innermost loop break outer; // Exits the outermost loop } }for
for (initialization; termination; increment) { statement // termination expression is evaluated before each iteration } // loop terminates when termination expression returns falsereturn
import java.util.Date; Date today = new Date(); switch (today.getDay) { case 0: //Sunday case 6: //Saturday System.out.println("It's Soccer Day!"); break; case 2: //Tuesday System.out.println("Tennis at 8:00 am"); case 1: //Monday case 5: //Friday System.out.println("Office Hours: 10:00 - 5:00"); break; } System.out.println("All done!");while and do-while
while (expression) { statement } do { statement(s) } while (expression); // expression returns a boolean valueComments
int[] a; String b[]; Object []c;Allocation
a = new int[10]; c = new String[arraysize];Initialization
for (int i = 0; i < a.length; a[i++] = 0);All the above three can be done in a single step.
int a[] = { 1, 2, 3 }; int a[] = new int[] { 1, 2, 3 }; // size should not be specified with the new statement in this case char [] charArray = {'a', 'b', 'c'}; String [] stringArray = {"A", "Four", "Element", "Array"};Array elements can be accessed with indexes. Array indexes start with 0 and are of the int datatype.
int arr[][] = new int[4][5]; - creates a 4x5 array
int arr[][] = new int[4][]; // allocate the four row arrays for (int i = 0; i < 4; i++) // initialize each of the four rows arr[i] = new int[i + 1]; // row i has i + 1 columns
public interface Price { public float price(); }Different classes can then implement the Price interface
public class Monopoly extends BoardGame implements Price { // other methods public float price() { return 14.95; } }When other code is passed an object, it can test whether the object implements Price with the instanceof operator. For e.g
if (o instanceof Price) System.out.println("Subtotal is " + o.price());Access levels for class members
class sampleClass { int x; //instance variable static int y; // class variable public int x() { //instance method return x; } static public int y() { //class method return y; } public void setX(int newX) { //instance method x = newX; } static public void setY(int newY) { //class method y = newY; } }
protected void finalize() throws Throwable { }Nested classes
abstract class item { public abstract float price(); }Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract.
Back
InputStreamReader isr = new InputStreamReader ( System.in ); BufferedReader br = new BufferedReader ( isr ); String s = null; try { while ( (s = br.readLine ()) != null ) { // do something } } catch ( IOException ioe ) { // exception handler }If it is needed to do some parsing of a line of input, Java provides a powerful and general facility through the java.io.StreamTokenizer.
InputStreamReader isr = new InputStreamReader ( System.in ); StreamTokenizer st = new StreamTokenizer ( isr ); int c; try { while ( true ) { switch ( c = st.nextToken () ) { case StreamTokenizer.TT_NUMBER: System.out.println ( "Read a number: " + st.nval ); break; case StreamTokenizer.TT_WORD: System.out.println ( "Read a word: " + st.sval ); break; case default: // do something in other cases (EOL, EOF, whitespace, quotes...) break; } } catch ( IOException ioe ) { // exception handler }
import java.util.*; public class Now { public static void main(String arg[]) { Calendar cal = Calendar.getInstance(TimeZone.getDefault()); String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT); sdf.setTimeZone(TimeZone.getDefault()); System.out.println("Now : " + sdf.format(cal.getTime())); } }The Date class
import java.lang.System; import java.util.Date; public class DateApp { public static void main(String args[]){ Date today = new Date(); String days[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; System.out.println("Today's date (locale conventions): " + today.toLocaleString()); System.out.println("Today's date (Unix conventions): " + today.toString()); System.out.println("Today's date (GMT conventions): " + today.toGMTString()); System.out.println("Year: " + today.getYear() + "Month: " + today.getMonth() + "Date: " + today.getDate()); System.out.println("Day: " + days[today.getDay()]); System.out.println("Hour: " + today.getHours() + " Minute: " + today.getMinutes() + " Second: " + today.getSeconds()); Date newYears2000 = new Date(100,0,1); System.out.println("New Years Day 2000: " + newYears2000.toString()); System.out.println("New Years Day 2000 is " + days[newYears2000.getDay()]); } }The SimpleDateFormat class
import java.util.*; import java.text.*; public class ShowToday { public static void main(String args[]) { ShowToday st = new ShowToday(); st.demo(); } public void demo() { System.out.println(easyDateFormat("dd MMMMM yyyy")); System.out.println(easyDateFormat("yyyyMMdd")); System.out.println(easyDateFormat("MM/dd/yy")); System.out.println(easyDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z")); System.out.println(easyDateFormat("EEE, MMM d, ''yy")); System.out.println(easyDateFormat("h:mm a")); System.out.println(easyDateFormat("H:mm:ss:SSS")); System.out.println(easyDateFormat("K:mm a,z")); System.out.println(easyDateFormat("yyyy.MMMMM.dd GGG hh:mm aaa")); } public String easyDateFormat (String format) { Date today = new Date(); SimpleDateFormat formatter = new SimpleDateFormat(format); String datenewformat = formatter.format(today); return datenewformat; } }The Stack class
StringTokenizer st = new StringTokenizer("this is a test"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); }prints the following output
this is a testThe Vector class
java.lang.Object | +--java.util.AbstractCollection | +--java.util.AbstractList | +--java.util.VectorEach vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector's storage increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.
Vector myVector = new Vector (); // Create an instance of class Vector myVector = new Vector(50); // or suggest an initial vector size for (int i = 1; i <= 20; i++) //add some objects { myVector.addElement( new String ("I am string " + i)); } System.out.println ("Element : " + myVector.elementAt(5) ); // Peek at element 5 for (Enumeration e = myVector.elements(); e.hasMoreElements();) // Traverse entire list, printing them all out { String myString = (String) e.nextElement(); System.out.println(myString); }
Back
Throwable | ------------------------ | | Error Exception | RuntimeException
class TemperatureException extends Exception {} class TooColdException extends TemperatureException {} class TooHotException extends TemperatureException {} class VirtualPerson { private static final int tooCold = 65; private static final int tooHot = 85; public void drinkCoffee(CoffeeCup cup) throws TooColdException, TooHotException { int temperature = cup.getTemperature(); if (temperature <= tooCold) { throw new TooColdException(); } else if (temperature >= tooHot) { throw new TooHotException(); } //... } //... }Exceptions which are thrown by a method but not tackled with appropriate catch blocks need to be specified in the signature of the method by using the throws clause. These exceptions are passed up to the subsequent methods in the invocation stack.
import java.io.*; class ReadRawData { public static void main (String args[]) { boolean done = false; byte b[] = new byte[1024]; int num_bytes = 0; FileInputStream fin = null; try { fin = new FileInputStream(args[0]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("No file name"); System.exit(0); } catch (FileNotFoundException e) { System.out.println("File not found " + args[0]); System.exit(0); } catch(IOException e) { System.out.println("Error opening input file " + args[0]); System.exit(0); } catch (Exception e) { System.out.println("Unexpected exception: " + e); System.exit(0); } try { num_bytes = fin.read(b); } catch(IOException e) { System.out.println("Finished Reading: " + e); done = true; } catch (Exception e) { System.out.println("Unexpected exception: " + e); System.exit(0); } while(!done) { System.out.write(b, 0, num_bytes); try { num_bytes = fin.read(b); } catch(IOException e) { System.out.println("Finished Reading: " + e); done = true; } catch (Exception e) { System.out.println("Unexpected exception: " + e); System.exit(0); } if (num_bytes == -1) done = true; } } }To read data from a file line by line, a BufferedReader can be used:
String s; FileInputStream parmFile = new FileInputStream ("custmaint.ini"); BufferedReader br = new BufferedReader (new InputStreamReader (parmFile)); while ( (s = br.readLine()) != null) { System.out.println (s); }Writing data to a file
import java.io.*; class PrintToAFile { public static void main (String args[]) { try { FileOutputStream fout = new FileOutputStream("test.out"); //open file PrintStream ps = new PrintStream(fout); //convert the FileOutputStream into a PrintStream ps.println("Hello There!"); //write some data ps.println(1 + " + " + 1 + " = " + (1+1)); } catch (IOException e) { System.out.println("Error opening file: " + e); System.exit(1); } } }Appending data to a file
public FileOutputStream(String name, boolean append) throws IOException
Back
//get IP address InetAddress inet = InetAddress.getByName("www.java.com"); System.out.println ("IP : " + inet.getHostAddress()); //get hostname InetAddress inet = InetAddress.getByName("209.204.220.121"); System.out.println ("Host: " + inet.getHostName());The Socket class
import java.net.*; import java.io.*; public class getwebURL { public static void main(String args[]) throws Exception { try { if (args.length != 1) // check if a parameter was entered { System.err.println ("Invalid command parameters"); // print message, pause, then exit System.in.read(); System.exit(0); } URL url = new URL(args[0]); // create a URL instance InputStream in = url.openStream(); // get an input stream for reading BufferedInputStream bufIn = new BufferedInputStream(in); // create a buffered input stream for efficiency for (;;) // repeat until EOF { int data = bufIn.read(); if (data == -1) // check for EOF break; else System.out.print ( (char) data); } } catch (MalformedURLException mue) { System.err.println ("Invalid URL"); } catch (IOException ioe) { System.err.println ("I/O Error - " + ioe); } } }Sending data to a web server
URL url = new URL("http://www.swengg.com/script"); URLConnection connection = url.openConnection(); connection.setDoOutput (true); PrintWriter out = new PrintWriter (connection.getOutputStream()); out.print(name1 + "=" + URLEncoder.encode(value1) + "&"); out.print(name2 + "=" + URLEncoder.encode(value2) + "\n"); out.close();
import java.io.*; import java.util.*; public class serialize1 { public static void main(String[] aArguments) { List quarks = new ArrayList(); //create a Serializable List quarks.add("up"); quarks.add("down"); quarks.add("strange"); quarks.add("charm"); quarks.add("top"); quarks.add("bottom"); //serialize the List //note the use of generic interface references //declared here only to ensure visibility in finally clause ObjectOutput output = null; try{ OutputStream file = new FileOutputStream( "quarks.ser" ); //use buffering OutputStream buffer = new BufferedOutputStream( file ); output = new ObjectOutputStream( buffer ); output.writeObject(quarks); } catch(IOException ex){ System.out.println ("Cannot perform output."); } finally{ try { if (output != null) { //flush and close "output" and its output.close(); //underlying streams } } catch (IOException ex ){ System.out.println ("Cannot close output stream."); } } //deserialize the quarks.ser file. Note the use of generic interface references ObjectInput input = null; //declared here only to ensure visibilty // in finally clause try{ InputStream file = new FileInputStream( "quarks.ser" ); //use buffering InputStream buffer = new BufferedInputStream( file ); input = new ObjectInputStream ( buffer ); //deserialize the List ArrayList recoveredQuarks = (ArrayList)input.readObject(); //display its data Iterator quarksItr = recoveredQuarks.iterator(); while ( quarksItr.hasNext() ) { System.out.println( (String)quarksItr.next() ); } } catch(IOException ex){ System.out.println ("Cannot perform input."); } catch (ClassNotFoundException ex){ System.out.println ("Unexpected class found upon input."); } finally{ try { if ( input != null ) { //close "input" and its underlying streams input.close(); } } catch (IOException ex){ System.out.println ("Cannot close input stream."); } } } }
public interface Calculator extends java.rmi.Remote { public long add(long a, long b) throws java.rmi.RemoteException; }2. Write and compile Java code for implementation classes
public class CalculatorImpl extends java.rmi.server.UnicastRemoteObject implements Calculator { // Implementations must have an explicit constructor // in order to declare the RemoteException exception public CalculatorImpl() throws java.rmi.RemoteException { super(); } public long add(long a, long b) throws java.rmi.RemoteException { return a + b; } }3. Generate Stub and Skeleton class files from the implementation classes
>rmic CalculatorImpl4. Write Java code for a remote service host program
import java.rmi.Naming; public class CalculatorServer { public CalculatorServer() { try { Calculator c = new CalculatorImpl(); Naming.rebind("rmi://localhost:1099/CalculatorService", c); } catch (Exception e) { System.out.println("Trouble: " + e); } } public static void main(String args[]) { new CalculatorServer(); } }5. Develop Java code for RMI client program
import java.rmi.Naming; import java.rmi.RemoteException; import java.net.MalformedURLException; import java.rmi.NotBoundException; public class CalculatorClient { public static void main(String[] args) { try { Calculator c = (Calculator) Naming.lookup("rmi://localhost/CalculatorService"); System.out.println( c.add(4, 5) ); } catch (MalformedURLException murle) { System.out.println("MalformedURLException" + murle); } catch (RemoteException re) { System.out.println("RemoteException" + re); } catch (NotBoundException nbe) { System.out.println("NotBoundException" + nbe); } catch (java.lang.ArithmeticException ae) { System.out.println("java.lang.ArithmeticException" + ae); } } }6. Install and run the RMI system
>rmiregistry
>java CalculatorServer
>java CalculatorClient
public class MyThread implements Runnable { private String holdA = "This is "; private int[] holdB = {1,2,3,4,5,6,7,8,9,10}; public static void main(String args[]) { MyThread z = new MyThread(); ( new Thread(z) ).start(); ( new Thread(z) ).start(); } // Any object implementing a synchronized keyword is a monitor: public synchronized void run() { for(int w = 0;w < 10;w++) { System.out.println(holdA + holdB[w] + "."); } } }
Back
Class.forName("my.sql.Driver");When the getConnection method is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.
//step1 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // loads the JDBC-ODBC bridge driver //or Class.forName("jdbc.Driverxyz") // loads a class name jdbc.Driverxyz for a particular database //step2 Connection con = DriverManager.getConnection(url, "myLogin", "myPassword"); // connects the driver to the DB //For JDBC-ODBC driver, url = jdbc:odbc:data-source-name
Statement stmt = con.createStatement(); //where con is a valid connection stmt.executeUpdate( "INSERT INTO COFFEES " + "VALUES ('Colombian', 101, 7.99, 0, 0)");For select queries, the executeQuery method of the Statement class is used. It returns a ResultSet object.
String query = "SELECT COF_NAME, PRICE FROM COFFEES"; ResultSet rs = stmt.executeQuery(query); //result of query is stored in ResultSet class while (rs.next()) { String s = rs.getString("COF_NAME"); //getString method is used for string-type data float n = rs.getFloat("PRICE"); //getFloat for floating-point data System.out.println(s + " " + n); }
Java method SQL Type ----------- -------- getInt INTEGER getLong BIGINT getFloat REAL getDouble FLOAT getBignum DECIMAL getBoolean BIT getString VARCHAR getString CHAR getDate DATE getTime TIME getTimestamp TIME STAMP getObject any typeThe PreparedStatement class
PreparedStatement updateSales = con.prepareStatement("UPDATE ITEMS SET ITEM_PRICE = ? WHERE ITEM_NAME LIKE ?"); updateSales.setInt(1, 75); updateSales.setString(2, "Road Atlas"); updateSales.executeUpdate();The CallableStatement class
String createProcedure = "create procedure SHOW_SUPPLIERS " + "as " + "select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " + "from SUPPLIERS, COFFEES " + "where SUPPLIERS.SUP_ID = COFFEES.SUP_ID " + "order by SUP_NAME"; Statement stmt = con.createStatement(); stmt.executeUpdate(createProcedure); CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}"); ResultSet rs = cs.executeQuery();The DatabaseMetaData class
Connection con = DriverManager.getConnection( "jdbc:odbc:mydatasource", "user", "password"); DatabaseMetaData md = con.getMetaData(); if (md==null) { System.out.println("No Database Meta Data"); } else { System.out.println("Database Product Name : " + md.getDatabaseProductName()); System.out.println("Allowable active connections: "+ md.getMaxConnections()); }The ResultSetMetaData class
try { ResultSet result = stmt.executeQuery( "SELECT * FROM Items ORDER BY ItemCode DESC;"); ResultSetMetaData meta = result.getMetaData(); int numbers = 0; int columns = meta.getColumnCount(); for (int i=1;i<=columns;i++) { System.out.println (meta.getColumnLabel(i) + "\t" + meta.getColumnTypeName(i)); if (meta.isSigned(i)) { // is it a signed number? numbers++; } } System.out.println ("Columns: " + columns + " Numeric: " + numbers); con.close(); } catch (Exception e) { e.printStackTrace(); }
import java.sql.*; class sqlserver1 { public static void main(String[] args) { try { // Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver" ); DriverManager.registerDriver(new com.microsoft.jdbc.sqlserver.SQLServerDriver()); String connStr = "jdbc:microsoft:sqlserver://EMACHINES\\TANTRA:1433;"; connStr += "databasename=esupplies;SelectMethod=direct"; Connection conn = DriverManager.getConnection( connStr,"Kandas","ustatesa"); System.out.println("Connection established"); } catch (Exception e) { System.out.println("Error: " + e); } } }For compilation
import java.sql.*; class accessConnect { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String filename = "d:/java/mdbtest.mdb"; String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="; database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end Connection con = DriverManager.getConnection( database ,"",""); } catch (Exception e) { System.out.println("Error: " + e); } } }JDBC Exceptions
Connection con = DriverManager.getConnection(...); con.setAutoCommit(false); Statement s = con.createStatement(); try { s.executeUpdate("SQL statement 1"); s.executeUpdate("SQL statement 2"); con.commit(); } catch (SQLException sqlexc) { con.rollback(); }
Back
Back
public interface javax.ejb.SessionBean extends javax.ejb.EnterpriseBean { public abstract void ejbActivate (); public abstract void ejbPassivate (); public abstract void ejbRemove (); public abstract void setSessionContext (SessionContext ctx); }ejbActivate - prepare a Session Bean for transition from a passive state to active
Method Description ejbActivate() and ejbPassivate() Used by the container to manage bean instances ejbLoad() and ejbStore() Used to synchronize the data in the entity bean's persistent fields with the underlying data store. The implementation of these methods depends upon the bean's persistence model setEntityContext() and unsetEntityContext() Used to pass information to the entity bean from the container ejbRemove() Used to delete a record from the underlying data store
Back
import java.io.*; import javax.servlet.*; public class SampleServlet implements Servlet { private ServletConfig config; public void init (ServletConfig config) throws ServletException { this.config = config; } public void destroy() {} //do nothing public ServletConfig getServletConfig() { return config; } public String getServletInfo() { return "A Simple Servlet"; } public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType( "text/html" ); PrintWriter out = res.getWriter(); out.println( "<html><head><title>A Sample Servlet</title></head><body>" ); out.println( "<h1>A Sample Servlet</h1>" ); out.println( "</body></html>" ); out.close(); } }Handling both GET and POST data
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ThreeParams extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading Three Request Parameters"; out.println("<HTML><BODY>\n" + " <LI>param1: " + request.getParameter("param1") + "\n" + " <LI>param2: " + request.getParameter("param2") + "\n" + " <LI>param3: " + request.getParameter("param3") + "\n" + "</BODY></HTML>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }Servlet response to a HTTP request made from a normal class and not a browser
Servlet import java.util.HashMap; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloServlet extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); //getting the parameters String age = request.getParameter("age"); HashMap hm = new HashMap(); //putting them in a hashmap hm.put("name", name); hm.put("age", age); try { //returning them ObjectOutputStream p = new ObjectOutputStream(response.getOutputStream()); p.writeObject(hm); p.flush(); p.close(); } catch (Exception e) { e.printStackTrace(); } } } This is the class that calls the servlet import java.net.*; import java.util.*; import java.io.*; public class Hello { public static void main(String args[]) { ObjectInputStream is; URL url; String uri = "http://Server name:port/HelloServlet"; HashMap hash = new HashMap(); try { url = new URL(uri + "?&name=MyName&age=25"); //calling the servlet by passing params is = new ObjectInputStream(url.openStream()); // open input stream and read the hashmap hash = (HashMap) is.readObject(); // returned by the servlet System.out.println(hash); // print it out } catch (Exception e) { e.printStackTrace(System.err); } } }
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpSession session = req.getSession(false); res.setContentType("text/html"); res.setHeader("pragma", "no-cache"); PrintWriter out = res.getWriter(); out.print("<HTML><HEAD><TITLE>Session Tracker</TITLE>"+ "</HEAD><BODY><FORM METHOD=POST ACTION="); out.print(res.encodeUrl(req.getRequestURI())); out.print("><INPUT TYPE=SUBMIT NAME=btnSubmit VALUE="+ "\"Submit\">"+ "</FORM></BODY></HTML>"); out.close(); }
public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException { response.addCookie(new Cookie("userid", "4716")); //cookie name,value }
Cookie[] cookie_jar = request.getCookies(); if (cookie_jar != null) //check if any cookies exist { for (int i =0; i< cookies.length; i++) { Cookie aCookie = cookie_jar[i]; pout.println ("Name : " + aCookie.getName()); pout.println ("Value: " + aCookie.getValue()); } }
import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class DBservlet extends HttpServlet { private ServletConfig config; public void init (ServletConfig config) throws ServletException { this.config = config; } public void destroy() {} // do nothing public ServletConfig getServletConfig() { return config; } public String getServletInfo() { return "A Simple Servlet"; } public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException { try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver" ); String connStr = "jdbc:odbc:esupplies_dsn;"; connStr += "databasename=esupplies;SelectMethod=cursor"; Connection conn = DriverManager.getConnection( connStr,"Kandas","ustatesa"); Statement stmt = conn.createStatement(); String query = "SELECT ItemCode, ItemName FROM Items"; ResultSet rs = stmt.executeQuery(query); //result of query is stored in ResultSet class response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println( "<html><head>"<title>A Sample Data Access Servlet</title></head>" ); out.println( "<body>" ); out.println( "<table>" ); while (rs.next()) { String s = rs.getString("ItemCode"); String n = rs.getString("ItemName"); out.println("<tr><td>" + s + "</td><td>" + n + "</td></tr>"); } conn.close(); out.println( "</table></body></html>" ); out.close(); } catch(Exception e) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println( "<html><head>"<title>A Sample Data Access Servlet</title></head>" ); out.println( "<body>" ); out.println( "Exception Occurred:" + e + "</body></html>" ); out.close(); } } }
Back
language = "scriptinglanguage" import = "Package/Class" buffer = "none | sizekb" isThreadSafe = "true | false" errorPage = "url" Scope = "REQUEST/PAGE/SESSION/APPLICATION" <%@ page language="Java" extends="include - used to include a HTML, JSP or Sevlet file into a JSP file. This is a static inclusion of file i.e. included at the time of compilation and any later changes in the included file will not be reflected." import="<class> or <package>" %>
<%@ include file="<filename>" %>Declarations
<%! private int getDateCount = 0; private String getDate(GregorianCalendar gc) { ...method body here...} %>Comments in a JSP page
<!-- comment text -->Hidden comments which are not delivered and are invisible to the browser
<%-- comment text --%>Implicit/predefined objects available in JSP
<HTML> <HEAD><TITLE>Request object fields</TITLE></HEAD> <BODY> Request method: <%= request.getMethod() %> Protocol used for the request: <%= request.getProtocol() %> Server name: <%= request.getServerName() %> Server port: <%= request.getServerPort() %> Computer address: <%= request.getRemoteAddr() %> Computer name: <%= request.getRemoteHost() %> Path info portion of the URL: <%= request.getPathInfo() %> Server login name: <%= request.getRemoteUser() %> Full request URI: <%= request.getRequestURI() %> Browser: <%= request.getHeader("User-Agent") %> </BODY> </HTML>
The HTML File <HTML> <HEAD><TITLE>Using JavaBeans in JSP</TITLE></HEAD> <BODY> <jsp:useBean id="myBean" class="MyBean" /> <jsp:setProperty name="myBean" property="string" value="Welcome to JavaServer Pages" /> <H1>Hello!: <B> <jsp:getProperty name="myBean" property="string" /> </B></H1> </BODY> </HTML> The Bean File public class MyBean { private String str = "rajtek.tripod.com"; public String getString() { return(str); } public void setString(String str) { str = str; } }The include action
<jsp:include page="sample1.html" flush="true" /> //or <jsp:include page="/docs/sample2.jsp" flush="true"> </jsp:include>The flush="true" parameter indicates whether the output should be flushed before the included page is called. This must be set to true.
<jsp:forward page="/dir1/sample1.jsp" /> //or <%public String s1 = "sample2.jsp"%> <jsp:forward page="<% =s1 %>" ></jsp:forward>Running applets using the jsp:plugin action
<jsp:plugin type=applet code="SampleApplet.class" codebase="classes/applets" > <jsp:params> <jsp:param name="sampleapplet" value="applets"/> </jsp:params> <jsp:fallback> <p> unable to start plugin </p> </jsp:fallback> </jsp:plugin>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="iso-8859-1" %> <%@ page import="java.sql.*,java.util.*,java.io.*" %> <html> <head> <title>JSP Database connection example</title> </head> <% Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String connStr = "jdbc:odbc:esupplies_dsn;"; connStr += "databasename=esupplies;SelectMethod=cursor"; Connection conn = DriverManager.getConnection( connStr,"Kandas","ustatesa"); Statement stmt = conn.createStatement(); String query = "Select ItemCode, ItemName FROM Items"; ResultSet rs = stmt.executeQuery(query); //result of query is stored in ResultSet class %> <body><table> <% while (rs.next()) { String s = rs.getString("ItemCode"); String n = rs.getString("ItemName"); %><tr><td><%=s%></td><td><%=n%></td></tr> <% } conn.close();%> </table> </body> </html>
Back
javac -deprecation applicationname.javaAssuming that the program uses a standard look and feel - such as the Java or Windows look and feel, the program can be run without adding anything to the classpath. For e.g
java SwingApplicationFor a nonstandard look and feel, its package must be included in the class path. For e.g
Solaris: java -classpath .:/home/me/lnfdir/newlnf.jar SwingApplication Windows: java -classpath .;C:\java\lnfdir\newlnf.jar SwingApplicationAdvantages of Swing Components over AWT Components
JPanel panel1 = new JPanel(); panel1.setLayout(new BorderLayout());Swing classes for creating basic GUI components
Event ClassSourceEvent Types ActionEvent Button - when clicked ACTION_PERFORMED List - when doubleclicked MenuItem - when clicked TextField - when ENTER is pressed AdjustmentEvent Scrollbar ADJUSTMENT_VALUE_CHANGED ItemEvent Choice, List, Checkbox, CheckboxMenuItemITEM_STATE_CHANGED TextEvent TextField, TextArea TEXT_VALUE_CHANGED ComponentEvent All Components COMPONENT_SHOWN, COMPONENT_HIDDEN, COMPONENT_MOVED, COMPONENT_RESIZED ContainerEvent All Containers COMPONENT_ADDED, COMPONENT_REMOVED FocusEvent All Components FOCUS_GAINED, FOCUS_LOST KeyEvent All Components KEYPRESSED, KEYRELEASED, KEYTYPED MouseEvent All Components MOUSE_PRESSED/_RELEASED/_CLICKED/_DRAGGED/_MOVED/_ENTERED/_EXITED WindowEvent All Windows WINDOW_OPENED, WINDOW_CLOSING, WINDOW_CLOSED, WINDOW_(DE)ICONIFIED, WINDOW_(DE)ACTIVATEDEvent Listeners
ActionListener AdjustmentListener ItemListener TextListener ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener WindowListener
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SwingApplication { private static String labelPrefix = "Number of button clicks: "; private int numClicks = 0; public Component createComponents() { final JLabel label = new JLabel(labelPrefix + "0 "); JButton button = new JButton("I'm a Swing button!"); button.setMnemonic(KeyEvent.VK_I); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { numClicks++; label.setText(labelPrefix + numClicks); } }); label.setLabelFor(button); /* An easy way to put space between a top-level container and its contents is to put the contents in a JPanel that has an "empty" border */ JPanel pane = new JPanel(); pane.setBorder(BorderFactory.createEmptyBorder( 30, //top 30, //left 10, //bottom 30) //right ); pane.setLayout(new GridLayout(0, 1)); pane.add(button); pane.add(label); return pane; } public static void main(String[] args) { try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } //Create the top-level container and add contents to it. JFrame frame = new JFrame("SwingApplication"); SwingApplication app = new SwingApplication(); Component contents = app.createComponents(); frame.getContentPane().add(contents, BorderLayout.CENTER); //Finish setting up the frame, and show it. frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.pack(); frame.setVisible(true); } }Using an image within a button
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PictureButton extends JFrame { public PictureButton() { super("PictureButton v1.0"); setSize(200, 200); setLocation(200, 200); Icon icon = new ImageIcon("rhino.gif"); JButton button = new JButton(icon); button.addActionListener(new ActionListener( ) { public void actionPerformed(ActionEvent ae) { System.out.println("God!"); } }); Container content = getContentPane(); content.setLayout(new FlowLayout()); content.add(button); } public static void main(String[] args) { JFrame f = new PictureButton(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); f.setVisible(true); } }List and Combo boxes
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class combobox1 { public static void main(String[] args) { JFrame f = new JFrame("List and Combo Box Sample v1.0"); f.setSize(200, 200); f.setLocation(200, 200); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); // create a combo box String [] items = { "un", "deux", "trois", "quatre", "cinq", "six" }; JComboBox comboBox = new JComboBox(items); comboBox.setEditable(true); // create a list with the same data model final JList list = new JList(comboBox.getModel()); // create a button; when it's pressed, print out the selection in the list JButton button = new JButton("Pour favor"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { Object[] selection = list.getSelectedValues(); System.out.println("-----"); for (int i = 0; i < selection.length; i++) System.out.println(selection[i]); } }); Container c = f.getContentPane( ); // put the controls in the content pane JPanel comboPanel = new JPanel( ); comboPanel.add(comboBox); c.add(comboPanel, BorderLayout.NORTH); c.add(new JScrollPane(list), BorderLayout.CENTER); c.add(button, BorderLayout.SOUTH); f.setVisible(true); } }
Back
Maintained by: VINCENT KANDASAMY, Database Architect/Administrator (kandasf@hotmail.com)