Saturday, December 21, 2013

How to retrieve the current value of an oracle sequence without increment it?

SELECT last_number
  FROM all_sequences
 WHERE sequence_owner = ''
   AND sequence_name = '';
You can get a variety of sequence metadata from user_sequencesall_sequences anddba_sequences.
These views work across sessions.
EDIT:
If the sequence is in your default schema then:
SELECT last_number
  FROM user_sequences
 WHERE sequence_name = '';
If you want all the metadata then:
SELECT *
  FROM user_sequences
 WHERE sequence_name = '';
Hope it helps...
EDIT2:
A long winded way of doing it more reliably if your cache size is not 1 would be:
SELECT increment_by I
  FROM user_sequences
 WHERE sequence_name = 'SEQ';

      I
-------
      1

SELECT seq.nextval S
  FROM dual;

      S
-------
   1234

-- Set the sequence to decrement by 
-- the same as its original increment
ALTER SEQUENCE seq 
INCREMENT BY -1;

Sequence altered.

SELECT seq.nextval S
  FROM dual;

      S
-------
   1233

-- Reset the sequence to its original increment
ALTER SEQUENCE seq 
INCREMENT BY 1;

Sequence altered.
Just beware that if others are using the sequence during this time - they (or you) may get
ORA-08004: sequence SEQ.NEXTVAL goes below the sequences MINVALUE and cannot be instantiated
Also, you might want to set the cache to NOCACHE prior to the resetting and then back to its original value afterwards to make sure you've not cached a lot of values.

Wednesday, December 11, 2013

What is a serialVersionUID and why should I use it?

The docs for java.io.Serializable are probably about as good an explanation as you'll get:
The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members.
http://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it

Tuesday, December 10, 2013

java.util.Date vs java.sql.Date

Congratulations, you've hit my favorite pet peeve with JDBC: Date class handling.
Basically databases usually support at least three forms of datetime fields which are date, time and timestamp. Each of these have a corresponding class in JDBC and each of them extendjava.util.Date. Quick semantics of each of these three are the following:
  • java.sql.Date corresponds to SQL DATE which means it stores years, months and days whilehour, minute, second and millisecond are ignored. Additionally sql.Date isn't tied to timezones.
  • java.sql.Time corresponds to SQL TIME and as should be obvious, only contains information about hour, minutes, seconds and milliseconds.
  • java.sql.Timestamp corresponds to SQL TIMESTAMP which is exact date to the nanosecond (note that util.Date only supports milliseconds!) with customizable precision.
One of the commonest bugs in JDBC drivers in relation to these three types is that the types are handled incorrectly. This means that sql.Date is timezone specific, sql.Time contains current year, month and day et cetera et cetera.

Finally: Which one to use?

Depends on the SQL type of the field, really. PreparedStatement has setters for all three values,#setDate() being the one for sql.Date#setTime() for sql.Time and #setTimestamp() forsql.Timestamp.
Do note that if you use ps.setObject(fieldIndex, utilDateObject); you can actually give a normal util.Date to most JDBC drivers which will happily devour it as if it was of the correct type but when you request the data afterwards, you may notice that you're actually missing stuff.

I'm really saying that none of the Dates should be used at all.

What I am saying that save the milliseconds/nanoseconds as plain longs and convert them to whatever objects you are using (obligatory joda-time plug). One hacky way which can be done is to store the date component as one long and time component as another, for example right now would be 20100221 and 154536123. These magic numbers can be used in SQL queries and will be portable from database to another and will let you avoid this part of JDBC/Java Date API:s entirely.

Friday, December 6, 2013

Checking oracle sid and database name

