Tuesday, July 30, 2013

Note: How to write SQL injection proof PL/SQL

Use const
Use compile-time-fixed SQL statement text unless you cannotUse compile-time-fixed SQL statement text unless you cannot
Use sql syntax template that constructs run-time-created sql statement text.
Expose the database to clients only via a pl/sql api. Control priviledges so that the client has no direct access to the application's objects of other kinds -- especially tables and views.


check/limit the variable
expose minimal pl/sql api
expose minimal previledge

The & syntax device denotes what we will call a value placeholder; and the &&
syntax device9
 denotes what we will call a simple SQL name placeholder

Note: Doing SQL from PL/SQL: Best and Worst Practices

A must read document for all Oracle PL/SQL developers.
1.
PL/SQL supports three methods for issuing SQL: Embedded SQL, native dynamic sql and dbms_sql api.
alter session is not supported by embedded sql. So use execute immediated 'alter session ...'

2. Use the constant keyword in the declaration of any variable that is not changed after its initialization.
(reduces the surface area of attack for SQL injection)

3. Always specify the authid property explicitly in every PL/SQL unit. definer's or invoker's
procedure p(Input in varchar2) authid Current_User is...

4. To avoid sql injection
Stmt constant varchar2(200) := Replace(
 Template, '&&t',
 Sys.DBMS_Assert.Simple_Sql_Name(The_Table));

5. When the sql statement text cannot be fixed at compile time, strive to sue a fixed syntax template and limit the run-

time variation to the provision of names.

6. Native dynamic sql was introduced as an improvement on the dbms_sql API (it is easier to write and executes faster):
open_cursor(), parse(), define_column(), bind_variable(), execute_and_fetch() and close_cursor()

7. when a PL/SQL subprogram executes a
SQL statement there is at least one, and possibly many, so-called context
switches from the PL/SQL virtual machine, to the SQL virtual machine, and
back to the PL/SQL virtual machine

8.
When many rows are to be selected, and the result set may be arbitrarily big,
process them in batches by using fetch... bulk collect into with the limit clause
inside an infinite loop.

9.
When you have an “upsert” requirement, use merge rather than implementing
update... set row... and providing an exception handler for Dup_Val_On_Index
that implements the corresponding insert.

Friday, July 26, 2013

Oracle PL/SQL interview note

Object type is "known and visible" to Oracle SQL engine AND PL/SQL engine.
Record Type is "known and visible" to PL/SQL engine only.
Left join and right join
Exception
e_integration exception;
pragma exception_init(e_integration,-2291);

raise_application_error(-20001,'The employee has no complementary!');
1) Indexed TABLE
DECLARE
TYPE ename_table_type IS TABLE OF emp.ename%TYPE
   INDEX BY BINARY_INTEGER;
ename_table ename_table_type;
BEGIN
SELECT ename INTO ename_table(-1) FROM emp WHERE empno = 7788;
DBMS_OUTPUT.PUT_LINE('The name is:'||ename_table(-1));
END;
/   
2) Nested table
declare
type ename_table_type is table of emp.ename%type;
ename_table ename_table_type;
begin
ename_table:=ename_table_type('MARY','MARY','MARY');
select ename into ename_table(2) from emp where empno = &no;
dbms_output.put_line('The employee name: '||ename_table(2));
end;
/
3) VARRAY
CREATE TYPE article_type AS OBJECT (
title VARCHAR2(30), pubdate DATE
);
CREATE TYPE article_array IS VARRAY(20) OF article_type;
CREATE TABLE author(
id NUMBER(6),name VARCHAR2(10),article article_array
);


UNION, INTERSECT and MINUS are ordered by the first column while UNION ALL is not ordered.


select the N element order asc:
select * from (select t.*,dense_rank() over (PARTITION BY deptno order by sal) rank from employee t) where rank = N;


Most complicated sql query:


B*Tree index is used mostly (one key to one row/range) while Bitmap index is used for low cardinality data (Y,N and null).

dynamic sql

Oracle PL/SQL note

