Question about Exception!
class A
public void f() throws Myexcption
class B extends A
public void f() throws [Myexception][devied exception from Myexception]
Why B.f() can only throw less exceptions than A.f()?
if A temp = new B();
temp.f() will perform the B.f()'s defination. And if I defined B.f() as
public void f() throws AnotherException
throw AnotherException;
It will has nothing to do with A.f().
Why did the designer design the less exception throwwing rules?
Thanks
class MyFirstException extends Exception {}
class MySecondException extends MyFirstException {}
class A {
public void f() throws MyFirstException { ... }
class B extends A {
public void f() throws MySecondException { ... }
Why B.f() can only throw less exceptions than A.f()?The reason is one of decoupling. If you write code to the contract of A but are actually using an instance of B and the compiler allowed new exceptions to be thrown (not inheriting from the exceptions declared on the original contract) - you would have no way of knowing which other exceptions you must catch. Therefore by enforcing that an overriding method must throw only exceptions within the inheritance hierarchy of the original contract you can be certain to have caught all possible exceptions.
EG
A a = new B();
try {
a.f();
} catch(MyFirstException e) { ... }--
Talden
Similar Messages
-
Question about Exception Error
I'm writing a small PBE program for a class project and I keep getting an InvalidKeySpecException that claims my char[ ] is not ASCII. Now I am under the impression that when a char value is entered it's in ASCII values... I've only put up a piece of my code, if needed I can put up the rest, it's fairly simple and easy to follow.
here is my terminal output (with a number of debug outputs):
Encryption Program Started
Getting Password
Input password (32 character max):
hello
Holdspot is: 6
Pass: hello
Holder: (shows string of char (0) values, verifies that the array was cleared)
Done getting password, pass is:
hello
Creating PBEKeySpec
My keySpec value is: hello
Creating Salt
createSalt entered
Done getting salt
Creating PBEParameterSpec
setParams entered
My iteration field is: 1500
Done getting param
My param iterations are: 1500
Creating SecretKey
createKey Entered
My keySpec value is: hello
InvalidKeySpecException: Password is not ASCII
java.security.spec.InvalidKeySpecException: Password is not ASCII
at com.sun.crypto.provider.PBEKey.<init>(DashoA6275)
at com.sun.crypto.provider.PBEKeyFactory.engineGenerateSecret(DashoA6275)
at javax.crypto.SecretKeyFactory.generateSecret(DashoA6275)
at Cryptography.createKey(Cryptography.java:141)
at Cryptography.main(Cryptography.java:265)
at __SHELL3.run(__SHELL3.java:7)
at bluej.runtime.ExecServer.vmSuspend(ExecServer.java:178)
at bluej.runtime.ExecServer.main(ExecServer.java:143)
java.security.spec.InvalidKeySpecException: Password is not ASCII
at com.sun.crypto.provider.PBEKey.<init>(DashoA6275)
at com.sun.crypto.provider.PBEKeyFactory.engineGenerateSecret(DashoA6275)
at javax.crypto.SecretKeyFactory.generateSecret(DashoA6275)
at Cryptography.createKey(Cryptography.java:141)
at Cryptography.main(Cryptography.java:265)
at __SHELL4.run(__SHELL4.java:7)
at bluej.runtime.ExecServer.vmSuspend(ExecServer.java:178)
at bluej.runtime.ExecServer.main(ExecServer.java:143)
here is my code to get the char array input:
private char[] getPass () throws IOException{
System.out.println("Input password (32 character max):");
char[] holder = new char[maxChar];
int holdspot=0;
while ((holder[holdspot++] = (char) System.in.read()) != '\n') {};
//Debug
System.out.println("Holdspot is: "+holdspot);
//End Debug
char[] pass = new char[holdspot];
System.arraycopy (holder, 0, pass, 0, holdspot);
//clear our holder array
for (int i=0; i<holder.length;i++){
holder=0;
//Debug
System.out.print("Pass: ");
for (int i=0; i<holdspot;i++){
System.out.print(pass[i]);
System.out.print("\n");
System.out.print("Holder: ");
for (int i=0; i<holder.length;i++){
System.out.print(holder[i]);
System.out.print("\n");
//End Debug
//Comment back in for final version, screen clear
//System.out.flush();
return (pass);
here is my code at the point where the exception is thrown:
private SecretKey createKey(PBEKeySpec keySpec)
throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException{
//Debug
System.out.println("createKey Entered");
char[] L = keySpec.getPassword();
System.out.print("My keySpec value is: ");
for (int i=0; i<L.length;i++){
System.out.print(L);
//End Debug
SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey secKey = keyFac.generateSecret(keySpec);
return (secKey);OK, got to Eclipse and reproduced the problem using your code.
Something about the way you were reading your password bugged me. I changed your code a bit to the following:import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class PBETest {
static final int MAX_CHAR = 32;
private char[] getPass() throws IOException {
System.out.print("Input password ("+MAX_CHAR+" character max):");
String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
char[] holder = s.toCharArray();
int holdspot = (s.length()>MAX_CHAR?MAX_CHAR:s.length());
//End Debug
char[] pass = new char[holdspot];
System.arraycopy(holder, 0, pass, 0, holdspot);
//clear our holder array
for (int i = 0; i < holder.length; i++) {
holder[i] = 0;
//Debug
System.out.print("Pass: ");
for (int i = 0; i < holdspot; i++) {
System.out.print(pass);
System.out.print("\n");
System.out.print("Holder: ");
for (int i = 0; i < holder.length; i++) {
System.out.print(holder[i]);
System.out.print("\n");
//End Debug
//Comment back in for final version, screen clear
//System.out.flush();
return (pass);
private SecretKey createKey(PBEKeySpec keySpec)
throws NoSuchAlgorithmException, InvalidKeyException,
InvalidKeySpecException {
//Debug
System.out.println("createKey Entered");
char[] L = keySpec.getPassword();
System.out.print("My keySpec value is: ");
for (int i = 0; i < L.length; i++) {
System.out.print(L[i]);
//End Debug
SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey secKey = keyFac.generateSecret(keySpec);
return (secKey);
public static void main(String[] args) {
try {
PBETest ptest = new PBETest();
char[] pwd = ptest.getPass();
PBEKeySpec spec = new PBEKeySpec(pwd);
SecretKey sk = ptest.createKey(spec);
} catch (Exception e) {
e.printStackTrace();
}And now it works.
I don't know exactly why your "one char at a time from System.in" bugged me, and I don't know exactly why it didn't work - but that was the problem.
Grant -
Forms question about exceptions
Hello,
I am a newbie and hence my question may find very basic, please help me.
I have a Pl/sql code where I am executing a queryand if the query doesn't retrieve any values I need to show a message.
My code is something like this:
select id from table into tmpid where id=:val_id
some code here
CALL_form(url);
If the query fails I need to show a message, how can I do this. Forgive me for my knowledge in forms, as I am a newbie.
Thanks in advance.
NewbieDeclare
Found1 varchar2(1);
Begin
...whatever code you need here...
begin
select 'Y' into Found1
from table where id=:val_id;
exception when no_data_found then null;
end;
If Found1 is null then
Message('No can do!!!');
Raise form_trigger_failure;
End if;
...some code here...
Call_form(url);
End; -
Question about exceptions in function module GUI_DOWNLOAD
To all,
I add the function module 'GUI_DOWNLOAD' in the ABAP report program. After the user download the data to excel, the program also displays a report on the screen for print output.
If the user keep the excel file open and tries to replace the file on download, the program gives an error message 'Access to file denied' and the program ends without displaying a report on the screen.
Is there any way not to end the program even if download is failed?
I would like the program displays a report after it gives an error message.
So I am trying to use exceptions. But if I code to give messages, the programs ends as above. And if I just make exit when it happens, no error message and the program displays a report but the user don't know if the excel file was updated or not.
Could anybody kindly let me know how to code exceptions and messages if it is possible the program works I hope.
Thank you very much in advance.
Best regards,
Miki KomatsuI figured out how to do that.
Thanks.
Best regards,
Miki -
Question about Exception stack
Hello,
I get the following exception stack and it is not the first time that I get this "ClassName.<init>".
What does the "init" mean?
Thanks in advance,
Balteo.
oracle.xquery.XQException: Too many arguments for function compare
[java] at oracle.xquery.PreparedXQuery.<init>(PreparedXQuery.java:63)
[java] at oracle.xquery.XQueryContext.prepareXQuery(XQueryContext.java:140)
[java] at com.agilience.sharenet.app.sgbdo.PPersistenceOracle.executeQuery(PPersistenceOracle.java:214)
[java] at com.agilience.sharenet.app.sgbdo.PPersistenceOracle.getAnonymousId(PPersistenceOracle.java:369)
[java] at com.agilience.sharenet.app.bl.persistence.PPersistenceModel.getAnonymousId(PPersistenceModel.java:112)When an exception occurs inside the constructor for the class, the stack trace refers to the constructor as <init>. <init> is the internal name that java uses to refer to constructors for a class.
-
Simple questions about exceptions
why use try catch with new File("filename") but not with x??
ArrayIndexOutOfBoundsException is unchecked.
IOException is checked.
http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html
Here's a quick overview of exceptions:
The base class for all exceptions is Throwable. Java provides Exception and Error that extend Throwable. RuntimeException (and many others) extend Exception.
RuntimeException and its descendants, and Error and its descendants, are called unchecked exceptions. Everything else is a checked exception.
If your method, or any method it calls, can throw a checked exception, then your method must either catch that exception, or declare that your method throws that exception. This way, when I call your method, I know at compile time what can possibly go wrong and I can decide whether to handle it or just bubble it up to my caller. Catching a given exception also catches all that exception's descendants. Declaring that you throw a given exception means that you might throw that exception or any of its descendants.
Unchecked exceptions (RuntimeException, Error, and their descendants) are not subject to those restrictions. Any method can throw any unchecked exception at any time without declaring it. This is because unchecked exceptions are either the sign of a coding error (RuntimeException), which is totally preventable and should be fixed rather than handled by the code that encounters it, or a problem in the VM, which in general can not be predicted or handled. -
Question about open and close of MySqlConnection
hi
i'd like to ask a question.
MySqlConnection connection = newMySqlConnection(stringConnection);
MySqlCommand cmd = connection.CreateCommand();
connection.Open(); and i have a try catch. accoding to your opinion, i should put connection.Close() in the block of try,or outside of block of try? according to you,if i open the connection and do not close,is it bad?or i open 2 times(using different istancse,like connection1 and connecton2),is it ok? thank u very muchbest regardsmartinThis code will work in tests. But it will propably fail in a production environment. You don't even close the connection and that is bad enough. This is how you should never,
EVER work with disposeable objects!
try
MySqlConnection connectionLev = newMySqlConnection("server=P30LSIMUL;user id=root;database=cncp20l");
MySqlCommand cmd = connectionLev.CreateCommand();
connectionLev.Open();
Console.WriteLine("OK");
catch (Exception ex)
Console.WriteLine(ex.Message);
try
MySqlConnection connectionLev = newMySqlConnection("server=P30LSIMUL;user id=root;database=cncp20l");
MySqlCommand cmd = connectionLev.CreateCommand();
connectionLev.Open();
Console.WriteLine("OK");
catch (Exception ex)
Console.WriteLine(ex.Message);
If code like that runs in any production environment, you are about to get fired.
From a catapult.
SqlConnections implement Finalize so when the GC does collect them, they will be properly closed. That can be anywhere between "milisccond the reference vanishes" and "the programm is closed after 100 years of the computer running without
a hitch and reboot."
Put one of those blocks (or both) into a loop that runs 100 times and you will run out of avalible SQL conenctions.
Since you alraedy have a try...catch block, just use the construct that Magnus showed you:
Put the variable outside of the try (so finalize can access it). Check for null (in case an exception happened before/during the creation, not during the use of it) then Dispose.
Note that finalize is even run after the function it is contained in returns (about the only code that can still run then). And that you should always log/expose ex.ToString(), never only the message (that one contains only 5% of the information, the otehr
95% are much more important).
More tips about exception handling:
http://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET
Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2 Please mark post as helpfull and answers respectively. -
Some questions about configuration in MAX.
Hello,everyone!
I have some questions about configuration in MAX(I am a jackaroo for motion control development),I hope I can get your help.
I use PCI-7344+UMI-7764+Servo amplifier+Servo motor,my MAX version is 4.2 and I use NI-Motion7.5
My question as following:
1,In Axis Configuration,for motor type,why I must select stepper but not servo?my motor is servo motor!If I select Servo,my motor can't run,I don't know why.
If I select stepper,though motor can work but I can't test encoder in MAX.
2,In Stepper settings,for stepper loop mode,why I must select open-loop but not close-loop?If I select close-loop,the servo motor doesn't work too.
3,If I want my two servo motors run at different velocity,How shoud I do?It seems I just can set the same velocity in MAX for my two servo motors.
My English is poor,Pls pardon me!I come from China.
Thank you for your help!
EnquanLi
Striving is without limit!Hi,Jochen,
Thank you for your kindly help!
The manufacturer of the drive and motor that I am using now is Japan SANYO DENKI,drive type is RS1A01AA,motor type is R2AA06020FXP00.
And I use position control mode,thehe encoder's counts per revolution is 131072.I set the electronic gear ratio to 1:1 for drive.
Now,I can use Close-Loop to control the motor but still has some problems.When I configure it to run in closed loop mode, the motors behave strangely and never move to the target position.When I configure it to run in closed loop mode, the motors behave strangely and never move to the target position.The detail situation is as following
1,Motor can't run.
2, Or motor moves to a position, then moves in the same direction agian and eventually stops.
Except for the two points mentioned above,"Following Error" is occured frequently,I don't know why.
I am still not clear why I must set the motor type be stepper in MAX .
And I have another question:what the relationship between the steps and the counts?They have the proportion relations?I notice that there are a section said like this in help document: For proper closed-loop and p-command operation, steps per revolution/counts per revolution must be in the range of 1/32,767 < steps/counts < 32,767. An incorrect counts to steps ratio can result in failure to reach the target position and erroneous closed-loop stepper operation.
I am verry sorry I have too many questions!
I am very appreciate for your kingly help!Thanks again!
EnquanLi
China
Striving is without limit! -
Two questions about Risk Management 2.0
hi experts,
Please find below two questions about Risk Management:
-In SPRO, Risk Management>Create top node: after completing information and executing I have this error:
Error in the ABAP Application Program
The current ABAP program "/ORM/ORM_CREATE_TOP_NODES" had to be terminated
because it has
come across a statement that unfortunately cannot be executed.
The following syntax error occurred in program "/ORM/SAPLORM_API_SERVICES " in
include "/ORM/LORM_API_SERVICESU10 " in
line 97:
"Bei PERFORM bzw. CALL FUNCTION "GET_ORGUNIT_THRESHOLDS" ist der Aktual"
"parameter "I_ORGUNIT_ID" zum Formalparameter "IV_ORGUNIT_ID" inkompati"
"bel."
The include has been created and last changed by:
Created by: "SAP "
Last changed by: "SAP "
Error in the ABAP Application Program
The current ABAP program "/ORM/ORM_CREATE_TOP_NODES" had to be terminated
because it has
come across a statement that unfortunately cannot be executed.
Do you know where it could come from?
-On the Portal>Risk Management
when I click in a link under the risk management menu(activities and risks, risk report, document risk,...) i alway have an internal server error:
While processing the current request, an exception occured which could not be handled by the application or the framework.
If the information contained on this page doesn't help you to find and correct the cause of the problem, please contact your system administrator. To facilitate analysis of the problem, keep a copy of this error page. Hint: Most browsers allow to select all content, copy it and then paste it into an empty document (e.g. email or simple text file).
Do we have to set up some customizing points before accessing these links?
Thank you !
Regards,
JulienHi Julien ,
I have the same error what u described as :-
-On the Portal>Risk Management
when I click in a link under the risk management menu(activities and risks, risk report, document risk,...) i alway have an internal server error:
While processing the current request, an exception occured which could not be handled by the application or the framework.
If the information contained on this page doesn't help you to find and correct the cause of the problem, please contact your system administrator. To facilitate analysis of the problem, keep a copy of this error page. Hint: Most browsers allow to select all content, copy it and then paste it into an empty document (e.g. email or simple text file).
Do we have to set up some customizing points before accessing these links? "
Are you able to solve this. Please let me know how to resolve this???
Thanks
Regards,
Atul -
Question about email setting: how do i change the setting so i need to login to check my email. Currently it automatically come to the inbox without the need to log in.
You don't. Email comes in either by push or when you invoke the email app. Ther is no password except when you first set up the account. If your iPad is not being used as your personal device and you need to shield emails from other users, then don't use the email app. Instead, use web mail if available from your provider.
-
A few questions about Patone colors
I have a few questions about patone colors since this is the first time I use them. I want to use them to create a letterhead and business cards in two colors.
1)
I do understand that the uncoated is more washed out than the coated patone colors. I heard that this is because the way paper absorbs the inkt. This is why the same inkt results in different colors on different paper (right?). My question is why is the patone uncoated black so much different than normal black (c=0 m=0 y=0 k=100) or rich black:
When I print a normal document with cmyk, I can get pretty dark black colors. Why is it that I cannot have that dark black color with patone colors? Even text documents printed on a cheap printer can get a darker color than the Patone color. It just looks way too grey for me.
2) For a first mockup, I want to print the patone colors as cmyk (since I put like 10 different colors on a page for fast comparison). I know that these cmyk colors differ from the patone colors and that I cannot get a 100% representation. But is there a way to convert patone to cmyk values?
I hope that some of you can help me out with my questions.
Thanks.You can get Pantone's CMYK tints in Illustrator, (Swatches Panel > Open Swatch Library > Color Books > PANTONE+ Color Bridge Coated or Uncoated) but in my view, what's the point? If you're printing to a digital printer, just use RGB (HSB) or CMYK. Personally, I never use Pantone's CMYK so-called "equivalents."
Pantone colors are all mixed pigmented inks, many of which fluoresce beyond the gamut limits of RGB and especially CMYK. The original Pantone Matching System (PMS) was created for the printing industry. It outlined pigmented ink formulations for each of its colors.
Most digital printers (laser or inkjet) use CMYK. The CMYK color gamut is MUCH SMALLER than what many mixed inks, printed on either coated or uncoated papers can deliver. When you specify non-coated Pantone ink in AI, according to Pantone's conversion tables, AI tries to "approximate" what that color will look like on an uncoated sheet, using CMYK. -- In my opinion, this has little relevance to real-world conditions, and is to be avoided in most situations.
If your project is going to be printed on a printing press with spot Pantone inks, then by all means, use Pantone colors. But don't trust the screen colors; rather get a Pantone swatch book and look at the actual inks on both coated and uncoated papers, according to the stock you will use on the press.
With the printing industry rapidly dwindling in favor of the web and inkjet printers, Pantone has attempted to extend its relevance beyond the pull-date by publishing (in books and in software alliances, with such as Adobe) its old PMS inks, and their supposed LAB and CMYK equivalents. I say "supposed" because again, RGB monitors and CMYK inks can never be literally equivalent to many Pantone inks. But if you're going to print your project on a printing press, Pantone inks are still very relevant as "spot colors."
I also set my AI Preferences > Appearance of Black to both Display All Blacks Accurately, and Output All Blacks Accurately. The only exception to this might be when printing on a digital printer, where there should be no registration issues.
Rich black in AI is a screen phenomenon, unless in Prefs > Appearance of Black, you also specify "Output All Inks As Rich Black," -- something I would NEVER do if outputting for an actual printing press. I always set my blacks in AI to "Output All Blacks Acurately" when outputting for a press. If you fail to do this, then on the press you will see any minor registration problems, with C, M, and Y peeking out, especially around black type. UGH!
Good luck! :+) -
Questions about CIN tax procedure choice and pricing schemas
Hi all,
I have to implement SAP on a Indian company and I'm verifying all particularity about this country (in particular tax procedures and the great number of differents tax conditions used).
I have two questions about tax procedures and pricing schemas. Every feedback about thse points will be appreciated.
a) To choose tax procedure TAXINN or TAXINJ which are the elements that I have to consider?
I have read lot of documentation about CIN implementation and Iu2019m oriented to choose TAXINN schema, but If possible I would to understand better which are on behalf of one choice or another.
b) To define pricing schemas for India, after check with local users and using examples of documents (in particular tax invoice) actually produced, I have understood that taxes have to be applied on amount defined starting from price list, minus discounts recognized to customer plus surcharges eventually to bill (packing, transport, etc.).
Itu2019s correct for any type of taxes that tax amount is calculated on u201Cnet valueu201D defined at item level or there are exceptions to this rule?
Thanks in advance
Gianpaolohi,
this is to inform you that,
a) About point 1 I know the difference between the 2 tax procedures (conditions or formulas). I also have read in others post in the FORUM that TAXINN is preferable. So I would to understand which are the advantages to choose instead TAXINJ. There are particular reasons or it'a only an alternative customizing setting?
a.a. for give for posting the link : plese give me the advantages of TAXINJ and TAXINN
CIN - TAXINN and TAXINJ
b) About point 2, to define which value has to be used as base amount to calculate taxes isn't a choice, but is defined depending by fiscal requirement of the country, in this case India fiscal requirement. I know that, as Lakshmipathi
write as answer on my question, exception could be, but it was important for me to understand if I have understood correctly the sequence of the pricing condition in the schema in "normal" situation.
b.b. you can create your own pricing procedure for this and go ahead.
hope this clears your issue.
balajia -
Few questions about difference between Satellite P70 , L70, S70
Hello, i have many questions about the series P70 , L70, S70 that come with a 1920x1080 panel.
1) What are the differences between the L70 and S70 series? Except of the HDD capacity and RAM, the notebooks look pretty identical.
2) Do P70 , L70, S70 support a 2nd HDD or is it just the P70 series that support it ?
3) Do all three (P70, L70, S70 series) come with the same TFT Panels ?
4) Which of the above series supports mSata ?
5) Do all of the model of each series come with a mSata support? E.g. Could it be that L70-a-13m supports mSata while the L70-a-146 does not ?
6) All of the above, come with a S-ATA II or S-ATA III interface ?
7) Which is the best of those series listed ? I am trying to understand what makes the big difference from S70 to P70 except of the casing for example.
Thank you in advance.>1) What are the differences between the L70 and S70 series? Except of the HDD capacity and RAM, the notebooks look pretty identical.
What Sat L70 and S70 models do you mean exactly? There are different L70-xxx and S70-xxx models on the market which supports different hardware specifications.
>2) Do P70 , L70, S70 support a 2nd HDD or is it just the P70 series that support it?
As you can see in this [Sat P70 HDD replacement document,|http://aps2.toshiba-tro.de/kb0/CRU3903II0000R01.htm] the P70 series supports 2nd HDD bay BUT even if there is an 2nd HDD bay this does not mean that you could use 2nd HDD. In case the 2nd HDD bay would be equipped with HDD connector, you could use the 2nd HDD
I found also the [Sat L70/S70 HDD replacement |http://aps2.toshiba-tro.de/kb0/CRU3703HG0000R01.htm] document on Toshiba page and there I can see that 2nd HDD bay is not available
> 3) Do all three (P70, L70, S70 series) come with the same TFT Panels?
See point 1). Different P70, L70, S70 models were equipped with different hardware parts.
> 4) Which of the above series supports mSata?
As far as I know only some P70 models are equipped with an 256GB mSATA-SSD.
> 5) Do all of the model of each series come with a mSata support? E.g. Could it be that L70-a-13m supports mSata while the L70-a-146 does not ?
See point 4) not all models supports the same hardware specifications
> 6) All of the above, come with a S-ATA II or S-ATA III interface ?
I dont think that SATA III is supported. I guess it would be SATA II
> 7) Which is the best of those series listed ? I am trying to understand what makes the big difference from S70 to P70 except of the casing for example.
Not easy to answer because there are too many models released in Europea.
And not all models are available in each country. So I guess you will need to look for models which were released in your country. -
Few questions about Calendar / SimpleDateFormat classes
Hi.
I have few questions about Calendar class:
1. How can I get only date representation (without the time)?
after doing:
Calendar cal = Calendar.getInstance();
I tried to clear unecessary fields:
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.HOUR_OF_DAY);
But after printing the time, it seems that the HOUR was not cleared:
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
System.out.println(sdf1.format(cal.getTime()));
---> 03/11/2004 17:00:00
Am I missing somthing?
2. I want to make sure that two different formats couldn't be compared. i.e., if I'll try to parse one String according to different format -- ParseException will be thrown.
String date = "19/04/2004 13:06:10";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date dateObj = sdf.parse(date);
However, even though that formats are different, no exception is thrown and the return Date is 19/04/2004 00:00:00.
How can I cause to exception to be thrown if formats are not identical?
Thanks in advancedThe Calendar class has a few of what Microsoft would call 'features'. :^)
To clear the time, call:
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY), 0, 0, 0);
If you want 'pessimistic' rather than 'optimistic' date parsing, you have two options:
1) Call calendar.setLenient(false);
See if that is strict enough for your needs, otherwise:
2) Write code to ensure a stricter parsing of the string passed in. For example, you could very simply check the length of the string to determine if time data is also present.
When parsing, a string like '02/29/02' would parse to the date '03/01/02'. Setting lenient to false may fix this, but the surest way is to do some testing and then make the parsing more pessimistic where it suits your needs.
- Saish
"My karma ran over your dogma." - Anon -
Few questions about apex + epg and cookie blocked by IE6
Hi,
I would like to ask a few questions about apex and epg.
I have already installed and configured apex 3.2 on oracle 10g (on my localhost - computer name 'chen_rong', ip address -192.168.88.175 ), and enable anonymous access xdb http server.
now,
1. I can access 'http://chen_rong' , 'http://localhost' , 'http://192.168.88.175' without input username / password for realm 'XDB' in IE6;
2. I can access 'http://localhost/apex/apex_admin' , 'http://192.168.88.175/apex/apex_admin' , and I can be redirected into apex administation page after input admin/<my apex admin password> for realm 'APEX' in IE6;
3. I can access 'http://chen_rong/apex/apex_admin' in IE6, but after input admin/password , I can not be redirected into administation page, because the cookie was blocked by IE6.
then, the first question is :
Q1: What is the difference among 'http://chen_rong' , 'http://localhost' , 'http://192.168.88.175' ? I have already include site 'chen_rong' into my trusted stes! why the cookie was blocked by IE6. I have already tried firefox and google browser, both of them were ok for 'chen_rong', no cookie blocked from site 'chen_rong'!
and,
1. I have tried to use the script in attachment to test http authentication and also want to catch the cookie by utl_http .
2. please review the script for me.
3. I did:
SQL> exec show_url('http://localhost/apex/apex_admin/','ADMIN','Passw0rd');
HTTP response status code: 401
HTTP response reason phrase: Unauthorized
Please supplied the required Basic authentication username/password for realm XDB for the Web page.
Web page http://localhost/apex/apex_admin/ is protected.
MS-Author-Via: DAV
DAV: 1,2,<http://www.oracle.com/xdb/webdav/props>
Server: Oracle XML DB/Oracle Database
WWW-Authenticate: Basic realm="XDB"
Date: Tue, 04 Aug 2009 02:25:15 GMT
Content-Type: text/html; charset=GBK
Content-Length: 147
======================================
PL/SQL procedure successfully completed
4. I also did :
SQL> exec show_url('http://localhost/apex/apex_admin/','ANONYMOUS','ANONYMOUS');
HTTP response status code: 500
HTTP response reason phrase: Internal Server Error
Check if the Web site is up.
PL/SQL procedure successfully completed
SQL> exec show_url('http://localhost/apex/apex_admin/','SYSTEM','apexsite');
HTTP response status code: 401
HTTP response reason phrase: Unauthorized
Please supplied the required Basic authentication username/password for realm APEX for the Web page.
Web page http://localhost/apex/apex_admin/ is protected.
Content-Type: text/html
Content-Length: 147
WWW-Authenticate: Basic realm="APEX"
======================================
PL/SQL procedure successfully completed
my second questions is :
Q2: After I entered into realm 'XDB', I still need went into realm'APEX'. how could I change the script show_url to accomplish these two tasks and successfully get the cookie from site.
the show_url script is as following:
CREATE OR REPLACE PROCEDURE show_url
(url IN VARCHAR2,
username IN VARCHAR2 DEFAULT NULL,
password IN VARCHAR2 DEFAULT NULL)
AS
req UTL_HTTP.REQ;
resp UTL_HTTP.RESP;
name VARCHAR2(256);
value VARCHAR2(1024);
data VARCHAR2(255);
my_scheme VARCHAR2(256);
my_realm VARCHAR2(256);
my_proxy BOOLEAN;
cookies UTL_HTTP.COOKIE_TABLE;
secure VARCHAR2(1);
BEGIN
-- When going through a firewall, pass requests through this host.
-- Specify sites inside the firewall that don't need the proxy host.
-- UTL_HTTP.SET_PROXY('proxy.example.com', 'corp.example.com');
-- Ask UTL_HTTP not to raise an exception for 4xx and 5xx status codes,
-- rather than just returning the text of the error page.
UTL_HTTP.SET_RESPONSE_ERROR_CHECK(FALSE);
-- Begin retrieving this Web page.
req := UTL_HTTP.BEGIN_REQUEST(url);
-- Identify yourself.
-- Some sites serve special pages for particular browsers.
UTL_HTTP.SET_HEADER(req, 'User-Agent', 'Mozilla/4.0');
-- Specify user ID and password for pages that require them.
IF (username IS NOT NULL) THEN
UTL_HTTP.SET_AUTHENTICATION(req, username, password, 'Basic', false);
END IF;
-- Start receiving the HTML text.
resp := UTL_HTTP.GET_RESPONSE(req);
-- Show status codes and reason phrase of response.
DBMS_OUTPUT.PUT_LINE('HTTP response status code: ' || resp.status_code);
DBMS_OUTPUT.PUT_LINE
('HTTP response reason phrase: ' || resp.reason_phrase);
-- Look for client-side error and report it.
IF (resp.status_code >= 400) AND (resp.status_code <= 499) THEN
-- Detect whether page is password protected
-- and you didn't supply the right authorization.
IF (resp.status_code = UTL_HTTP.HTTP_UNAUTHORIZED) THEN
UTL_HTTP.GET_AUTHENTICATION(resp, my_scheme, my_realm, my_proxy);
IF (my_proxy) THEN
DBMS_OUTPUT.PUT_LINE('Web proxy server is protected.');
DBMS_OUTPUT.PUT('Please supply the required ' || my_scheme ||
' authentication username/password for realm ' || my_realm ||
' for the proxy server.');
ELSE
DBMS_OUTPUT.PUT_LINE('Please supplied the required ' || my_scheme ||
' authentication username/password for realm ' || my_realm ||
' for the Web page.');
DBMS_OUTPUT.PUT_LINE('Web page ' || url || ' is protected.');
END IF;
ELSE
DBMS_OUTPUT.PUT_LINE('Check the URL.');
END IF;
-- UTL_HTTP.END_RESPONSE(resp);
-- RETURN;
-- Look for server-side error and report it.
ELSIF (resp.status_code >= 500) AND (resp.status_code <= 599) THEN
DBMS_OUTPUT.PUT_LINE('Check if the Web site is up.');
UTL_HTTP.END_RESPONSE(resp);
RETURN;
END IF;
-- HTTP header lines contain information about cookies, character sets,
-- and other data that client and server can use to customize each
-- session.
FOR i IN 1..UTL_HTTP.GET_HEADER_COUNT(resp) LOOP
UTL_HTTP.GET_HEADER(resp, i, name, value);
DBMS_OUTPUT.PUT_LINE(name || ': ' || value);
END LOOP;
-- Read lines until none are left and an exception is raised.
--LOOP
-- UTL_HTTP.READ_LINE(resp, value);
-- DBMS_OUTPUT.PUT_LINE(value);
--END LOOP;
UTL_HTTP.GET_COOKIES(cookies);
dbms_output.put_line('======================================');
FOR i in 1..cookies.count LOOP
IF (cookies(i).secure) THEN
secure := 'Y';
ELSE
secure := 'N';
END IF;
-- INSERT INTO my_cookies
-- VALUES (my_session_id, cookies(i).name, cookies(i).value,
-- cookies(i).domain,
-- cookies(i).expire, cookies(i).path, secure, cookies(i).version);
dbms_output.put_line('site:'||url);
dbms_output.put_line('cookies:');
dbms_output.put_line('name:'||cookies(i).name);
dbms_output.put_line('value:'||cookies(i).value);
dbms_output.put_line('domain:'||cookies(i).domain);
dbms_output.put_line('expire:'||cookies(i).expire);
dbms_output.put_line('path:'||cookies(i).path);
dbms_output.put_line('secure:'||secure);
dbms_output.put_line('version:'||cookies(i).version);
END LOOP;
UTL_HTTP.END_RESPONSE(resp);
EXCEPTION
WHEN UTL_HTTP.END_OF_BODY THEN
UTL_HTTP.END_RESPONSE(resp);
END;
/I use oracle database enterprise edtion 10.2.0.3. I have already figured out the epg on 10.2.0.3 to support apex 3.2.
And as I described above, the apex site works fine for ip address , and localhost. but the cookie will be blocked by IE6, if I want to access the site by 'http://computername:port/apex/apex_admin'. This problem does not occured in firefox and google browser. Could someone give me answer?
Maybe you are looking for
-
Can one join a 2011 Mini to an older model, plus external HD?
I currently have the 2006 Mac Mini connected by firewire to a La Cie external hard drive. I would like to know if the new Mini can be connected to the existing mini -- and by extension the firewire HD -- Also would i need to purchase a separate editi
-
ORA-06502 encountered due to negative sign
Problem: I encountered the error in my sql statement with the message: declare ERROR at line 1: ORA-06502: PL/SQL: numeric or value error: character to number conversion error ORA-06512: at line 144 I already found the problem: v_str:= lpad(nvl(to_ch
-
Changed Preferences to MANUAL - ipod STILL begins activity upon plugging in
Okay, this is absolutely infuriating. I have changed the ipod settings in itunes to do everything MANUAL that can possibly be set to MANUAL; however, the moment I plug in my ipod, the "Do not disconnect" text appears on the display, and it NEVER goes
-
Probleme with previews in 5.3
Hi after having handled my files, I have lost previews in Lightroom. If I change my catalog I found the previews but are Lightroom settings that are no longer available thank you for helping me PS: if this topic has already been dealt thank you to gu
-
Iphoto crashes when importing pevious systems iphoto pics
I restored my system on the same computer without deleting personal libraries. Now when I try to import my previous Iphoto library Iphoto crashes everytime. Also when I open I photo it say so many pictures have been found do you want to import so I s