I presume select user from dual; should give you the current user
and select sys_context('userenv','instance_name') from dual; the name of the instance
I believe you can get SID as SELECT sys_context('USERENV', 'SID') FROM DUAL; (can't to check this now)

Default passwords of Oracle 11g?

It is possible to connect to the database without specifying a password. Once you've done that you can then reset the passwords. I'm assuming that you've installed the database on your machine; if not you'll first need to connect to the machine the database is running on.
  1. Ensure your user account is a member of the dba group. How you do this depends on what OS you are running.
  2. Enter sqlplus / as sysdba in a Command Prompt/shell/Terminal window as appropriate. This should log you in to the database as SYS.
  3. Once you're logged in, you can then enter
    alter user SYS identified by "newpassword";
    
    to reset the SYS password, and similarly for SYSTEM.
See also here.
(Note: I haven't tried any of this on Oracle 11g; I'm assuming they haven't changed things since Oracle 10g.)

Monday, November 25, 2013

What is the use of marker interfaces in Java?

In earlier versions of Java, Marker Interfaces were the only way to declare metadata about a class. For example, the Serializable Marker Interface lets the author of a class say that their class will behave correctly when serialized and deserialized.
In modern Java, marker interfaces have no place. They can be completely replace by Annotations, which allow for a very flexible metadata capability. If you have information about a class, and that information never changes, then annotations are a very useful way to represent it.

Sunday, November 17, 2013

Initial size for the arraylist

You're confusing the size of the array list with its capacity:
  • the size is the number of elements in the list;
  • the capacity is how many elements the list can potentially accommodate without reallocating its internal structures.
When you call new ArrayList(10), you are setting the list's initial capacity, not its size. In other words, when constructed in this manner, the array list starts its life empty.
One way to add ten elements to the array list is by using a loop:
for (int i = 0; i < 10; i++) {
  arr.add(0);
}
Having done this, you can now modify elements at indices 0..9.

Why is Java Vector class considered obsolete or deprecated?

Vector synchronizes on each individual operation. That's almost never what you want to do.
Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?
Of course, it also has the overhead of locking even when you don't need to.
Basically, it's a very flawed approach to synchronization in most situations. As MrSpandex pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vectorcombines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.
As for a Stack equivalent - I'd look at Deque/ArrayDeque to start with.

Wednesday, November 6, 2013

How to choose the right bean scope?

It represents the scope (the lifetime) of the bean. A request scoped bean lives as long as a single HTTP request-response cycle. A view scoped bean lives as long as you're interacting with the same JSF view by postbacks returning null/void. A session scoped bean lives as long as the established HTTP session. An application scoped bean lives as long as the web application runs.
Which scope to choose depends solely on the data (the state) the bean holds and represents. Use the request scope for simple and non-ajax forms/presentations. Use the view scope for rich ajax-enabled dynamic views (ajaxbased validation, rendering, etc). Use the session scope for client specific data, such as the logged-in user and user preferences (language, etc). Use the application scope for application wide data/constants, such as dropdown lists which are the same for everyone.
Abusing an application scoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a session scoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a request scoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a view scoped bean for request scoped data doesn't affect the client, but it unnecessarily occupies server memory.
Note that the scope should rather not be chosen based on performance implications, unless you reallyhave a low memory footprint and want to go completely stateless; you'd need to use exclusively request scoped beans and fiddle with request parameters to maintain the client's state.

See also:

Thursday, October 17, 2013

How to change user credentials in Subclipse?

Delete, or rename, the Eclipse '.keyring' file in Eclipse's configuration folder. This is where the Subclipse SVNKit connector caches your SVN credentials..
[ECLIPSE INSTALL]\configuration\org.eclipse.core.runtime.keyring
If, on the other hand, you're using the JavaHL connector -- or SVN command-line -- then their credentials are stored in the Subversion runtime config folder. Delete or rename the credential file.
On Windows: %APPDATA%\Subversion\auth
On Linux and OSX: ~/.subversion/auth
Sorry about this pig of complexity, for what should be a real version-control system. :-(

Wednesday, October 16, 2013

A brief introduction to the service integration bus

When Graham started this blog in September there was a definite idea that we would be talking about what is new in v7. It was launched at the same time v7 shipped, so to deny a link would be ludicrous, but it has recently occurred to me that it might be useful just to cover some of the basics. I am basing this on a large number of conversations I have had over the last month or so where I have had to explain the basics to people who had not quite got one of the concepts. So here I go:

What is a bus?
A bus is a number of things, which makes coming up with a single definition hard, but when we talk about a bus we mean all of the following:

  1. A name space for destinations
  2. A cloud to which destinations are defined and client applications connect.
  3. A set of interconnected application servers and/or clusters that co-operate to provide messaging function
  4. A set of interconnected messaging engines that co-operate to provide messaging function
While some of these might seem similar they are in fact different and that difference should become clear later on (each statement is not quite equal).

What is a destination?

A destination is a point of addressibility within the bus. Messages are sent to and received from destinations. There are a number of different types of destination. These are:
  1. A queue. This provides point to point messaging capabilities. A message is delivered to exactly one connected client and the messages are broadly processed in a first in first out order (message priority can affect this order).
  2. A topic space. This provides publish/subscribe messaging capabilities. A message is delivered to all matching connected clients.
There are other types of destinations, but they are less common, so I have skimmed over those.

What is a messaging engine?

A bus is a logical entity and as such provides no value on its own. The "runtime" of the bus is provided by a set of messaging engines which co-operate to provide this runtime. Messaging engines provide two important functions. The first is that clients connect to messaging engines, and the second is that messages are managed by the messaging engine.
What is a bus member?
While messaging engines provide the runtime they are not directly configurable (except for one key exception I will cover later). Instead servers and/or clusters are added to the bus. When a server or cluster is added to the bus it causes a single messaging engine to be created. A server bus member can host at most one messaging engine per bus, a cluster can have multiple, which is the only time you can create messaging engines.

Destinations are then "assigned" to a bus member at which point the messaging engines running on those bus members get something called a message point which is where the messages are stored.

Multiple servers and clusters can be added to a single bus. This is an important point. Some discussions I have had recently point to this being a point of confusion. Two different servers or clusters can be added to to the same bus. A bus can be as large as the cell in which it is defined. It can be larger than a single cluster.

How does High Availability work?
A certain level of availability is provided just by adding multiple application servers as a bus, a client can connect into any running messaging engines. The problem is that if messaging engine is not running the message points it is managing are not available. This does not provide an ideal HA story.

If you want HA you just use a cluster as a bus member instead. When you add a cluster as a bus member you get one messaging engine which can run on any application server in that cluster. If the server in the cluster fails then the messaging engine will be started in another server in the cluster. This can be configured using a policy.

How does Scalability work?
Scalability also utilizes application server clusters. By configuring multiple messaging engines in a cluster each messaging engine in the cluster will have a message point for destinations the cluster manages. We call this a partitioned destination. This is because each messaging engine only knows about a subset of the messages on the destination.

The upshot of all this is that the work load is shared by multiple servers.

And finally


So there we have it. The infocenter does cover a lot of this in more detail. I have linked the titles to the appropriate part of theinfocenter for learning about the topics.

If you have any questions feel free to ask in the comments.
Alasdair

Thursday, October 10, 2013

How to get rid of nerve pinch in shoulder?

The wide grip requires that your shoulder have full range to abduct and externally rotate. Limitation from tight muscles or from weak scapular stabilizers can cause an impingement at the shoulder joint, so it may or may not be a pinched nerve.
To find out what you actually have and to get a good exercise program to correct it, you should see your doctor (orthopedist) and/or a physical therapist (physio). Any info here will only be general information which might help, but may not address your complete problem.
If your main problem is poor shoulder positioning the following may help:
  • Tight Muscles: Muscles that limit this wide grip motion are tight pecs (esp. pec minor) and subscapularis.
  • Exercises to Stretch: Pec stretches such as the doorway stretch may help. Try this stretch with the arm at various heights along the door frame to find where in the range your muscle feels tight.
  • Exercises to Strengthen and Stretch: The wall pec stretch, stretches the pecs but also contracts the rhomboid and trapezius scapular muscles to help improve the positioning of the shoulder blade. The position of the shoulder blade is important because if it is out of position (as with shoulders that are rounded forward) it can lead to impingement and pain.
If your problem is a pinched nerve, then see your doctor/physical therapist for treatment and an exercise regime to correct the imbalances and to improve your nerve mobility.

Wednesday, October 9, 2013

EGit Push tag broken

The Push Tag... wizard is much too complicated at the moment, yes. Try 
enteringrefs/tags/ as the target ref name.

http://stackoverflow.com/questions/18396182/egit-push-tag-broken

Java - How to change context root of a dynamic web project in eclipse

I'm sure you've moved on by now, but I thought I'd answer anyway.
Some of these answers give work-arounds. What actually must happen is that you clean and republish your project to "activate" the new URI. This is done by right-clicking your server (in the Servers view) and choosing Clean. Then you start (or restart it). Most of the other answers here suggest you do things that in effect accomplish this.
The file that's changing is workspace/.metadata/.plugins/org.eclipse.wst.server.core/publish/publish.dat unless, that is, you've got more than one server in your workspace in which case it will be publishN.dat on that same path.
Hope this helps somebody.

Not sure if this is proper etiquette or not -- I am editing this answer to give exact steps for Eclipse Indigo.
(1) In your project's Properties, choose "Web Project Settings".
(2) Change "Context root" to "app".
screen shot of Eclipse project properties Web Project Settings
(3) Choose Window > Show View > Servers.
(4) Stop the server by either clicking the red square box ("Stop the server" tooltip) or context-click on the server listing to choose "Stop".
(5)On the server you want to use, context-click to choose "Clean…".
enter image description here
(6) Click OK in this confirmation dialog box.
Screenshot of dialog asking to update server configuration to match the changed context root
Now you can run your app with the new "app" URL such as:
Doing this outside of Eclipse, on your production server, is even easier --> Rename the war file. Export your Vaadin app as a WAR file (File > Export > Web > WAR file). Move the WAR file to your web server's servlet container such as Tomcat. Rename your WAR file, in this case to "app.war". When you start the servlet container, most such as Tomcat will auto-deploy the app, which includes expanding the war file to a folder. In this case, we should see a folder named "app". You should be good to go. Test your URL. For a domain such as "example.com" this would be: http://www.example.com/app/
Thanks so much to Russ Bateman for posting the correct answer to this frustrating problem.
Vaadin toolkit programmers may need to rebuild their widget set if using visual add ons.
--Basil Bourque