Oralce PL/SQL
11g new features:
Compound Triggers: define statement triggers and row triggers at the same time
Ordered Triggers: specify "follows ..." to define the order (dependency)
disabled triggers
virtual column
result cache
continue support
straight sequence

The names for exceptions can be referenced in only two ways:
In a RAISE statement in the execution section of the program (to raise the exception),
as in:
RAISE invalid_company_id;
In the WHEN clauses of the exception section (to handle the raised exception), as
in:
WHEN invalid_company_id THEN

You can raise an exception of your own or a system exception. The RAISE
statement can take one of three forms:
RAISE exception_name;
RAISE package_name.exception_name;
RAISE; --Use this form when you want to re-raise (or propagate out) the same exception from within an exception handler
EXCEPTION
WHEN NO_DATA_FOUND
THEN
-- Use common package to record all the "context" information,
-- such as error code, program name, etc.
errlog.putline (company_id_in);
-- And now propagate NO_DATA_FOUND unhandled to the enclosing block.
RAISE;

The advantage to using RAISE_APPLICATION_ERROR instead of RAISE (which can
also raise an application-specific, explicitly declared exception) is that you can associate
an error message with the exception.

When this procedure is run, execution of the current PL/SQL block halts immediately,
and any changes made to OUT or IN OUT arguments (if present and without the
NOCOPY hint) will be reversed. Changes made to global data structures, such as
packaged variables, and to database objects (by executing an INSERT, UPDATE,
MERGE, or DELETE) will not be rolled back. You must execute an explicit ROLLBACK
to reverse the effect of DML operations.
The maximum length string that SQLERRM will return is 512 bytes (in some earlier
versions of Oracle, only 255 bytes). Because of this restriction, Oracle Corporation
recommends that you instead call DBMS_UTILITY.FORMAT_ERROR_STACK
to ensure that you see the full error message string (this built-in will not truncate
until 2,000 bytes).
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE --see the error line number
You should call the DBMS_UTILITY.FORMAT_ERROR_BACKTRACE function in
your exception handler.

In the PL/SQL language, errors of any kind are treated as exceptions—situations that
should not occur—in your program. When an error occurs in PL/SQL, whether it’s a system error or an application error,
an exception is raised. The processing in the current PL/SQL block’s execution section
halts, and control is transferred to the separate exception section of the current block,
if one exists, to handle the exception. You cannot return to that block after you finish
handling the exception. Instead, control is passed to the enclosing block, if any.
There are, in general, two types of exceptions:
System exception
An exception that is defined by Oracle and is usually raised by the PL/SQL runtime
engine when it detects an error condition. Some system exceptions have names,
such as NO_DATA_FOUND, while many others simply have numbers and
descriptions.
Programmer-defined exception
An exception that is defined by the programmer and is therefore specific to the
application at hand. You can associate exception names with specific Oracle errors
using the EXCEPTION_INIT pragma (a compiler directive, requesting a specific
behavior), or you can assign a number and description to that error using
RAISE_APPLICATION_ERROR.

Raise
Stops execution of the current PL/SQL block by notifying the runtime engine of
an error. The database itself can raise exceptions, or your own code can raise an
exception with either the RAISE or RAISE_APPLICATION_ERROR command.
Unhandled exception
An exception is said to go “unhandled” when it propagates without being handled
out of the outermost PL/SQL block. Control then passes back to the host execution
environment, at which point that environment/program determines how to respond
to the exception (roll back the transaction, display an error, ignore it, etc.).
Un-named or anonymous exception
An exception that has an error code and a description associated with it, but does
not have a name that can be used in a RAISE statement or in an exception handler
WHEN clause.
Named exception
An exception that has been given a name, either by Oracle in one of its built-in
packages or by a developer. You can also associate a name with this exception
through the use of the EXCEPTION_INIT pragma, or leave it defined only by its
name (which can be used to both raise and handle the exception).
You declare an exception by listing the name of the exception you want
to raise in your program followed by the keyword EXCEPTION:
exception_name EXCEPTION;



