HTTP in Java

Hi, I am **very** new to Java, though I have prior knowledge of C, C++, Pascal, LISP, etc.
I was trying to write a program to simply fetch the first character of a text file from the web, in order to test my knowledge of HTTP in Java. The document is shed.hawknetwork.org/gamefiles/test.txt, which contains simply the content "thisisatest".
Here is what I wrote. It doesn't really work at all, and I was hoping someone would give me a hand in fixing it. I also attach the error given by Java, which doesn't make any sense to me as I am so new to the language.
Thanks in advance,
Adam.
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.applet.*;
public class TestApp extends Applet implements ActionListener
Button Test;
public void init()
  setLayout(new FlowLayout());
  Test = new Button("Test");
  Test.addActionListener(this);
  add(Test);
public void stop()
public char GetFirstChar()
  URL u;
  InputStream in;
  int c;
  try
   u = new URL("http://shed.hawknetwork.org/gamefiles/test.txt");
  catch(MalformedURLException e)
   getAppletContext().showStatus("Error 1.");
   return ' ';
  try
   in = u.openStream();
  catch(IOException e)
   getAppletContext().showStatus("Error 2.");
   return ' ';
  try
   c = in.read();
  catch(IOException e)
   getAppletContext().showStatus("Error 3.");
   return ' ';
  return ((char) c);
public void actionPerformed(ActionEvent act)
  char c;
  if (act.getSource() == Test)
   c = GetFirstChar();
   if (c != ' ')
    showStatus(String.valueOf(GetFirstChar()));
Exception in thread "AWT-EventQueue-1" java.security.AccessControlException: acc
ess denied (java.net.SocketPermission shed.hawknetwork.org:80 connect,resolve)
at java.security.AccessControlContext.checkPermission(AccessControlConte
xt.java:264)
at java.security.AccessController.checkPermission(AccessController.java:
427)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
at java.lang.SecurityManager.checkConnect(SecurityManager.java:1034)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:459)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:214)
at sun.net.www.http.HttpClient.New(HttpClient.java:287)
at sun.net.www.http.HttpClient.New(HttpClient.java:299)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLC
onnection.java:795)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConne
ction.java:747)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection
.java:672)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLCon
nection.java:916)
at java.net.URL.openStream(URL.java:1007)
at TestApp.GetFirstChar(TestApp.java:41)
at TestApp.actionPerformed(TestApp.java:68)
at java.awt.Button.processActionEvent(Button.java:388)
at java.awt.Button.processEvent(Button.java:356)
at java.awt.Component.dispatchEventImpl(Component.java:3955)
at java.awt.Component.dispatchEvent(Component.java:3803)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
read.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
ad.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

Maybe you can with Java Web Start. I don't know. If it's a requirement that you start it from a web page, a standalone app probably isn't what you want.
I'd suggest changing your applet so that it doesn't hardcode the URL it's trying to retrieve in the applet. Use a relative URL. So for example use resources references:
http://java.sun.com/j2se/1.5.0/docs/guide/lang/resources.html
Or create the URL dynamically by doing Applet.getCodeBase or .getDocumentBase and then futzing with the URL.
And/or put the applet and html on the server you're trying to reach from the applet.
The first option is probably best.

