Java returns wrong DynamicIP

I hava a dynamic IP address and the host:
"somehost.ip.net" returns my dynamic IP.
If I check it with nslookup or ping, I always see my actual IP.
I have run this code:
try {
                           InetAddress addr = InetAddress.getByName("somehost.ip.net");
                           byte[] ipAddr = addr.getAddress();
                           String ipAddrStr = "";
                              for (int i=0; i<ipAddr.length; i++) {
                                   if (i > 0) {
                                      ipAddrStr += ".";
                                  ipAddrStr += ipAddr&0xFF;
          } catch (UnknownHostException e1) {
               e1.printStackTrace();
On my computer it returns the right IP. I have tried to run it on the other one and it returns some other IP, I don't have now.
I have checked my DynIP account, there is info, that there is my current IP in their database.
Why on my computer this code returns always right IP. On other computers ping return always right actual IP. But threre is no garanty with the Java-Code on the other computers/servers. What can I do in this situation?
Thanks in advance.

I Think the other computer may not be performing a
DNS lookup. I used your code with a former employer
domain and it worked on both my laptop and my
desktop.
I traced the route to the domain and got back 20
hops.
Conversly, when I used the same procedure for my
registered DynDNS domain name, I never went past my
home router, which is configured to automatically
update the DynDNS record when my public IP changes.
So, in that line of thinking, I think the 'other
computer' is not getting the address for some reason,
or has a bogus host entry in the hosts file.
On another note, thats a nice little for loop you
have there. You do know about the
addr.getHostAddress() method dont you?
It makes life easier.
JJThanks JJ for your answer. It's much clearly for me now.
I can use addr.getHostAddress()I have just called it on the server, not at home. It shows wrong IP twice, so there is no HostAddress for the IP I got.
I know that this server run on Sun. There is the other one, with the same problem. Can you imagine my wounder, all worked fine and then I got error. I just couldn't imagine, what was wrong.
Sometimes it works, sometime not. Is there a way to get the real IP, if they don't have nslookup etc?

Similar Messages

  • Robot getpixelColor returns wrong color sometimes...

    Hey
    I ve got a problem. I read Pixels from a Game with the Robot getPixelColor method. Sometimes it returns right values, sometimes wrong! I check some pixels if they are white. The pixels dont move, so this same pixels are white everytime!.
    Now sometimes he returns wrong colors. Instead of 255,255,255 ...it returns 0,12,25 or something like that. (with the same x, y coordinate).
    My assumption is: My code is like following
    CheckPixel(MyRobot.getPixelColor(30,40);
    CheckPixel(MyRobot.getPixelColor(31,45);
    CheckPixel(MyRobot.getPixelColor(36,20);
    CheckPixel(MyRobot.getPixelColor(51,70);
    Now it has to return 255,255,255 but somtimes its not working, he return 0,0.12 .... 0,0,15..... 255,255,255 .. or something like that
    Could it be, that java does not refresh the robot object so fast when I call getPixelColor so fast in a row?
    Is there a command with which I force Java to wait until the pointer is on the right x,y coordinate? Except of Thread.Sleep();
    Thank you for your help..

    ok I try:
    Robot r = new Robot();
    int x, int y;
    x = getItSomehwere();
    y = getitsomehwere();
    for (int i= 0, i< 20; i++) {
    if (isThatPixelsWhite(x, y) != 0) {
      DoSomething;
    public int isThatPixelsWhite(int x, int y) {
    if  (
    r.getPixelColor(x+5,y+15).equals(Color.WHITE)  &&
    r.getPixelColor(x+7,y+19).equals(Color.WHITE) &&
    r.getPixelColor(x+9,y+11).equals(Color.WHITE) &&
    r.getPixelColor(x+21,y+5).equals(Color.WHITE) &&
    r.getPixelColor(x+13,y+2).equals(Color.WHITE) &&
    r.getPixelColor(x+23,y+7).equals(Color.WHITE) &&
    r.getPixelColor(x+9,y+9).equals(Color.WHITE) &&
    r.getPixelColor(x+10,y+21).equals(Color.WHITE) &&
    r.getPixelColor(x+11,y+22).equals(Color.WHITE)
    ) return 1;
    return 0;
    }Thats the relevant code.
    I guess the fast calling of getPixelColor in this if struct (in Method isthatPixelsWhite) overburd java ..

  • Report returns wrong data when run on server

    Hi,
    I'm runing CRS XI R2 on Windows Server 2003 SP2.  When I refresh a report in the Crystal Reports XI Designer, I'm getting correct data.  But when I schedule the report to run on the server it returns wrong data.  The data is different from what I see when I refresh it from the designer.  In the report I have running totals set up to count customers that meet a certain criteria.  The report is very large.  It take almost 2 hours to refresh.
    I was wondering what is causing the difference in running total data between refreshing it on the designer and running it on the server.  Is it returning wrong data b/c of it not reading all the records?  Should I be making any changes to the server settings?  I saw that under pageserver, there are options for  setting the 'Minutes Before an Idle Report Job is Closed' and 'Database Records To Read When Previewing Or Refreshing a Report".  Do either of those have anything to do with the report returning incorrect data when being scheduled to run on the server?
    Thanks,
    Kim

    Hi Xuandao,
    You would need to Use Cell Binding and Trigger concept to accomplish this.
    Its simple, however, you would have to work on a trial and error basis to understand this concept as implementing the same is subject to your dashboard and WEBI Design.
    Open you LiveOffice.
    Insert your WEBI, Now, go to Object Properties of your WEBI, select the second tab that says Prompt, Here, it lists the prompts that you have for your WEBI. This would also enlist your BEx variables as well. Select this BEx variable and click on the button that says Prompt at the bottom of this window. Here, select choose Excel Data Range and click on the cell select button on the right (small button that lets you choose what cell you want to bind this prompt to), Now select a free cell that would not be even populated later on when you run the dashboard say A1 (remember the value that you select). Click on OK and again OK. The WEBI Refreshes and you can see all the prompt values at the cell A1. These are all the possible values stored for your BEx prompt variables (these values are fetched from BW system dynamically).
    Now, save this LiveOffice, Go to you dashboard. Connect your dashboard to your Live office. Go to Data-> connections-> Now, select the WEBI and in the right hand pane  go to Usage tab, here, Click on Trigger cell button on the right hand side and select A1 in you LiveOffice.
    It should work fine.
    Let me know.
    Rgds,
    Sreekul Nair

  • Statvfs returns wrong values

    Hi,
    I am developing a program the will check for disk space (used,blocks, available ...) and i am using the statvfs.h file.
    When tested with small capacity disks (~5G) it works fine (compared to df -k).
    When tested with large capacity disks (~400G) it returns wrong values(compared to df -k).
    I am using f_bavail and i am casting from fsblkcnt_t to integer/long.
    Please help.
    Thanx R.

    Thanks for your answer.
    I have discovered that it (statvfs.h) doe's not work with vxfs, only with ufs.
    I am using Veritas Cluster Server.
    Any chance of an answer ??
    thanks,
    R.

  • JSObject returns wrong date. How can I extract correct date from digital signature?

    I'm trying to extract name and date from digital signatures by using JSObject in Excel VBA, but JSObject returns wrong date. Year, month, hour and minute are correct, but only day is incorrect.
    Here is my code. I'm using Acrobat 8.1.3.
    Please tell me what's wrong with this code and how I can extract correct date from digital signatures.
    Public Sub sbTest()
    Dim oApp As Acrobat.acroApp
    Dim oPDDoc As Acrobat.AcroPDDoc
    Dim jso As Object
    Dim f As Object
    Dim sig As Object
    Dim strFileName As String
    Set oApp = CreateObject("AcroExch.App")
    Set oPDDoc = CreateObject("AcroExch.PDDoc")
    strFileName = "C:\Test.pdf"
    If (oPDDoc.Open(strFileName)) Then
    Set jso = oPDDoc.GetJSObject
    Set f = jso.getField("Signature1.0")
    Set sig = f.signatureInfo()
    Debug.Print sig.Name
    Debug.Print sig.Date
    End If
    Call oPDDoc.Close
    Call oApp.Exit
    End Sub

    Hi
    You can use TDMS file format to save the data. I have attached a reference Vi.
    On button click you can log the data or remove the case structure and continuous log the complete acquisition data.
    Thanks and Regards
    Himanshu Goyal
    Thanks and Regards
    Himanshu Goyal | LabVIEW Engineer- Power System Automation
    Values that steer us ahead: Passion | Innovation | Ambition | Diligence | Teamwork
    It Only gets BETTER!!!
    Attachments:
    Data Save in File.vi ‏35 KB

  • SXPG_COMMAND_EXECUTE  return wrong parameter value

    Dear all.
    We have an Abap program that pulls an encrypted FTP file and saves it to our network.
    After that we activate an external command via transaction SM69 by calling FM SXPG_COMMAND_EXECUTE.
    This command is an execution of a batch file that executes a decryption method via PGP decryption software.
    The problem is that we get an output parameter of this FM (STATUS) as u201CEu201D (error) although the decryption is being executed successfully.
    We have the same process being activated same way successfully with another folders (rest is exactly the same).
    Why does SXPG_COMMAND_EXECUTE return wrong status value ?
    Regards,
    Rebeka

    SXPG_COMMAND_EXECUTE runs under certain operating system user account. Looks like that account does not have enough privileges to do what you want it to do. Look at the operating system for privileges (read,write,execute) of the user account SAPServiceuser or equivalent.
    /Simo

  • Please Help Urgent:Fast Search returning wrong result sets

    Hi All,
    We are facing below issue with fast search.
    Currently in My project  when  we are searching  for a phrase it is returning wrong result sets.
    For example if we search for “Endura”, It is returning documents related to
    Endura  as well as Centura.
    But the expected results are only Endura documents.
    When we look in to the documents we didn’t find the search term (“Endura” ) either inside document content or in its meta data.
    In order to resolve the issue we tried the below steps
    1-     
    We manually edited and saved the document, to ensure the appropriate Guid association to metadata.
    2-     
    Index reset
    3-     
    Full crawl
    But no luck  so far.
    Please help.Thanks in advance.
    Regards
    Subrat

    Subrat,
    This may be related to spellchecking or may be synonym. Spellcheck is based on indexed terms.
    The best test would be to run the queries from qrserver (13280) and then look at the spellcheck query transformations. If spellchecking is not doing it, then you must have a synonym setup .Check your keyword/synonyms from the SharePoint side. 

  • SQL query return wrong Windows version

    when excuting   'select @@VERSION' returns wrong Windows version. Why?

    when excuting   'select @@VERSION' returns wrong Windows version. Why?
    SELECT @@VERSION will return SQLServer version and not windows version
    Even in case of sql, if you're seeing a different version from what your management studio suggests, then it may be that you're SSMS (client tool) is of another later version whereas the server instance which you're actually connecting to may
    be of different (earlier) version.
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Function sometimes return wrong data

    Hi all.
    I have a very strange problem with a function. Situation is this: I have an application that handles processes. Each process have a number of steps that is arranged in a matrix like layout. User clicks a step to start/execute it.
    Now in a list of current processes i want to have an indication of how "far" a process has reached so i created a function for that and included that in my processlist fetch.
    gchs_user_process_steps is the table where the user data for the process step is
    gchs_process_steps is the definition table of what steps a process has
    gchs_steps is the definition table of all steps
    The below function is supposed to return latest step user clicked in the display matrix. tier is used to store the column number and sortorder is the row number of any step user clicked.
    CREATE OR REPLACE FUNCTION FN_REACHEDSTEP(p_user_process_id NUMBER)
    RETURN VARCHAR IS
      ret VARCHAR(30);
      ret_id INTEGER;
      ret_num INTEGER;
    BEGIN
       ret := '';
       ret_id := 0;
       ret_num := 0;
       BEGIN
    SELECT substr(step_name,1,30),step_id,reached INTO ret,ret_id,ret_num
    FROM (
    SELECT a.*, rownum rnum
    FROM (
        SELECT s.name AS step_name, ps.id AS step_id, max((ps.tier*1000)+ps.sortorder) AS reached
        FROM gchs_user_process_steps ups, gchs_process_steps ps, gchs_steps s
        WHERE ups.gchs_process_step_id=ps.id AND
           ps.gchs_step_id=s.id AND
           ups.gchs_user_process_id=p_user_process_id
        GROUP BY s.name,ps.id
        ORDER BY 3 DESC) a
    WHERE rownum <= 1 )
    WHERE rnum >= 1;
       EXCEPTION
         WHEN OTHERS THEN
            ret:='';
       END;     
          RETURN ret;
      EXCEPTION
    WHEN OTHERS THEN
           ret := '';
       RETURN ret;
    END FN_REACHEDSTEP;
    Now the problem is that the function sometimes return wrong value. The name of the step that is returned is not the one i get if i run the SQL by itself.
    So doing a
    SELECT substr(step_name,1,30),step_id,reached INTO ret,ret_id,ret_num
    FROM (
    SELECT a.*, rownum rnum
    FROM (
        SELECT s.name AS step_name, ps.id AS step_id, max((ps.tier*1000)+ps.sortorder) AS reached
        FROM gchs_user_process_steps ups, gchs_process_steps ps, gchs_steps s
        WHERE ups.gchs_process_step_id=ps.id AND
           ps.gchs_step_id=s.id AND
           ups.gchs_user_process_id=21680
        GROUP BY s.name,ps.id
        ORDER BY 3 DESC) a
    WHERE rownum <= 1 )
    WHERE rnum >= 1;
    and a
    select fn_ReachedStep(21680) from dual;
    will sometimes return different values.
    So is the function fundamentally wrong or is there any cache or something that i've missed that could hold "old" function outputs or am i missing something else.
    Thankful for any clues.
    I'm using Oracle 10.2.0.1.0
    Best regards
    /Tomas
    Edit: Here's some data that the system uses.
    gchs_steps
    ID           NAME
    10000     Step 1
    10020     Step 2
    10021     Step 3
    10022     Step 4
    10023     Step 5
    10060     Step 6
    10140     Step 7
    gchs_process_steps
    ID          GCHS_STEP_ID      TIER     SORTORDER
    10000     10000               0          1
    10001     10020               1          1                                                                                                                   
    10002     10021               1          2                                                                                                                   
    10003     10022               2          1
    10020     10023               3          5
    10060     10060                3          4
    10080     10140               3          2
    10040     10040               3          3
    10100     10160               4          3
    10160     10220               4          2
    11640     11640               3          1
    11660     11660               0          6
    11661     11661               0          7
    11600     11600               0          4
    11620     11620               4          1
    gchs_user_process_steps
    ID          GCHS_USER_PROCESS_ID     GCHS_PROCESS_STEP_ID
    35541     21680                         10002
    38441     21680                         10020
    38440     21680                         10000
    52062     21680                         10060
    Relations beween table is
    gchs_user_process_steps.gchs_process_step_id=gchs_process_steps.id
    and
    gchs_process_steps.gchs_step_id=gchs_steps.id
    So doing the SQL alone will always return
    SUBSTR(..)     STEP_ID REACHED
    Step 5      10020 3005
    but executing the function sometimes returns
    FN_REACHEDSTEP(21680)
    Step 6
    Also removing the rownum limits return and doing a
    SELECT s.name AS step_name, ps.id AS step_id, max((ps.tier*1000)+ps.sortorder) AS reached
    FROM gchs_user_process_steps ups, gchs_process_steps ps, gchs_steps s
    WHERE ups.gchs_process_step_id=ps.id AND
    ps.gchs_step_id=s.id AND
    ups.gchs_user_process_id=21680
    GROUP BY s.name,ps.id,ps.tier, ps.sortorder
    ORDER BY 3 DESC
    give this result
    STEP_NAME     STEP_ID     REACHED
    Step 5          10020     3005
    Step 6          10060     3004
    Step 3          10002     1002
    Step 1          10000     1
    Edited by: user4935832 on 2008-sep-19 01:38

    ORDER BY 3 DESC) a
    WHERE rownum <= 1 )
    WHERE rnum >= 1;Just some thoughts.
    1. You could replace "ORDER BY 3" by "ORDER BY reached"
    2. the rownum <=1 and rnum>=1 will return only one row... I don't understand the second one.
    Lastly, the difference might come from a duplicate value return by your MAX() function.
    If there is two rows (or more) with same MAX, Oracle might return one row arbitrary.
    To get the same row, you have to use some aggregation function like MAX() KEEP (DENSE_RANK LAST...).
    Here a try for your query, obviously not tested :
    SELECT max(substr(step_name,1,30)) keep (dense_rank last order by reached) as step_name,
           max(step_id) keep (dense_rank last order by reached,step_name) as step_id,
           max(reached) as reached
    FROM   (SELECT s.name AS step_name,
                   ps.id AS step_id,
                   max((ps.tier*1000)+ps.sortorder) AS reached
            FROM   gchs_user_process_steps ups,
                   gchs_process_steps ps,
                   gchs_steps s
           WHERE   ups.gchs_process_step_id=ps.id
           AND     ps.gchs_step_id=s.id
           AND     ups.gchs_user_process_id=21680
           GROUP BY s.name,ps.id) a;Nicolas.

  • Why does the cell style index returning wrong CellFormat value when parsing excel cells using OpenXml SDK?

    Consider a General format cell having a value of 39.95. When I fetch the CellFormat of the cell it returns wrong cell format-
    CellFormat thisCellFormat = ((CellFormat)cellFmts.ChildElements[(int)thisCell.StyleIndex.Value]);
    int fmtId = Convert.ToInt32(thisCellFormat.FormatId.Value);
    The value of fmtId returned is 1, and in some cases 38, where it should be 2 or 39.
    This issue is only for General format cells, I am getting correct id for Number format cells.
    Below is the
    Standard ECMA-376 Office Open XML File Formats specified set of implied cell formats for reference-
    ID Format Code
    0 General
    1 0
    2 0.00
    3 #,##0
    4 #,##0.00
    9 0%
    10 0.00%
    11 0.00E+00
    12 # ?/?
    13 # ??/??
    14 mm-dd-yy
    15 d-mmm-yy
    16 d-mmm
    17 mmm-yy
    18 h:mm AM/PM
    19 h:mm:ss AM/PM
    20 h:mm
    21 h:mm:ss
    22 m/d/yy h:mm
    37 #,##0 ;(#,##0)
    38 #,##0 ;Red
    39 #,##0.00;(#,##0.00)
    40 #,##0.00;Red
    45 mm:ss
    46 [h]:mm:ss
    47 mmss.0
    48 ##0.0E+0
    49 @

    The purpose of this forum is to support the Open Specifications documentation. You can read about the Microsoft Open Specifications program here,
    http://www.microsoft.com/openspecifications/en/us/default.aspx
    The library of Open Specification documents is located here,
    http://msdn.microsoft.com/en-us/library/dd208104.aspx
    It doesn’t appear that you are implementing one of the protocols cited.  Your question may be more applicable to MSDN's Microsoft Office for Developers/Open XML Format SDK forum at
    https://social.msdn.microsoft.com/Forums/office/en-US/home?forum=oxmlsdk
    Bryan S. Burgin Senior Escalation Engineer Microsoft Protocol Open Specifications Team

  • On Firefox stage.stageWidth stage.stageHeight return wrong values

    Hello,
    I have a problem on firefox windows 8, stage.stageWidth and stage.stageHeight return wrong values,
    swfobject.embedSWF("mySwf.swf", "mySwf", "500", "500", "14.0.0","expressInstall.swf", flashvars, params, attributes);
    on ie, Chrome stage.stageWidth and stage.stageHeight return 500
    on iFirefox stage.stageWidth and stage.stageHeight return 750 and my animation is smaller (66%)
    Thanks

    In order to target iPhone 5 you need to use AIR 3.5 beta or AIR 3.4
    pointing to iOS 6 SDK. Be sure to include the [email protected] to
    trigger the iPhone 5 size. In other words, the app has to be built
    targeting the iOS 6 SDK and have the new default png to trigger the full
    size on the iPhone 5.
    AIR 3.5 beta includes the bits that to target iOS 6 SDK, but you can
    target iOS 6 with AIR 3.4 by using the external SDK path in the package
    ANE prompt in FB 4.6
    http://labs.adobe.com
    iBrent

  • [ASK]Bugs of Java or Wrong Code?

    Dear All,
    What this is bugs of Java or me not to understand java programming, this my piece code :
    String kode = txtKode.getText();
            String nama = inputNama.getText();
            String keterangan = inputKeterangan.getText();
            try {
                Connection c = KoneksiMySql.getKoneksi();
                String sql = "UPDATE UNIT SET NAMA=?, KETERANGAN=?, WKT_INPUT=now() WHERE KODE=?";
                PreparedStatement p = c.prepareStatement(sql);
                p.setString(1, nama);
                p.setString(2, keterangan);
                p.setString(3, kode);
                p.executeUpdate();
                p.close();
                JOptionPane.showMessageDialog(null, "Data Berubah",
                        "Pemberitahuan", JOptionPane.INFORMATION_MESSAGE);
            } catch(SQLException e) {
                System.out.println("Error : " + e);
                JOptionPane.showMessageDialog(null, "Proses Rubah Unit Gagal",
                        "Pesan Error", JOptionPane.ERROR_MESSAGE);      
            }finally {
            inputNama.setText(null);
            inputKeterangan.setText(null);
                btnTambah.setEnable(true);
                btnHapus.setEnabled(false);
                btnRubah.setEnabled(false);
                inputNama.requestFocus();
    JOptionPane is Show and no error appears but data in database does not change, and code in block finally not executed.
    i'm use jInternalFrame, first run Only 'Add Button, Search Button' enable and other button are disable, then when 'Search Button' is clicked and open other jInternalFrame and get data form database, 'Add button' Disable and 'Delete Button, Change Button' are Enable. that my piece code on Change Button ActionPerformed.
    Please it's support.
    Thanks,
    Best & Regrads.

    Cross posted
    [ASK]Bugs of Java or Wrong Code?
    [HELP]Bugs of Java or Wrong Code?
    db

  • When orientation change and soft keyboard is activated, return wrong value

    Hello,
    in a View, when the orientation change and the soft keyboard is activated, this.navigator.height return wrong value.
    systemManager.stage.addEventListener(StageOrientationEvent.ORIENTATION_CHANGE, orientationChangeHandler);
    public function orientationChangeHandler(event:StageOrientationEvent):void {
    inp.text=String(this.navigator.height);
    thanks.

    Can you attach a simple sample application that demonstrates this?  What device are you seeing this issue on?

  • Java.util.Calendar returning wrong Date object

    Example: This was my scenario last night. A server in California has date/time of 'Mon Aug 18'. Current time in Indiana is 'Sun Aug 17'. I use Calendar.getInstance(TimeZone.getTimeZone("America/Indiana/Indianapolis")) to return a Calendar instance. I then call the getTime() method on that instance. It should return a Date object relating to that particular time zone. It will not. It defaults back to the server time. When I print out the Calendar instance everything is good, correct date, correct time,etc. WHY WON'T THE getTime() return the correct java.util.Date???
    Following is the output was run today so the dates happened to be the same so focus on the Time. Output includes Server time, new Calendar values, and the Date returned by calendar instance getTime(). See that the Calendar is getting the correct Time.
    SERVER DATE=Mon Aug 18 15:52:13 CEST 2003
    CALENDAR INSTANCE=java.util.GregorianCalendar[time=1061214732975,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Indiana/Indianapolis",offset=-18000000,dstSavings=0,useDaylight=false,transitions=35,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=1,ERA=1,YEAR=2003,MONTH=7,WEEK_OF_YEAR=34,WEEK_OF_MONTH=4,DAY_OF_MONTH=18,DAY_OF_YEAR=230,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=52,SECOND=12,MILLISECOND=975,ZONE_OFFSET=-18000000,DST_OFFSET=0]
    Date from getTime()=Mon Aug 18 15:52:12 CEST 2003

    I got it worked with using DateFormat.parse !
    The trick is to instantiate a new Date object as a result
    of parsing out of 'localized' date string.
    with below code :
    Calendar localCal = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles"));
    localCal.set(Calendar.DATE, 25);
    localCal.set(Calendar.MONTH, 7);
    localCal.set(Calendar.YEAR, 2003);
    localCal.set(Calendar.HOUR_OF_DAY,6);
    localCal.set(Calendar.MINUTE, 38);
    localCal.set(Calendar.SECOND, 11);
    Calendar sinCal = new GregorianCalendar(TimeZone.getTimeZone("Asia/Singapore"));
    sinCal.setTimeInMillis(localCal.getTimeInMillis());
    int date = sinCal.get(Calendar.DATE);
    int month = sinCal.get(Calendar.MONTH);
    int year = sinCal.get(Calendar.YEAR);
    int hour = sinCal.get(Calendar.HOUR_OF_DAY);
    int min = sinCal.get(Calendar.MINUTE);
    int sec = sinCal.get(Calendar.SECOND);
    String sinTimeString = date + "/" + month + "/" + year + " " + hour + ":" + min + ":" + sec;
    System.out.println("VIDSUtil.hostToLocalTime : time string now in SIN time : " + sinTimeString);
    java.util.Date sinTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(sinTimeString);
    System.out.println("time in SIN using Date.toString(): " + sinTime.toString());
    It prints out :
    VIDSUtil.hostToLocalTime : time string now in SIN time : 25/7/2003 21:38:11
    time in SIN using Date.toString(): Fri Jul 25 21:38:11 PDT 2003
    (Ignore the PDT, because Date.toString() defaults where the JVM is running)

  • Java returning incorrect values for width and height of a Tiff image

    I have some TIFF images (sorry, I cannot post them b/c of there confidential nature) that are returning the incorrect values for the width and height. I am using Image.getWidth(null) and have tried the relevant methods from BufferedImage. When I open the same files in external viewers (Irfanview, MS Office Document Imaging) they look fine and report the "correct" dimensions. When I re-save the files, my code works fine. Obviously, there is something wrong with the files, but why would the Java code fail and not the external viewers? Is there some way I can detect file problems?
    Here is the code, the relevant section is in the print() routine.
    * ImagePrinter.java
    * Created on Feb 27, 2008
    * Created by tso1207
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.print.PageFormat;
    import java.awt.print.PrinterException;
    import java.io.File;
    import java.io.IOException;
    import java.util.Iterator;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageReader;
    import javax.imageio.stream.FileImageInputStream;
    import javax.imageio.stream.ImageInputStream;
    import com.shelter.io.FileTypeIdentifier;
    public class ImagePrinter extends FilePrintable
       private final ImageReader _reader;
       private final int _pageCount;
       private final boolean _isTiff;
       //for speed we will hold current page info in memory
       private Image _image = null;
       private int _imgWidth = 0;
       private int _imgHeight = 0;
       private int _currentPage = -1;
       public ImagePrinter(File imageFile) throws IOException
          super(imageFile);
          ImageInputStream fis = new FileImageInputStream(getFile());
          Iterator readerIter = ImageIO.getImageReaders(fis);
          ImageReader reader = null;
          while (readerIter.hasNext())
             reader = (ImageReader) readerIter.next();
          reader.setInput(fis);
          _reader = reader;
          int pageCount = 1;
          String mimeType = FileTypeIdentifier.getMimeType(imageFile, true);
          if (mimeType.equalsIgnoreCase("image/tiff"))
             _isTiff = true;
             pageCount = reader.getNumImages(true);
          else
             _isTiff = false;
          _pageCount = pageCount;
       public int print(java.awt.Graphics g, java.awt.print.PageFormat pf, int pageIndex)
          throws java.awt.print.PrinterException
          int drawX = 0, drawY = 0;
          double scaleRatio = 1;
          if (getCurrentPage() != (pageIndex - getPageOffset()))
             try
                setCurrentPage(pageIndex - getPageOffset());
                setImage(_reader.read(getCurrentPage()));
                setImgWidth(getImage().getWidth(null));
                setImgHeight(getImage().getHeight(null));
             catch (IndexOutOfBoundsException e)
                return NO_SUCH_PAGE;
             catch (IOException e)
                throw new PrinterException(e.getLocalizedMessage());
             if (!_isTiff && getImgWidth() > getImgHeight())
                pf.setOrientation(PageFormat.LANDSCAPE);
             else
                pf.setOrientation(PageFormat.PORTRAIT);
          Graphics2D g2 = (Graphics2D) g;
          g2.translate(pf.getImageableX(), pf.getImageableY());
          g2.setClip(0, 0, (int) pf.getImageableWidth(), (int) pf.getImageableHeight());
          scaleRatio =
             (double) ((getImgWidth() > getImgHeight())
                ? (pf.getImageableWidth() / getImgWidth())
                : (pf.getImageableHeight() / getImgHeight()));
          //check the scale ratio to make sure that we will not write something off the page
          if ((getImgWidth() * scaleRatio) > pf.getImageableWidth())
             scaleRatio = (pf.getImageableWidth() / getImgWidth());
          else if ((getImgHeight() * scaleRatio) > pf.getImageableHeight())
             scaleRatio = (pf.getImageableHeight() / getImgHeight());
          int drawWidth = getImgWidth();
          int drawHeight = getImgHeight();
          //center image
          if (scaleRatio < 1)
             drawX = (int) ((pf.getImageableWidth() - (getImgWidth() * scaleRatio)) / 2);
             drawY = (int) ((pf.getImageableHeight() - (getImgHeight() * scaleRatio)) / 2);
             drawWidth = (int) (getImgWidth() * scaleRatio);
             drawHeight = (int) (getImgHeight() * scaleRatio);
          else
             drawX = (int) (pf.getImageableWidth() - getImgWidth()) / 2;
             drawY = (int) (pf.getImageableHeight() - getImgHeight()) / 2;
          g2.drawImage(getImage(), drawX, drawY, drawWidth, drawHeight, null);
          g2.dispose();
          return PAGE_EXISTS;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since version XXX
        * @return
       public int getPageCount()
          return _pageCount;
       public void destroy()
          setImage(null);
          try
             _reader.reset();
             _reader.dispose();
          catch (Exception e)
          System.gc();
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @return
       public Image getImage()
          return _image;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @return
       public int getImgHeight()
          return _imgHeight;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @return
       public int getImgWidth()
          return _imgWidth;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @param image
       public void setImage(Image image)
          _image = image;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @param i
       public void setImgHeight(int i)
          _imgHeight = i;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @param i
       public void setImgWidth(int i)
          _imgWidth = i;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @return
       public int getCurrentPage()
          return _currentPage;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @param i
       public void setCurrentPage(int i)
          _currentPage = i;
    }Edited by: jloyd01 on Jul 3, 2008 8:26 AM

    Figured it out. The files have a different vertical and horizontal resolutions. In this case the horizontal resolution is 200 DPI and the vertical is 100 DPI. The imgage width and height values are based on those resolution values. I wrote a section of code to take care of the problem (at least for TIFF 6.0)
       private void setPageSize(int pageNum) throws IOException
          IIOMetadata imageMetadata = _reader.getImageMetadata(pageNum);
          //Get the IFD (Image File Directory) which is the root of all the tags
          //for this image. From here we can get all the tags in the image.
          TIFFDirectory ifd = TIFFDirectory.createFromMetadata(imageMetadata);
          double xPixles = ifd.getTIFFField(256).getAsDouble(0);
          double yPixles = ifd.getTIFFField(257).getAsDouble(0);
          double xRes = ifd.getTIFFField(282).getAsDouble(0);
          double yres = ifd.getTIFFField(283).getAsDouble(0);
          int resUnits = ifd.getTIFFField(296).getAsInt(0);
          double imageWidth = xPixles / xRes;
          double imageHeight = yPixles / yres;
          //if units are in CM convert ot inches
          if (resUnits == 3)
             imageWidth = imageWidth * 0.3937;
             imageHeight = imageHeight * 0.3937;
          //convert to pixles in 72 DPI
          imageWidth = imageWidth * 72;
          imageHeight = imageHeight * 72;
          setImgWidth((int) Math.round(imageWidth));
          setImgHeight((int) Math.round(imageHeight));
          setImgAspectRatio(imageWidth / imageHeight);
       }

Maybe you are looking for