Associative arrays:
like hash table
Nested tables:
unbounded
become sparse through deletions
no inherent order to the elements
PL/SQL and database
varrays:
must specify the max number of elements
never sparse
element order is preserved
PL/SQL and database

Programming Interviews Exposed note

Programming.Interviews.Exposed.2nd.Edition.Apr.2007
If someone is sufficiently impressed by your résumé to want to talk to you, the next step is one or more screening interviews,
usually followed by an on-site interview.
Your performance in on-site interviews is the biggest factor in determining whether you get an offer.
If you make a negative impression at lunch, you may lose your offer. Be polite, and avoid alcohol and messy foods like ribs.
a suit is de rigueur when interviewing at a bank or brokerage, unless of course you’re interviewing on the West Coast.
A standard technical interviewing outfit for men consists of nondenim cotton pants, a collared shirt, and loafers (no sneakers or sandals).
their job is to get you to sign with their company as quickly as possible for as little money as possible.
This shouldn’t be a snap decision - never accept an offer on the spot. Always spend at least a day thinking about important decisions like this;
it’s surprising how much can change in a day.
Don’t let this bullying rush your decision.
In the worst case, the company refuses to change the offer and you’re no worse off than before you tried to negotiate.
Pigs get fat, but hogs get slaughtered.
I’m very pleased to have received the offer, but I’m having a hard time accepting it because it’s not competitive with my other offers.
I keep all my offers confidential, including yours, and feel that it’s unprofessional to give out that sort of information.
I want to thank you again for extending me the offer. I was very impressed with your company, but I’ve decided it’s not the best choice for me right now.
Thank you again, and I appreciate your confidence in me.
Describe the better way to solve the problem, but solve the question as it was asked. For example, if you are asked to solve a certain problem with a hash table,
you might say, “This would be easy with a binary search tree because it’s much easier to extract the largest element, but let’s see how I can solve this with
a hash table …”
Even when you immediately know the answer to a problem, because it’s something you’ve already done before, don’t just blurt it out. Break the answer down into
discrete steps and explain the thought processes behind each step.
Make sure you check your code for all error and special cases, especially boundary conditions.

I guess you’re off the hook!”

java concurrency in practice note

In the absence of synchronization, the compiler, hardware, and runtime are allowed to take substantial liberties with the timing and ordering of actions, such as caching variables in registers or processor-local caches where they are temporarily (or even permanently) invisible to other threads.

Every Java application uses threads. When the JVM starts, it creates threads for JVM housekeeping tasks (garbage collection, finalization) and a main thread for running the main method.

If a TimerTask accesses data that is also accessed by other application threads, then not only must the TimerTask do so in a thread-safe manner, but so must any other classes that access that data. Often the easiest way to achieve this is to ensure that objects accessed by the TimerTask are themselves thread-safe, thus encapsulating the thread safety within the shared objects.

Like servlets, RMI objects should be prepared for multiple simultaneous calls and must provide their own thread safety.

Swing components, such as JTable, are not thread-safe. Instead, Swing programs achieve their thread safety by confining all access to GUI components to the event thread. If an application wants to manipulate the GUI from outside the event thread, it must cause the code that will manipulate the GUI to run in the event thread instead.

Perhaps surprisingly, concurrent programming isn't so much about threads or locks, Writing thread-safe code is, at its core, about managing access to state, and in particular to shared, mutable state. By shared, we mean that a variable could be accessed by multiple threads; by mutable, we mean that its value could change during its lifetime. Whenever more than one thread accesses a given state variable, and one of them might write to it, they all must coordinate their access to it using synchronization. The primary mechanism for synchronization in Java is the synchronized keyword, which provides exclusive locking, but the term "synchronization" also includes the use of volatile variables, explicit locks, and atomic variables.

A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.
Thread-safe classes encapsulate any needed synchronization so that clients need not provide their own.