Similar Messages

  • Need help : how to send 3 parameters over http using Java POST

    I am trying to sending some data to agency company over http using Java POST
    They need 3 parameters and some contents like below
    1. Cmd : cmd=_RequestInsertNewLead
    2 Live : False
    3 XMLData : 3C%3Fxml+version%3D%........
    I already have XML done ,but I don't know how to send these guy over http
    is that like
    this.out = new DataOutputStream(os);
    out.writeBytes("Cmd");
    out.writeBytes(" cmd=_RequestInsertNewLead");
    out.writeBytes(" Live ");
    out.writeBytes("False");
    anyone could give help :)

    First of all, are you getting any exception?
    You didn't put much logging information in your code.
    You can also try this.Instead of doing sos.println(".....") try to build the output string using string buffer.
    Like:
    StringBuffer sb = new StringBuffer();
    sb.append("Some output");
    sb.append("More output");
    sos.print(sb.toString());
    sos.flush();Let me know if this works.

  • HTTP/HTTPS and Java

    Why is the difference between the following classes? Why do different versions of these classes exist the way they do? (This question is based off of Sun's Java 1.3.1 release).
    java.net.HttpURLConnection
    <==>
    sun.net.www.protocol.http.HttpURLConnection
    sun.plugin.protocol.https.BrowserHttpsURLConnection
    <==>
    com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnection
    I'm writing code that needs to make HTTPS connections (I am using JSSE for this). I can make HTTP connections just fine, but the 'connect' member variable in URLConnection always remains false when I attempt an HTTPS connection. I get no status codes or error messages, just a dead connection. In an effort to debug this, I figured I'd take a peek out the source to get a hint as to what was going wrong. Anyway, I found myself more confused looking at the source, because there are different versions of things in different places. This is what led me to the question above.
    Anyway help or insight would be much appreciated. Thanks.
    Jake

    the command-line looks like:
    /opt/third-party/pkg/java-1.3.1_SUN/bin/java -classpath /opt/quality-ass
    urance/lib/jars.current/HTTPClient.jar:/opt/quality-assurance/lib/jars.current/antlr.jar:/opt/quality-assurance/lib/jars.current/frank.jar:/opt/quality-assurance/lib/jars.current/org.jar:/opt/third-party/pkg/junit-3.2/jars/junit.jar:/opt/third-party/pkg/openxml-1.2/lib/openxml-1.2.jar:/opt/app/oracle/product/8.1.6/jdbc/lib/classes111.zip:/opt/third-party/jars/jsse.jar:/opt/third-party/jars/jnet.jar:/opt/third-party/jars/jcert.jar -Djava.library.path=/opt/quality-assurance/lib/jars.current qa.TestServer.GenericServer
    the starting point where we are concerned is the run method of the class HttpTask. also i don't include the implementations, but methods like createFullyQualifiedURL() and originalURL(), etc return strings like 'http://www.company.com/one/two/three.html' or 'https://www.company.com/one/two/three.html' and also 'http://www.company.com:80/one/two/three.html' and
    'https://www.company.com:443/one/two/three.html' depending on the startup params...
    i know the details are sparse, but hopefully you understand the context. also i can assume the ca side of things is working, because i can use my browser to access the site via https. the code i'm writing which is somewhat functioning as a web client cannot access the site via https however.
    jake
    public class HttpTask extends SubTask {
    // snip ..
    public ResultIf run() {
    // If we have already fetched, return NoResult
    if (this.statusCode() != -1) {
    return new NoResult(this.parent());
    // Initialize URL
    this.createFullyQualifiedURL();
    if (this.originalURL().length() == 0) {
    return this.defaultErrorResult(new Error("Empty URL"));
    try {
    // setup connection
    HttpURLConnection connection = null;
    connection = setupConnection();
    connection.connect();
    Log.log().debug("HTTP", "Fetching " + this.originalURL());
    // process page
    processPage(connection);
    if (statusCode >= 300 && statusCode < 400) {
    handleRedirect(connection);
    } catch (Exception e) {
    System.err.println(e);
    return new HttpResult(this, true, "");
    public HttpURLConnection setupConnection() throws Exception {
    java.net.HttpURLConnection.setFollowRedirects(false);
    java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Pro\
    vider());
    java.lang.System.setProperty("java.protocol.handler.pkgs","com.sun.net.\
    ssl.internal.www.protocol");
    java.lang.System.setProperty("javax.net.debug", "ssl,handshake,data,tru\
    stmanager");
    HttpURLConnection connection = null;
    URL tempURL = new URL(this.originalURL());
    URLConnection uc = tempURL.openConnection();
    connection = (HttpURLConnection) uc;
    connection.setRequestProperty("User-Agent", "Frank/3.0");
    // Deal w/ cookies:
    this.setCookieForFetch(connection);
    // FIX what should the behavior for this be?
    // Send POST headers if any
    if (this.method().startsWith("POST")) {
    ResultIf result = this.doPost(connection);
    // returns non-null only if error occurs.
    if (result != null) {
    return null;
    return connection;
    public void handleRedirect(HttpURLConnection connection) throws Exception {
    while (statusCode >= 300 && statusCode < 400) {
    // shouldn't need to handle this for POST case,
    // some things may redirect on POST even though it's
    // against the HTTP spec
    if (method().equals("GETS") || method().equals("POSTS")) {
    method("GETS");
    } else {
    method ("GET");
    redirectURL = connection.getHeaderField("Location");
    if (! redirectURL.startsWith("http")) {
    if (method().equals("GETS") || method().equals("POSTS")) {
    redirectURL = "https://" + this.baseURL() + ":" + myTask().variable("HTTPS_PORT") + redirectURL;
    } else {
    redirectURL = "http://" + this.baseURL() + ":" + myTask().variable("HTTP_PORT") + redirectURL;
    this.originalURL(redirectURL);
    connection = setupConnection();
    connection.connect();
    statusCode = connection.getResponseCode();
    processPage(connection);
    public void processPage(HttpURLConnection connection) throws Exception {
    this.statusCode(connection.getResponseCode());
    this.pageSize(connection.getContentLength());
    if (this.getDynamicCookies()) {
    String dCookies = getCookiesFromReply(connection);
    Hashtable cookies = new Hashtable();
    this.addCookiesFromString(cookies, dCookies);
    // HACK: this is a quick tweak because I don't think
    // it is a good thing to have for every fetch.
    cookies.remove("path");
    Hashtable dynamicCookies = Tool.cloneIt(this.dynamicCookies());
    Tool.mergeHashes(dynamicCookies, cookies);
    this.dynamicCookies(dynamicCookies);
    // Get HTML if applicable
    if (! this.method().equals("HEAD")) {
    this.html(Tool.slurp(connection.getInputStream()));
    // WARN: check to see if length is different from above pageSize
    this.pageSize(html.length());
    // snip...
    }

  • How to configure https in java?

    Dude,
    I just know that If we need https page in our java web application we have to configure on server which we are using .
    I am gonna use Jboss as my application server.Right now I am using Http protocol to log in my site.Despite security reasons my clients push me to make it as https.
    As of my Knowlege , I know that its just server configuration but not know how ?
    Please help me to fix this..

    Besides configuring, you will also need a HTTPS host certificate.

  • HTTPS in java

    Hi all,
    I am looking forward for your reply for the https activation in my landscape.Recently I have installed a new Netweaver 2004 portal server.At the time of installation I have installed the SAP cryptgraphic tool kit as well by giving the security level as strong. After that I have tried to change the settings in the config tool for the Https port and verified it in the browser level.Its not worked out for me. I have configured SSl for abap and I have downloaded license file and applied it in strustsso2.
    Is there anythign we have to do the same for java? Kindly advice me for the same.
    Thanks and Regards
    Vijay

    Follow the steps in the below thread: also go through the below help document.
    /thread/1207698
    http://help.sap.com/saphelp_nw70/helpdata/EN/f1/2de3be0382df45a398d3f9fb86a36a/frameset.htm
    Prerequisites:
    -Download SAP Cryptographic ToolKit at http://service.sap.com/ swdc and -> SAP Crypto-graphic Software -> SAP JAVA CryptoToolkit (J2EE Engine as of Release 6.30)
    -Unzip it with SAPCAR
    Logon in SDM and deploy the file
    Check in Visual Admin -> Dispatcher/Server -> Libraries -> core_libs iaik_jce.jar is included
    Loof for SSL Service in Config Tool in Server and Dispatcher, it should be "always"
    Steps:
    -Asking for a certificate
    Visual Admin -> Cluster -> Server (central instance ) -> Services -> Key storage -> Service_ssl -> Create
    Fill in all the data, and be careful with the common name:
    -It shouldn´t have "http" or "https" on it
    -It shouldn´t have port number on it
    For example: "https
    www.myportal.domain:port", the common name should be "www.myportal.domain"
    Visual Admin -> Key Storage -> service_ssl -> Select your certificate and u201CGenerate CSR Requestu201D
    Send the file to a CA
    -Importing the validated certificate:
    Visual Admin -> Key Storage -> Import CSR Response
    In each Server, under SSL Provider, assign the certificate to port 50001, in each Dispatcher
    Now, the portal is secure, and you can check it now.
    A last step would be export the certificate and send it to your Network Team, so they can export it in the load balancing server, reverse proxy, etc. 
    Regards,
    Jazz

  • Question on HTTP with Java

    I have a web page that adds any visitors ip address to a list that it maintains. Does anyone know how I can visit this page froma Java application to produce the same result. The page does not need to be displayed by the Java application, only "visited". If somebody could please tell me how to do this I would be very thankful.
    Gary

    Try to compile the program shown below and run it to see if it works for you (to run the program, type java testVisit URL where URL is the full address to your web page:
    import java.net.*;
    import java.io.*;
    public class testVisit {
       public static void main(String[] args) {
          try {
             URL url = new URL(args[0]);
             URLConnection connection = url.openConnection();
             connection.setRequestProperty("Referer", args[0]);
             connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0");
             BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
             String Line;
             while ((Line = in.readLine()) != null) System.out.println(Line);
             in.close();
          } catch (Throwable e) {e.printStackTrace();}
    }If it works or points you to the right direction, don't forget the Dukes!
    ;o)
    V.V.

  • Download a file using http proxy - java

    Hi,
    I'm trying to download a pic using http proxy.
    Means - I have the url to the pic, I want to get it by my proxy
    Can anyone help me with that? any link, example etc...?
    Thanks

    This works:String server="hostname";
    String user="user ID";
    String passwd="password";
    try {
         sun.net.ftp.FtpClient client = new sun.net.ftp.FtpClient();
         client.openServer(server);
         client.login(user, passwd);
         client.cd("..");
         sun.net.TelnetInputStream in = client.get("File to be downloaded");
         BufferedReader br = new BufferedReader(new InputStreamReader(in));
         String s;
         while((s=br.readLine()) != null) {
              System.out.println(s);
         in.close();
             br.close();
    catch (IOException ioe) {
         ioe.printStackTrace();
    }Mark

  • Bad http.agent in Java properties : a bug in the HTTP user-agent string?

    Hi all,
    Me :
    I'm patching AWSTATS (web log analyzer tool) in order to recognize which Java version has
    been used to download files.
    Context of the problem :
    Each time a Java program (or applet) is downloading a file (for example .class, .png, .html)
    from a web server, a line will be added in the web server log file. If the web server is well
    configured, the user agent used to download the file will be at the end of the line in the log file.
    For Sun Java JVM, the user agent string is configured in the Java properties under "http.agent".
    Usually, the user-agent string contains the word "Java" and the virtual machine version. In most
    cases, this is just a string like "Java/1.4.2", so this is relatively easy to parse.
    Problem :
    Looking in my web server stats, and then on the web, I found that a JVM's user-agent is
    "Mozilla/4.0 (Windows XP 5.1)", which obviously does not contains the word "Java".
    Consequently, it is difficult to say that this user-agent string belongs to a JVM.
    Further look in my log files and on google shows that this http.agent string appears
    on Microsoft Internet Explorer (it seems MSIE 6.0) over Windows XP with the J2RE plugin:
    http://board.gulli.com/thread/300321
    http://forum.java.sun.com/thread.jsp?thread=531295&forum=30&message=2559523
    http://forum.java.sun.com/thread.jsp?forum=63&thread=132769&start=210&range=15&tstart=0&trange=15
    http://forum.java.sun.com/thread.jsp?forum=32&thread=480899
    http://www.goodidea.ru/setupJava/javaInstall.htm
    The J2RE plugin version does not seems to play a role as this user-agent string has
    been seen on 1.4.1_02-b06, 1.4.2_01, 1.4.2_03 and 1.4.2_04-b05.
    Further information requested :
    I would like to know:
    1) if you have reported the same problem;
    2) if there is some rules for the http.agent property;
    3) if this is a bug.
    Thank you very much, and feel free to add you opinion.
    Julien

    The web log files where the "Mozilla/4.0 (Windows XP 5.1)" user-agent appears can be displayed using the following search terms on google :
    "Mozilla/4.0 (Windows XP 5.1)" -"(Windows XP 5.1) Java"
    http://www.google.ch/search?hl=fr&ie=UTF-8&q=%22Mozilla%2F4.0+%28Windows+XP+5.1%29%22+-%22%28Windows+XP+5.1%29+Java%22&btnG=Rechercher&meta=
    Julien

  • Java Program to run an https based url

    This is the simple code to read through a java program from a simple http based procot URL
    import java.net.*;
    import java.io.*;
    public class URLReader {
    public static void main(String[] args) throws Exception {
         URL yahoo = new URL("http://mail.yahoo.com/");
         BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                        yahoo.openStream()));
         String inputLine;
         while ((inputLine = in.readLine()) != null)
         System.out.println(inputLine);
         in.close();
    But if i use the url https://mail.yahoo.com/ instead of http://mail.yahoo.com/ then i have an exception given below
    Exception in thread "main" java.io.IOException: HTTPS hostname wrong: should be
    <mail.yahoo.com>
    at sun.net.www.protocol.https.HttpsClient.b(DashoA12275)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(DashoA12275)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect
    (DashoA12275)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLCon
    nection.java:626)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Dash
    oA12275)
    at java.net.URL.openStream(URL.java:913)
    at URLReader.main(URLReader.java:7)
    Now i want this program based on https to run. SO can anybody help me running the same program by using https? Or can anybody give me the code to run a url based on https protocol?

    Same as http://forum.java.sun.com/thread.jspa?threadID=677398&tstart=0 . Check reply on the other post.

  • Java applet runs inside html page when opened with http, but no longer with "Open File" menu, why?

    Using the "Open File" menu, file:///Users/234866H/Documents/atom/atomic1.html fails to open the java applet atomic1.class inside atomic.html. However, http://atom.curtin.edu.au/igor/atom/atomic1.html works just fine.
    I suspect the problem arose following the recent java upgrade. It is also there on Safari.
    Testing Java at http://www.java.com/en/download/testjava.jsp yields:
    "Your Java is working. Your Java configuration is as follows: Vendor: Apple Inc. Version: Java SE 6 Update 51 Operating System: Mac OS X 10.6.8 Java Architecture: 64-bit"
    However, this is an http test, and not an "Open File" test.
    Any help would be appreciated.

    Hello, I don't know about this specifically but this is what I would try.
    Instead of the string "\u7834\u70C2\u7269\u7A0B\u5E8F\u5458..."
    Set the encoding type in the String constructor first...
    ie:
    new String( "\u7834\u70C2\u7269\u7A0B\u5E8F\u5458...","GB18030");
    Here is a little class I whipped up to show the CharSets that are available to you..
    public class ShowAllCharSets
    ShowAllCharSets()
    Map myMap = Charset.availableCharsets();
    Iterator iterator = myMap.keySet().iterator();
       while (iterator.hasNext())
          System.out.println("Char set name = "+((String)it.next()));
    public static void main(String args[])
       new ShowAllCharSets();
    }Then use the preset charset String with the specific encoding already set for your menu items.
    GB18030 I picked arbitrarily because it is Chinese and you may have to try another.
    Good Luck!
    (T)

  • Create Java bean for a http session

    how can i create a java bean for an http session. also is it possible to access it from another java class within that session

    Try the following forum (about JSP technology)
    http://forum.java.sun.com/forum.jspa?forumID=45

  • Java proxy  - http.nonProxyHosts issue

    Hi,
    I have a test code that connects to a URL. I want the local URLs to be connected without proxy server. But It ends with the following error
    C:\temp>java -Dhttp.nonProxyHosts="192.168.10.150|*.mycompany.local|localhost" ProxyTest
    Exception in thread "main" java.io.IOException: Unable to tunnel through proxy.
    Proxy returns "HTTP/1.0 403 Forbidden"
    at sun.net.www.protocol.http.HttpURLConnection.doTunneling(HttpURLConnec
    tion.java:1648)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect
    (AbstractDelegateHttpsURLConnection.java:164)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLCon
    nection.java:1172)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Http
    sURLConnectionImpl.java:234)
    at ProxyTest.main(ProxyTest.java:17)
    The following is my code
    import java.net.*;
    import java.io.*;
    public class ProxyTest
         public static void main(String[] args) throws Exception
              System.setProperty("nonProxyHosts", "192.168.10.150|localhost");
              Authenticator.setDefault(new ProxyAuth("pandian", "pandian"));
              URL url = new URL("https://192.168.8.150/");
              SocketAddress addr = new InetSocketAddress("192.168.8.100", 808);
              Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
              HttpURLConnection con = (HttpURLConnection) url.openConnection(proxy);
              InputStream is = con.getInputStream();
              int i=-1;
              while ((i=is.read())!=-1)
                   System.out.print((char)i);
              is.close();
    class ProxyAuth extends Authenticator
         private String user, password;
    public ProxyAuth(String user, String password) { 
    this.user = user;
    this.password = password;
    protected PasswordAuthentication getPasswordAuthentication() { 
    return new PasswordAuthentication(user, password.toCharArray());
    The same code executes for any URLs those are not blocked by the proxy server.
    Any guess?
    Edited by: user3749193 on Aug 10, 2011 2:40 AM
    Edited by: user3749193 on Aug 10, 2011 3:18 PM

    By going through your code, i could see change in only below below line:
    Present code
    >
              Authenticator.setDefault(new ProxyAuth("eguser", "egurkha"));
              URL url = new URL("http://192.168.10.100/");
    earlier Code:
    >
              Authenticator.setDefault(new ProxyAuth("eguser", "egurkha"));
              URL url = new URL("http://192.168.8.100/");
    That means still your using proxy to access the urls. And earlier you were trying to access the proxy server, by below code:
    SocketAddress addr = new InetSocketAddress("192.168.8.100", 808);
    HttpURLConnection con = (HttpURLConnection) url.openConnection(proxy);
    Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);Regarding below error, it says the site you are trying to access is not having valid certificate/ the certificate is not trusted by your truststore.
    C:\temp>java ProxyTest
    Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.val
    idator.ValidatorException: PKIX path building failed: sun.security.provider.cert
    path.SunCertPathBuilderException: unable to find valid certification path to req
    uested targetEDiting:: To Add to your trust store run the below Program
    * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    *   - Redistributions of source code must retain the above copyright
    *     notice, this list of conditions and the following disclaimer.
    *   - Redistributions in binary form must reproduce the above copyright
    *     notice, this list of conditions and the following disclaimer in the
    *     documentation and/or other materials provided with the distribution.
    *   - Neither the name of Sun Microsystems nor the names of its
    *     contributors may be used to endorse or promote products derived
    *     from this software without specific prior written permission.
    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    import java.io.*;
    import java.net.URL;
    import java.security.*;
    import java.security.cert.*;
    import javax.net.ssl.*;
    public class InstallCert {
        public static void main(String[] args) throws Exception {
         String host;
         int port;
         char[] passphrase;
         if ((args.length == 1) || (args.length == 2)) {
             String[] c = args[0].split(":");
             host = c[0];
             port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
             String p = (args.length == 1) ? "changeit" : args[1];
             passphrase = p.toCharArray();
         } else {
             System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
             return;
         File file = new File("jssecacerts");
         if (file.isFile() == false) {
             char SEP = File.separatorChar;
             File dir = new File(System.getProperty("java.home") + SEP
                  + "lib" + SEP + "security");
             file = new File(dir, "jssecacerts");
             if (file.isFile() == false) {
              file = new File(dir, "cacerts");
         System.out.println("Loading KeyStore " + file + "...");
         InputStream in = new FileInputStream(file);
         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
         ks.load(in, passphrase);
         in.close();
         SSLContext context = SSLContext.getInstance("TLS");
         TrustManagerFactory tmf =
             TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
         tmf.init(ks);
         X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
         SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
         context.init(null, new TrustManager[] {tm}, null);
         SSLSocketFactory factory = context.getSocketFactory();
         System.out.println("Opening connection to " + host + ":" + port + "...");
         SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
         socket.setSoTimeout(10000);
         try {
             System.out.println("Starting SSL handshake...");
             socket.startHandshake();
             socket.close();
             System.out.println();
             System.out.println("No errors, certificate is already trusted");
         } catch (SSLException e) {
             System.out.println();
             e.printStackTrace(System.out);
         X509Certificate[] chain = tm.chain;
         if (chain == null) {
             System.out.println("Could not obtain server certificate chain");
             return;
         BufferedReader reader =
              new BufferedReader(new InputStreamReader(System.in));
         System.out.println();
         System.out.println("Server sent " + chain.length + " certificate(s):");
         System.out.println();
         MessageDigest sha1 = MessageDigest.getInstance("SHA1");
         MessageDigest md5 = MessageDigest.getInstance("MD5");
         for (int i = 0; i < chain.length; i++) {
             X509Certificate cert = chain;
         System.out.println
              (" " + (i + 1) + " Subject " + cert.getSubjectDN());
         System.out.println(" Issuer " + cert.getIssuerDN());
         sha1.update(cert.getEncoded());
         System.out.println(" sha1 " + toHexString(sha1.digest()));
         md5.update(cert.getEncoded());
         System.out.println(" md5 " + toHexString(md5.digest()));
         System.out.println();
         System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
         String line = reader.readLine().trim();
         int k;
         try {
         k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
         } catch (NumberFormatException e) {
         System.out.println("KeyStore not changed");
         return;
         X509Certificate cert = chain[k];
         String alias = host + "-" + (k + 1);
         ks.setCertificateEntry(alias, cert);
         OutputStream out = new FileOutputStream("jssecacerts");
         ks.store(out, passphrase);
         out.close();
         System.out.println();
         System.out.println(cert);
         System.out.println();
         System.out.println
              ("Added certificate to keystore 'jssecacerts' using alias '"
              + alias + "'");
    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
    private static String toHexString(byte[] bytes) {
         StringBuilder sb = new StringBuilder(bytes.length * 3);
         for (int b : bytes) {
         b &= 0xff;
         sb.append(HEXDIGITS[b >> 4]);
         sb.append(HEXDIGITS[b & 15]);
         sb.append(' ');
         return sb.toString();
    private static class SavingTrustManager implements X509TrustManager {
         private final X509TrustManager tm;
         private X509Certificate[] chain;
         SavingTrustManager(X509TrustManager tm) {
         this.tm = tm;
         public X509Certificate[] getAcceptedIssuers() {
         throw new UnsupportedOperationException();
         public void checkClientTrusted(X509Certificate[] chain, String authType)
              throws CertificateException {
         throw new UnsupportedOperationException();
         public void checkServerTrusted(X509Certificate[] chain, String authType)
              throws CertificateException {
         this.chain = chain;
         tm.checkServerTrusted(chain, authType);
    Edited by: 833545 on Aug 12, 2011 3:32 PM

  • Is there a way to create a semi-transparency with Java?

    I would like to be able to create a semi transparent form and I was does anyone know how to do this?

    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class CompositeTest extends JPanel {
        private BufferedImage backImage, frontImage;
        private float alpha = 1;
        public CompositeTest() throws IOException {
            backImage = ImageIO.read(new URL("http://today.java.net/jag/bio/JagHeadshot-small.jpg"));
            frontImage = ImageIO.read(new URL("http://today.java.net/jag/Image54-small.jpeg"));
        public Dimension getPreferredSize() {
            return new Dimension(backImage.getWidth(), backImage.getHeight());
        public void setAlpha(float alpha) {
            this.alpha = alpha;
            repaint();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            int x = (getWidth() - backImage.getWidth())/2;
            int y = (getHeight()- backImage.getHeight())/2;
            g2.drawRenderedImage(backImage, AffineTransform.getTranslateInstance(x, y));
            Composite old = g2.getComposite();
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
            x = (getWidth() - frontImage.getWidth())/2;
            y = (getHeight()- frontImage.getHeight())/2;
            g2.drawRenderedImage(frontImage, AffineTransform.getTranslateInstance(x, y));
            g2.setComposite(old);
        public static void main(String[] args) throws IOException {
            final CompositeTest app = new CompositeTest();
            JSlider slider = new JSlider();
            slider.addChangeListener(new ChangeListener(){
                public void stateChanged(ChangeEvent e) {
                    JSlider source = (JSlider) e.getSource();
                    app.setAlpha(source.getValue()/100f);
            slider.setValue(100);
            JFrame f = new JFrame("CompositeTest");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container cp = f.getContentPane();
            cp.add(app);
            cp.add(slider, BorderLayout.SOUTH);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }

  • Calling all java gurus - i cant figure out what is wrong with my code

    please can someone see why a null pointer exception is being thrown and how do i fix it?
    my current code which throws the null pointer is as below - the key issues that i need some java expert to tell me about is
    1. is the usage of resultSet ok in the way i'm doing it , i'm not able to look at the code in debug mode as don't have an IDE and don't know how to do a log4j setup. - i tried doing an out.println("Got........"); but servlet keeps on forwarding the request object to results.jsp even when i comment out the code. and recomplie and restart tomcat 4.1.
    2. is the way i'm declaring the List object and the adding stuff to bean and then stuffing bean into list ok?
    3. why is the List object null? although i know the query works fine - and that using the below original code where only one row of data was being retrieved and set into bean worked fine.
    current code with problem in the List object:
    package com.bt.ros;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import javax.sql.*;
    import javax.naming.InitialContext;
    import javax.naming.Context;
    import javax.naming.NamingException;
    * This class is a servlet that searches for a Finder Aid.
    * @author
    public class FinderAidsSearchS extends HttpServlet {
       * This is the static initializer,
       * executed the first time this class is referred to.
       * It makes sure the JDBC pool driver is loaded.
       * This method examines an HTTP request and searches for the
       * specified Finder Aid record in the database. It then redirects
       * the response to the <tt>Results.jsp</tt> JSP page.
      public void service(HttpServletRequest req, HttpServletResponse res)
           throws IOException
        HttpSession session = req.getSession(true);
    //res.setContentType("text/html");
    //PrintWriter out = res.getWriter( );
    //out.println("<HTML>");
    //out.println("<HEAD>");
    //out.println("<TITLE>");
    //out.println("A Servlet Example");
        String year   = req.getParameter("Year");
        String year_range      = req.getParameter("Year_Range");
        String county          = req.getParameter("County");
        Connection conn = null;
        try {
    //example code from tomcatmanual
    Context initContext = new InitialContext();
    Context envContext  = (Context)initContext.lookup("java:/comp/env");
    DataSource ds = (DataSource)envContext.lookup("jdbc/rosDS");
    //Connection
    conn = ds.getConnection();
              Statement stmt = conn.createStatement();
          String select = "select * from abridgment where " +
                          "(a_county = '" + county +
                          "' AND a_year_date = " + year +
    out.println("<DEBUG> <select> the select staement is : " + select);
          stmt.execute(select);
          ResultSet resultSet = stmt.getResultSet();
         Results abridgeresults = new Results();
         abridgeresults.setName("NaeemColl");
         Abridgment varabridgment = null;
          int nRows = 0;
          while(resultSet.next()){
            nRows++;
               varabridgment = new Abridgment();
           varabridgment.seta_county(county);
          varabridgment.seta_year_date(Integer.parseInt(year));
            varabridgment.seta_sub_year_volume(resultSet.getInt("a_sub_year_volume"));
           // out.println("varabridgment - attributes are:");
              //out.println("varabridgment - attributes are:" +varabridgment.geta_sub_year_volume());
              //out.println("varabridgment - attributes are:"+resultSet.getInt("a_sub_year_volume"));
              varabridgment.seta_page_id(resultSet.getString("a_page_id"));
            varabridgment.seta_month_date(resultSet.getInt("a_month_date"));
            varabridgment.seta_day_date(resultSet.getInt("a_day_date"));
            varabridgment.seta_year_sequence(resultSet.getLong("a_year_sequence"));
            varabridgment.seta_day_sequence(resultSet.getLong("a_day_sequence"));
            varabridgment.seta_year_volume(resultSet.getInt("a_year_volume"));
            varabridgment.seta_volume_id(resultSet.getString("a_volume_id"));
            varabridgment.seta_summary(resultSet.getString("a_summary"));
            varabridgment.seta_batch_id(resultSet.getLong("a_batch_id"));
            varabridgment.seta_image_id(resultSet.getLong("a_image_id"));
              abridgeresults.addAbridgment(varabridgment);
              //trying to use vector construct
          req.setAttribute("results",abridgeresults);
          //session.setAttribute("results", abridgeresults);
          stmt.close();
          conn.close();
    //out.println("</BODY>");
    //out.println("</HTML>");
    //      String sURL = res.encodeRedirectURL("/rossearch/results.jsp");
            try{
    //TEMPCOMM        res.sendRedirect(sURL);
    req.getRequestDispatcher("/rossearch/results.jsp").forward(req, res);
    //TEMPCODE
    //out.println("</BODY>");
    //out.println("</HTML>");
          catch(Exception e){
            System.err.println("Exception: FinderAidsSearchS.service: " + e);
        catch (Exception e) {
          System.err.println("Exception: FinderAidsSearchS.service: " + e);
    original code that worked fine - for one test row retrieved by query
      public void service(HttpServletRequest req, HttpServletResponse res)
           throws IOException
        HttpSession session = req.getSession(true);
    res.setContentType("text/html");
    PrintWriter out = res.getWriter( );
    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>");
    out.println("A Servlet Example");
    out.println("</TITLE>");
    out.println("</HEAD>");
    out.println("<BODY>");
    out.println("Using servlets");
       // if (! checkParams(req, res))
       //      return;
        String year   = req.getParameter("Year");
        String year_range      = req.getParameter("Year_Range");
        String county          = req.getParameter("County");
        Connection conn = null;
        try {
    //example code from tomcatmanual
    Context initContext = new InitialContext();
    Context envContext  = (Context)initContext.lookup("java:/comp/env");
    DataSource ds = (DataSource)envContext.lookup("jdbc/rosDS");
    //Connection
    conn = ds.getConnection();
          Statement stmt = conn.createStatement();
          String select = "select * from abridgment where " +
                          "(a_county = '" + county +
                          "' AND a_year_date = " + year +
    out.println("<DEBUG> <select> the select staement is : " + select);
          stmt.execute(select);
          ResultSet resultSet = stmt.getResultSet();
          Abridgment abridgment = new Abridgment();
          abridgment.seta_county(county);
          abridgment.seta_year_date(Integer.parseInt(year));
        //  abridgment.a_sub_year_volume        = Long.parseLong(c_phone);
          if (resultSet.next()){
            abridgment.seta_sub_year_volume(resultSet.getInt("a_sub_year_volume"));
            abridgment.seta_page_id(resultSet.getString("a_page_id"));
            abridgment.seta_month_date(resultSet.getInt("a_month_date"));
            abridgment.seta_day_date(resultSet.getInt("a_day_date"));
            abridgment.seta_year_sequence(resultSet.getLong("a_year_sequence"));
            abridgment.seta_day_sequence(resultSet.getLong("a_day_sequence"));
            abridgment.seta_year_volume(resultSet.getInt("a_year_volume"));
            abridgment.seta_volume_id(resultSet.getString("a_volume_id"));
            abridgment.seta_summary(resultSet.getString("a_summary"));
            abridgment.seta_batch_id(resultSet.getLong("a_batch_id"));
            abridgment.seta_image_id(resultSet.getLong("a_image_id"));
            session.setAttribute("isNewAbridgment", new Boolean(false));
          else{
            session.setAttribute("isNewAbridgment", new Boolean(true));
            out.println("<DEBUG> <AbridgmentSearchS-service> Abridgment not found: " + abridgment);
          session.setAttribute("abridgment", abridgment);
          stmt.close();
          conn.close();
    out.println("</BODY>");
    out.println("</HTML>");
          String sURL = res.encodeRedirectURL("/rossearch/results.jsp");
              try{
            res.sendRedirect(sURL);
          catch(Exception e){
            System.err.println("Exception: FinderAidsSearchS.service: " + e);
        catch (Exception e) {
          System.err.println("Exception: FinderAidsSearchS.service: " + e);
    exception being thrown is:
    2005-11-07 02:45:20 StandardWrapperValve[jsp]: Servlet.service() for servlet jsp threw exception
    org.apache.jasper.JasperException
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:254)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:594)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619)
         at java.lang.Thread.run(Thread.java:536)
    ----- Root Cause -----
    java.lang.NullPointerException
         at org.apache.jsp.results_jsp._jspService(results_jsp.java:95)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:210)
    ......etc..
    the problem line in the results_jsp.java is:
    for (int i = 0; i < myAbridgments.size(); i++) in a scriptlet in the jsp to retrieve the List of beans and go through each one as follows:
    <% List myAbridgments = (List) request.getAttribute("results");
    for (int i = 0; i < myAbridgments.size(); i++) {
                    abridgment = (Abridgment) myAbridgments.get(i);
    %>ok then all wanabe java experts lets see who is the first and best at resolving this one!
    i have 10 points on offer - and a HUGE AMOUNT of graditude and appreciation for any one who can help me resolve this - Thanks.

    Check replies here
    http://forum.java.sun.com/thread.jspa?threadID=680127

  • Can not reinstall Java 7 on Windows 8 x64

    Hi,
    Restinstalling Java 7 opens a dialog box saying that Java is already installed and should be uninstalled first. When I click on Yes to go on with unstalling, I get a second msg box saying that this action is only valid on installed products.
    I tried everything: running Cleansweep to clean the registry, running CCleaner for the same purpose. Using Cleansweep to delete manually the reg entries with name of value containing "java\", deleting any "java" directory on disk (in c:\program files, c:\program files (x86), c:\commonFiles, <user>\appData\localLow and I may forget deleted locations ... Finally rerun Cleansweep ...
    The problem still remains and, unless I can solve it, I will have to do a clean install of the OS (will be Windows 7 since Windows 8 drives me mad, sorry).
    Though, doing a clean install will cost me money, and 1 week of time !
    Will some nice person save me from this huge work ?
    Thanks in advance !
    Jean-Pierre

    Hello,
    It is odd that you are seeing a dialog saying it needs to be removed. Can you post a screenshot of that?
    If a particular update version is already installed, regardless of the build number in the case of EA builds, you will see a message saying that it is already installed, you can then continue or cancel.
    Why is it that you were trying to reinstall? As you called out the 64bit OS it may be the case that a 64bit JRE was installed and the JRE is not working in the 32 browser. I mention this as this is a common case.  Really only IE has a 64bit browser for Windows, Chrome and Firefox are do not provide production 64bit browsers and thus the 64bit plugin will not run in those browsers. Windows 8 as a bit more of a hurdle as Java must be run on the desktop rather then the start screen and the 32bit browser, as I recall, is the default.  Java.com will not provide the 64bit JRE unless a 64bit browser is being used for just this reason. Here are a few links that cover this:
    https://www.java.com/en/download/faq/java_win64bit.xml
    http://windows.microsoft.com/en-us/windows7/32-bit-and-64-bit-Windows-frequently-asked-questions
    You can obtain the 32bit JRE from https://www.java.com/en/download/manual.jsp
    To complete the uninstall there are some steps you can try this first:
    http://support.microsoft.com/mats/Program_Install_and_Uninstall/en
    Only if the above does not work... registry changes, be careful, back up the registry!
    https://www.java.com/en/download/help/regkey_addremove.xml
    Cheers,
    Roger

Maybe you are looking for