The transient state for a particular computation exists solely in local variables that are stored on the thread's stack and are accessible only to the executing thread. One thread accessing a StatelessFactorizer cannot influence the result of another thread accessing the same StatelessFactorizer; because the two threads do not share state, it is as if they were accessing different instances. Since the actions of a thread accessing a stateless object cannot affect the correctness of operations in other threads, stateless objects are thread-safe.

A race condition occurs when the correctness of a computation depends on the relative timing or interleaving of multiple threads by the runtime; in other words, when getting the right answer relies on lucky timing. The most common type of race condition is check-then-act, where a potentially stale observation is used to make a decision on what to do next.

To ensure thread safety, check-then-act operations (like lazy initialization) and read-modify-write operations (like increment) must always be atomic. We refer collectively to check-then-act and read-modify-write sequences as compound actions.

When a single element of state is added to a stateless class, the resulting class will be thread-safe if the state is entirely managed by a thread-safe object.

A synchronized block has two parts: a reference to an object that will serve as the lock, and a block of code to be guarded by that lock. A synchronized method is a shorthand for a synchronized block that spans an entire method body, and whose lock is the object on which the method is being invoked. (Static synchronized methods use the Class object for the lock.)
Every Java object can implicitly act as a lock for purposes of synchronization; these built-in locks are called intrinsic locks or monitor locks. The lock is automatically acquired by the executing thread before entering a synchronized block and automatically released when control exits the synchronized block, whether by the normal control path or by throwing an exception out of the block.

Intrinsic locks in Java act as mutexes (or mutual exclusion locks), which means that at most one thread may own the lock. When thread A attempts to acquire a lock held by thread B, A must wait, or block, until B releases it. If B never releases the lock, A waits forever.

When a thread requests a lock that is already held by another thread, the requesting thread blocks. But because intrinsic locks are reentrant, if a thread tries to acquire a lock that it already holds, the request succeeds. Reentrancy means that locks are acquired on a per-thread rather than per-invocation basis.

For each mutable state variable that may be accessed by more than one thread, all accesses to that variable must be performed with the same lock held. In this case, we say that the variable is guarded by that lock.

A common locking convention is to encapsulate all mutable state within an object and to protect it from concurrent access by synchronizing any code path that accesses mutable state using the object's intrinsic lock. This pattern is used by many thread-safe classes, such as Vector and other synchronized collection classes. In such cases, all the variables in an object's state are guarded by the object's intrinsic lock.

Code auditing tools like FindBugs can identify when a variable is frequently but not always accessed with a lock held, which may indicate a bug.

In order to ensure visibility of memory writes across threads, you must use synchronization.
Volatile variables are not cached in registers or in caches where they are hidden from other processors, so a read of a volatile variable always returns the most recent write by any thread.
Locking can guarantee both visibility and atomicity; volatile variables can only guarantee visibility.
When an object creates a thread from its constructor, it almost always shares its this reference with the new thread, either explicitly (by passing it to the constructor) or implicitly (because the Thread or Runnable is an inner class of the owning object

If data is only accessed from a single thread, no synchronization is needed. This technique, thread confinement, is one of the simplest ways to achieve thread safety. Swing uses thread confinement extensively. The Swing visual components and data model objects are not thread safe; instead, safety is achieved by confining them to the Swing event dispatch thread. To use Swing properly, code running in threads other than the event thread should not access these objects. (To make this easier, Swing provides the invokeLater mechanism to schedule a Runnable for execution in the event thread.)

Final fields can't be modified (although the objects they refer to can be modified if they are mutable),
Barriers are similar to latches in that they block a group of threads until some event has occurred. The key difference is that with a barrier, all the threads must come together at a barrier point at the same time in order to proceed.

The primary abstraction for task execution in the Java class libraries is not Thread, but Executor

However, Timer has some drawbacks, and ScheduledThreadPoolExecutor should be thought of as its replacement. there is little reason to use Timer in Java 5.0 or later.

single-threaded event queue model: a dedicated thread fetches events off a queue and dispatches them to applicationdefined event handlers.
Single-threaded GUI frameworks achieve thread safety via thread confinement; all GUI objects, including visual components and data models, are accessed exclusively from the event thread. Of course, this just pushes some of the thread safety burden back onto the application developer, who must make sure these objects are properly confined.

The Swing single-thread rule: Swing components and models should be created, modified, and queried only from the event-dispatching thread.













Java OSGI note

OSGi container implementations such as Knopflerfish, Equinox, and Apache Felix allow you to break your application into multiple modules
and thus more easily manage cross-dependencies between them.
Similar to the Java Servlet and EJB specifications, the OSGi specification defines two things: a set of services that an OSGi container
must implement and a contract between the container and
your application. Developing on the OSGi platform means first building your application using OSGi APIs, then deploying it in an OSGi container.
very Eclipse plug-in is essentially an OSGi bundle with some additional Eclipse-specific code.
The OSGi container creates a different class loader for every bundle.

Java Spring note

http://www.tutorialspoint.com/spring/index.htm

Dependency injection can happen in the way of passing parameters to the constructor or by post-construction using setter methods.
You can mix both, Constructor-based and Setter-based DI but it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies.

Java Swing Thread note

A Swing programmer deals with the following kinds of threads:
•Initial threads, the threads that execute initial application code.
•The event dispatch thread, where all event-handling code is executed. Most code that interacts with the Swing framework must also execute on this thread.
•Worker threads, also known as background threads, where time-consuming background tasks are executed.
The programmer does not need to provide code that explicitly creates these threads: they are provided by the runtime or the Swing framework. The programmer's
job is to utilize these threads to create a responsive, maintainable Swing program.

An initial thread schedules the GUI creation task by invoking javax.swing.SwingUtilities.invokeLater or javax.swing.SwingUtilities.invokeAndWait .
Both of these methods take a single argument: the Runnable that defines the new task. Their only difference is indicated by their names:
invokeLater simply schedules the task and returns; invokeAndWait waits for the task to finish before returning.
You can see examples of this throughout the Swing tutorial:
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        createAndShowGUI();
    }
});

Why does not the initial thread simply create the GUI itself? Because almost all code that creates or interacts with Swing components must
run on the event dispatch thread.

Swing event handling code runs on a special thread known as the event dispatch thread. Most code that invokes Swing methods also runs on
this thread. This is necessary because most Swing object methods are not "thread safe": invoking them from multiple threads risks thread
interference or memory consistency errors. Some Swing component methods are labelled "thread safe" in the API specification;
these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread.

It's useful to think of the code running on the event dispatch thread as a series of short tasks.Tasks on the event dispatch thread must finish quickly;
if they don't, unhandled events back up and the user interface becomes unresponsive.

If you need to determine whether your code is running on the event dispatch thread, invoke javax.swing.SwingUtilities.isEventDispatchThread.

SwingWorker provides a number of communication and control features:
•The SwingWorker subclass can define a method, done, which is automatically invoked on the event dispatch thread when the background task is finished.
•SwingWorker implements java.util.concurrent.Future. This interface allows the background task to provide a return value to the other thread. Other methods in this interface allow cancellation of the background task and discovering whether the background task has finished or been cancelled.
•The background task can provide intermediate results by invoking SwingWorker.publish, causing SwingWorker.process to be invoked from the event dispatch thread.
•The background task can define bound properties. Changes to these properties trigger events, causing event-handling methods to be invoked on the event dispatch thread.

When writing a multi-threaded application using Swing, there are two constraints to keep in mind:
Time-consuming tasks should not be run on the Event Dispatch Thread. Otherwise the application becomes unresponsive.
Swing components should be accessed on the Event Dispatch Thread only.

Don't invoke get without arguments unless you are confident that the background task is complete or close to completion.

a single cell renderer is generally used to draw all of the cells that contain the same type of data. When the user starts to edit a cell's data, a cell editor takes over the cell, controlling the cell's editing behavior.
To choose the renderer that displays the cells in a column, a table first determines whether you specified a renderer for that particular column. If you did not, then the table invokes the table model's getColumnClass method, which gets the data type of the column's cells. Next, the table compares the column's data type with a list of data types for which cell renderers are registered. This list is initialized by the table, but you can add to it or change it. Currently, tables put the following types of data in the list:

•Boolean — rendered with a check box.
•Number — rendered by a right-aligned label.
•Double, Float — same as Number, but the object-to-text translation is performed by a NumberFormat instance (using the default number format for the current locale).
•Date — rendered by a label, with the object-to-text translation performed by a DateFormat instance (using a short style for the date and time).
•ImageIcon, Icon — rendered by a centered label.
•Object — rendered by a label that displays the object's string value.
Cell editors are chosen using a similar algorithm.

asks described by Callable can throw checked and unchecked exceptions





Java Swing note

Swing provides three generally useful top-level container classes: JFrame, JDialog, and JApplet
•Each top-level container has a content pane that, generally speaking, contains (directly or indirectly) the visible components in that top-level container's GUI.
The menu bar is by convention positioned within the top-level container, but outside the content pane.
Although JInternalFrame mimics JFrame, internal frames aren't actually top-level containers.
With the exception of top-level containers, all Swing components whose names begin with "J" descend from the JComponent class.
An opaque component fills its background with its background color.
The z-order determines the order that components are painted. The component with the highest z-order paints first and the component with the lowest z-order paints last. Where components overlap, the component with the lower z-order paints over the component with the higher z-order.
repaint(): Request that all or part of the component be repainted.
void revalidate(): Request that the component and its affected containers be laid out again. You should not generally need to invoke this method unless you explicitly change a component's size/alignment hints after it's visible or change a containment hierarchy after it is visible. Always invoke repaint after revalidate.
void paintComponent(Graphics) Paint the component. Override this method to implement painting for custom components.

Unix shell VI note

Ctrl+a : Moves the cursor to the line start (equivalent to the key
Ctrl+e : (end) moves the cursor to the line end (equivalent to the key
Ctrl+l : Clears the screen content
Ctrl+x Ctrl+e : Edits the current line in the $EDITOR program, or vi if undefined.
CTRL+R in BASH for searching/activating previously executed commands (the contents of ~/.bash_history).

man 7 ascii
cd - Change to the previous working directory

Monday, July 8, 2013

no ads (ads free) merriam webster

import java.awt.AWTException;
import java.awt.Desktop;
import java.awt.Robot;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;

import com.sun.glass.events.KeyEvent;

public class MWDict {

private static final boolean AUTO_CLOSE = true;
    public static void main(String[] args) throws Exception {
    String word = "sumo";
    display(word);
    playAudio(word);
    System.exit(0);
    }
   
    public static void display(String word) throws IOException{
    String text = Jsoup.connect("http://www.merriam-webster.com/dictionary/"+word.trim()).get().getElementsByClass("d").outerHtml();
    List<String> lines = new ArrayList<String>();
    lines.add("<html>");
    lines.add(text);
    lines.add("</html>");
    FileUtils.write(new File("test.html"), lines);
    Desktop.getDesktop().browse(new File("test.html").toURI());
    }
   
    public static String getAudioURL(String word) throws IOException{
    String text = Jsoup.connect("http://www.merriam-webster.com/dictionary/"+word).get().getElementsByClass("au").outerHtml();
    String[] elements = text.substring(text.indexOf("(")+1,text.indexOf(")")).replaceAll("'","").split(",");
    String url = "http://www.merriam-webster.com/audio.php?file="+elements[0].trim()+"&word="+elements[1].trim();
    System.out.println("url: "+url);
    return url;
    }
   
    public static void playAudio(String word) throws IOException, URISyntaxException, AWTException, InterruptedException{
    Desktop.getDesktop().browse(new URI(getAudioURL(word)));
    //close
    if(AUTO_CLOSE){
        Thread.sleep(2000);
        Robot robot = new Robot();
        robot.setAutoDelay(200);
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_W);
        robot.keyRelease(KeyEvent.VK_W);
        robot.keyRelease(KeyEvent.VK_CONTROL);
    }
    }
}