Help with Java Memory Leak in URLConnection

Hi everyone,
I can't seem to find the memory leak in the below code, if anyone could help, i would greatly appreciate it. The jist of the code is: I open up a URLConnection to update a ColdFusion page that takes in URL parameters passed in my URL. Then, I get the response. I also check for proxy usage and take that into consideration when making the connection.
I have one class to handle the Connections, Connect.java:
     * Connection using Username and Password, as well as boolean option to use Basic Proxy Authentication
     public Connect(String pHost, String pPort, String urlString,
                         String pUsername, String pPassword, boolean useProxy) {
          this.pHost = pHost;
          this.pPort = pPort;
          this.urlString = urlString;
          this.pUsername = pUsername;
          this.pPassword = pPassword;
          this.useProxy = useProxy;
     * Get the Input Stream from the Connection given a specific URL
     public java.io.InputStream getInputStream(String urlString) {
          if (urlString == null) urlString = this.urlString;
             exDialog = new ExceptionDialog(new javax.swing.JFrame());
          try {
               String auth = "";
               if (useProxy) {
                    System.getProperties().put("proxySet", "true");
                    System.getProperties().put("proxyHost", pHost);
                    System.getProperties().put("proxyPort", pPort);
                    String authString = "";
                    if (pUsername != null && pUsername != "") authString = pUsername + ":";
                    else authString = "username:";
                    if (pPassword != null && pPassword != "") authString = authString + pPassword;
                    else authString = authString + "password";
                    auth = "Basic " + new sun.misc.BASE64Encoder().encode(authString.getBytes());
               java.net.URL url = new java.net.URL(urlString);
               java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection();
               if (useProxy) conn.setRequestProperty("Proxy-Authorization", auth);
               conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)");
               conn.setDoInput( true );
               conn.setDoOutput( true );
               conn.connect();
               return conn.getInputStream();
          } catch (java.io.IOException ioe) {
               exDialog.showForThrowable(ioe.toString(),ioe);
               return null;
     }I call the code in Download.java:
Connect conn = new Connect(sm.pHost, sm.pPort, null, sm.pUser, sm.pPass, sm.useProxy);
new BufferedReader(new InputStreamReader(conn.getInputStream(sUpdateURL)));
in.close();For some reason, as I loop through this call, the memory footprint of my program grows through every iteration, eventually resulting in a Java Out of Memory error. I can't track the leak down and it's fairly frustrating. If anyone can help, that would be greatly appreciated. Thanks!

One place there might be a memory leak is in the line
exDialog = new ExceptionDialog(new javax.swing.JFrame());Even though the JFrame object goes out of scope when the ExceptionDialog method returns, JFrames stay around until they are closed, even though in this case it isn't even shown on the screen.

Similar Messages

  • Help with java mapping

    PI File adapter has a processing option u2018Empty-Message Handlingu2019 to ignore or Write Empty Files. In case there is no data created after mapping on target side then this option determines whether to write an empty file or not. But there is a catch to this option when it comes to using it with File Content Conversion which is described in SAP Note u2018821267u2019. It states following:
    I configure the receiver channel with File content conversion mode and I set the 'Empty Message Handling' option to ignore. Input payload to the receiver channel is generated out of mapping and it does not have any record sets. However, this payload has a root element. Why does file receiver create empty output file with zero byte size in the target directory?  Example of such a payload generated from mapping is as follows:                                                           
    <?xml version="1.0" encoding="UTF-8"?>                          
    <ns1:test xmlns:ns1="http://abcd.com/ab"></ns1:test>
    solution :
    If the message payload is empty (i.e., zero bytes in size), then File adapter's empty message handling feature does NOT write files into the target directory. On the other hand, if the payload is a valid XML document (as shown in example) that is generated from mapping with just a root element in it, the File Adapter does not treat it as an empty message and accordingly it writes to the target directory. To achieve your objective of not writing files (that have just a single root element) into the target directory, following could be done:
    Using a Java or ABAP Mapping in order to restrict the creation of node itself during mapping. (This cannot be achieved via Message Mapping)
    Using standard adapter modules to do content conversion first and then write file. 
    can someone help with java mapping that can be used in this case?

    Hi,
        You have not mentioned the version of PI you are working in. In case you are working with PI 7.1 or above then here is the java mapping code you need to add after message mapping in the same interface mapping
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Map;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import com.sap.aii.mapping.api.AbstractTransformation;
    import com.sap.aii.mapping.api.StreamTransformationException;
    import com.sap.aii.mapping.api.TransformationInput;
    import com.sap.aii.mapping.api.TransformationOutput;
    public class RemoveRootNode extends AbstractTransformation{
         public void execute(InputStream in, OutputStream out)
         throws StreamTransformationException {
    // TODO Auto-generated method stub
    try
         DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
         DocumentBuilder builderel=factory.newDocumentBuilder();
         /*input document in form of XML*/
         Document docIn=builderel.parse(in);
         /*document after parsing*/
         Document docOut=builderel.newDocument();
         TransformerFactory tf=TransformerFactory.newInstance();
         Transformer transform=tf.newTransformer();
         if(docIn.getDocumentElement().hasChildNodes())
              docOut.appendChild(docOut.importNode(docIn.getDocumentElement(),true));
              transform.transform(new DOMSource(docOut), new StreamResult(out));
         else
              out.write(null);
    catch(Exception e)
    public void setParameter(Map arg0) {
    // TODO Auto-generated method stub
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    try{
         RemoveRootNode genFormat=new RemoveRootNode();
         FileInputStream in=new FileInputStream("C:\\apps\\sdn\\rootNode.xml");
         FileOutputStream out=new FileOutputStream("C:\\apps\\sdn\\rootNode1.xml");
         genFormat.execute(in,out);
         catch(Exception e)
         e.printStackTrace();
    public void transform(TransformationInput arg0, TransformationOutput arg1)
              throws StreamTransformationException {
         // TODO Auto-generated method stub
         this.execute(arg0.getInputPayload().getInputStream(), arg1.getOutputPayload().getOutputStream());
    In case you are working in PI 7.0 you can use this code
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Map;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import com.sap.aii.mapping.api.StreamTransformation;
    import com.sap.aii.mapping.api.StreamTransformationException;
    public class RemoveRootNode implements StreamTransformation{
         public void execute(InputStream in, OutputStream out)
         throws StreamTransformationException {
    // TODO Auto-generated method stub
    try
         DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
         DocumentBuilder builderel=factory.newDocumentBuilder();
         /*input document in form of XML*/
         Document docIn=builderel.parse(in);
         /*document after parsing*/
         Document docOut=builderel.newDocument();
         TransformerFactory tf=TransformerFactory.newInstance();
         Transformer transform=tf.newTransformer();
         if(docIn.getDocumentElement().hasChildNodes())
              docOut.appendChild(docOut.importNode(docIn.getDocumentElement(),true));
              transform.transform(new DOMSource(docOut), new StreamResult(out));
         else
              out.write(null);
    catch(Exception e)
    public void setParameter(Map arg0) {
    // TODO Auto-generated method stub
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    try{
         RemoveRootNode genFormat=new RemoveRootNode();
         FileInputStream in=new FileInputStream("C:\\apps\\sdn\\rootNode.xml");
         FileOutputStream out=new FileOutputStream("C:\\apps\\sdn\\rootNode1.xml");
         genFormat.execute(in,out);
         catch(Exception e)
         e.printStackTrace();
    The code for PI 7.0 should also work for PI 7.1 provided you use the right jar files for compilation, but vice-versa is not true.
    Could you please let us know if this code was useful to you or not?
    Regards
    Anupam
    Edited by: anupamsap on Dec 15, 2011 9:43 AM

  • Help! where memory leak exist??

    I am new to java, and I wrote this web spider.But the programme is out of memory after downloading about 350 pages.It should download much more pages in theory.Is there memory leak?where?
    I have been working on this for several days,but still not find out.Please help me!
    package search;
    import java.net.*;
    import java.io.*;
    import java.util.regex.*;
    import file.FileOP;
    public class SearchOneWeb extends Thread {
    private String webName;//host name
    private MutexList urlQueue;//MutexList is thread safe class I wrote
    public SearchOneWeb(String webName, MutexList urlQueue) {
    this.webName = removewww(webName);
    this.urlQueue = urlQueue;
    urlQueue.add("http://" + webName + "/");
    start();
    public SearchOneWeb(SearchOneWeb sow) {
    this.webName = sow.webName;
    this.urlQueue = sow.urlQueue;
    start();
    public void run(){     
    try {
    search();
    } catch (Exception e) {
    e.printStackTrace();
    * remove www
    * @param url
    private static String removewww(String url) {
    if(url != null) {
    int index = url.indexOf("www.");
    if (index != -1)
    return url.substring(0, index) + url.substring(index + 4);
    else
    return url;
    else
    return null;
    * make URL object
    * @param url
    private static URL makeURL(String url) {
    if(url == null)
    return null;
    //only deal with HTTP
    if (!url.toLowerCase().startsWith("http://"))
    return null;
    URL verifiedUrl = null;
    try {
    verifiedUrl = new URL(url);
    if(verifiedUrl.getPath() == null)
    verifiedUrl = new URL(verifiedUrl.toString() + "/");
    } catch (Exception e) {
    return null;
    return verifiedUrl;
    * test if this url belong to this host
    * @param url
    private boolean isInHost(URL url) {
    boolean result = false;
    if(url != null) {
    String host = url.getHost().toLowerCase();
    if(host.indexOf(webName) != -1)
    result = true;
    return result;
    * down load web page
    * @param url
    * @return
    private String downloadPage(URL url) {
    String sURL = url.toString();
    String pageContent = null;
    try {
         HttpURLConnection con = (HttpURLConnection)url.openConnection();
         con.connect();
         BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line;
    StringBuffer pageBuffer = new StringBuffer();
    while ((line = reader.readLine()) != null) {
    pageBuffer.append(line).append('\n');
    pageContent = pageBuffer.toString();
    reader.close();
         con.disconnect();
    } catch(IOException e) {
         System.out.println("error: can't connect to " + sURL);
    return pageContent;
    * write file
    * @param url
    * @param content
    private void writeFile(String url, String content, String charSet) {
    try {
    FileOP.write(url, content, charSet);
    } catch (IOException e) {
    e.printStackTrace();
    System.out.println("can't write file " + url);
    * retrive links from page content
    * @param pageUrl
    * @param pageContents
    private void retrieveLinks(URL pageUrl, String pageContents) {
    //use regular expression to find links
    Pattern pattern = Pattern.compile("<a\\s+href\\s*=\\s*[\"|']?(.*?)['|\"|>]", Pattern.CASE_INSENSITIVE);
    Matcher m = pattern.matcher(pageContents);
    int index1 = 0;
    int index2 = 0;
    String link = null;
    String path = null;
    String dir = null;
    URL url = null;
    while (m.find()) {
    link = m.group(1).trim();
    if (link.length() == 0)
    continue;
    if (link.charAt(0) == '#')
    continue;
    if (link.indexOf("mailto:") != -1)
    continue;
    if (link.toLowerCase().indexOf("javascript") != -1)
    continue;
    if (link.indexOf("://") == -1) {
    if (link.charAt(0) == '/') {
    link = "http://" + webName + link;
    } else {
    path = pageUrl.getPath();
    dir = path.substring(0, path.lastIndexOf('/') + 1);
    link = "http://" + webName + '/' + dir + link;
    } else {
    if (!link.startsWith("http"))
    continue;
    else {
    index1 = link.indexOf('/', 7);
    if (index1 == -1)
    link = link + '/';
    index2 = link.indexOf('#');
    if (index2 != -1) {
    link = link.substring(0, index2);
    link = removewww(link);
    url = makeURL(link);
    if (url == null)
    continue;
    if (!isInHost(url))
    continue;
    if (urlQueue.contains(link))
    continue;
    urlQueue.add(link);
    public void search() throws Exception {
    if (urlQueue == null) {
    System.out.println("urlQueue is null!");
    return ;
    String sURL = null;
    URL url = null;
    String pageContents = null;
    while (urlQueue.size() > 0) {
         // Get URL at bottom of the list.
         sURL = urlQueue.getHead();
         url = makeURL(sURL);
         if (url == null)
    continue;
         pageContents = downloadPage(url);
         if (pageContents != null && pageContents.length() > 0) {
    writeFile(url.toString(), pageContents, "GBK");
    retrieveLinks(url, pageContents);
    * for test
    * @param args
    public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    MutexList urlQueue = new MutexList();
    SearchOneWeb sow = new SearchOneWeb("news.163.com", urlQueue);
    sleep(10000);
    SearchOneWeb sow1 = new SearchOneWeb(sow);
    SearchOneWeb sow2 = new SearchOneWeb(sow);
    }

    You said:
    I don't delete url from urlQueue,but the point is
    that the urlQueue does't consume much memory.
    You also said:
    The size of urlQueue is tens of thousands when out of
    memory,so it consumes several MB memory.
    Are these statements both meant to be true at the same time?I meant that urlQueue was not the main reason for out of memory,enen though it consumed several MB memory.It is the strings saving page content that result to out of memory.These strings account for more than 30MB memory when out of memory.The point is why these strings are not GCd. I can not figure it out.
    You don't need a queue element after you've processed
    it, or even while you're processing it, so just keep
    removing and processing the first item in the queue
    until it is empty. That's how queues are normally
    processed.I modified urlQueue.It keeps removing and processing the first item.But there is no improvement.The strings contaning page content are still not GCd.Why???

  • Web Service data source report causes Java memory leak

    Crystal Report designer fails to preview a report whose data source is a WSDL web service.  This happens when the Java run time process has exceeded the memory limit specified in the CRConfig.xml file.  The Java memory is never released by Crystal Reports until the Crystal Reports Designer is closed.  Version is Crystal reports 2008 (product version 12.2.4.507).
    This error also occurs in the Crystal Reports Viewer when used in a Microsoft .NET application (framework 3.5) referencing CrystalDecisions.CrystalReports.Engine.dll v12.0.2000.0, CrystalDecisions.Enterprise.Framework.dll v12.0.1100.0, CrystalDecisions.Enterprise.InfoStore.dll v12.0.1100.0, CrystalDecisions.ReportSource.dll v12.0.2000.0, CrystalDecisions.Shared.dll v12.0.2000.0
    I load the ReportDocument object based on the location of the .rpt file and then set the ReportSource object of the CrystalReportViewer control:
    string FullReportName = "TestFile.rpt";
    ReportDocument reportDoc = new ReportDocument();
    reportDoc.Load(FullReportName, OpenReportMethod.OpenReportByTempCopy);
    this.crystalReportViewer1.ReportSource = reportDoc;
    reportDoc.Close();
    reportDoc.Dispose();
    GC.Collect();
    The code displays the report in the report viewer.  However, every time the report is refreshed the Java runtime memory increases until the application cannot display the results.  The error messages are "Failed to retrieve data from the database." followed by "Cannot determine the queries necessary to get data for this report. Details: Unexpected error".  If you try to refresh the data once again the following errors occur: "Failed to retrieve data from the database." then "Cannot determine the queries necessary to get data for this report. Details: Schema file is invalid   Java heap space".
    Increasing the java heap space in the CRConfig.xml file merely prolongues the onset of this error.
    Is there a service pack or hot fix for this???
    PLEASE HELP.

    Many thanks for your help.  This solved the issue for our .NET code, however the leak is still present in the report designer.  I was also wondering if you could help further: because of the limits on the java memory process is there a way to ensure that a separate java process is started for each report that is loaded in my report viewers collection?  Essentially the desktop application that i have created uses a tab control to display each type report, so each tab goes through the following code when displaying a report and closing a tab:
    Is there a way to ensure that a different Java process is kicked off each time that I display a different report?  My current code in c# always uses the same Java process so the memory ramps up.  The code to load the report and then dispose of the report through closing the tab (and now the Java process) looks like this:
        private void LoadCrystalReport(string FullReportName)
          ReportDocument reportDoc = new ReportDocument();
          reportDoc.Load(FullReportName, OpenReportMethod.OpenReportByTempCopy);
          this.crystalReportViewer1.ReportSource = reportDoc;
        private void DisposeCrystalReportObject()
          if (crystalReportViewer1.ReportSource != null)
            ReportDocument report = (ReportDocument)crystalReportViewer1.ReportSource;
            foreach (Table table in report.Database.Tables)
              table.Dispose();
            report.Database.Dispose();
            report.Close();
            report.Dispose();
            GC.Collect();
    Thanks

  • DAC Service shuts down with Java Memory when regenerating indexes.

    We have set up to run the DAC as a windows service. We have just set up a new execution plan comprising subject areas from Financials and Inventory. When we run the first full load, the execution plan executes all steps, but when it starts to run the last task: QUERY_INDEX_CREATION, the DAC service shuts down subsequently failing the execution plan. In the stderr.log we see the following:
    11-11-2008 16:44:59 global
    SEVERE:
    ANOMALY INFO:::
    MESSAGE:::Database Object should be specified for sql commands.
    EXCEPTION CLASS::: com.siebel.analytics.etl.etltask.TaskInitializationException
    com.siebel.analytics.etl.etltask.SQLTask.doInit(SQLTask.java:86)
    com.siebel.analytics.etl.etltask.CountTableTask.doInit(CountTableTask.java:59)
    com.siebel.analytics.etl.etltask.GenericTaskImpl.init(GenericTaskImpl.java:129)
    com.siebel.etl.engine.core.Session.getTargetTableRowCounts(Session.java:3057)
    com.siebel.etl.engine.core.Session.run(Session.java:2972)
    java.lang.Thread.run(Thread.java:619)
    11-11-2008 16:45:04 global
    SEVERE: MESSAGE:::Java heap space
    EXCEPTION CLASS::: java.lang.OutOfMemoryError
    java.util.Arrays.copyOfRange(Arrays.java:3209)
    java.lang.String.<init>(String.java:216)
    java.lang.StringBuilder.toString(StringBuilder.java:430)
    com.siebel.etl.engine.core.IndexPropertyFactory.createIndexProperty(IndexPropertyFactory.java:28)
    com.siebel.etl.engine.core.Index.<init>(Index.java:71)
    com.siebel.etl.engine.core.TableIndexHandler.loadIndexes(TableIndexHandler.java:329)
    com.siebel.etl.engine.core.TableIndexHandler.populate(TableIndexHandler.java:96)
    com.siebel.etl.command.IndexCreationCommand.doExecute(IndexCreationCommand.java:64)
    com.siebel.etl.command.SqlCommand.doExecute(SqlCommand.java:9)
    com.siebel.etl.command.MultiSourceSqlCommand.execute(MultiSourceSqlCommand.java:82)
    com.siebel.etl.database.AsyncDatabaseCall.run(AsyncDatabaseCall.java:34)
    java.lang.Thread.run(Thread.java:619)
    11-11-2008 16:45:04 global
    SEVERE: MESSAGE:::Java heap space
    EXCEPTION CLASS::: java.lang.OutOfMemoryError
    java.util.Arrays.copyOfRange(Arrays.java:3209)
    java.lang.String.<init>(String.java:216)
    oracle.jdbc.driver.CharCommonAccessor.getString(CharCommonAccessor.java:385)
    oracle.jdbc.driver.T4CVarcharAccessor.getString(T4CVarcharAccessor.java:411)
    oracle.jdbc.driver.OracleResultSetImpl.getString(OracleResultSetImpl.java:397)
    oracle.jdbc.driver.OracleResultSet.getString(OracleResultSet.java:1515)
    com.siebel.etl.database.DAWResultSet.getString(DAWResultSet.java:597)
    com.siebel.etl.engine.core.TableIndexHandler.loadIndexes(TableIndexHandler.java:301)
    com.siebel.etl.engine.core.TableIndexHandler.populate(TableIndexHandler.java:96)
    com.siebel.etl.command.IndexCreationCommand.doExecute(IndexCreationCommand.java:64)
    com.siebel.etl.command.SqlCommand.doExecute(SqlCommand.java:9)
    com.siebel.etl.command.MultiSourceSqlCommand.execute(MultiSourceSqlCommand.java:82)
    com.siebel.etl.database.AsyncDatabaseCall.run(AsyncDatabaseCall.java:34)
    java.lang.Thread.run(Thread.java:619)
    11-11-2008 16:45:05 global
    SEVERE: Failed due to the following reason: Java heap space
    11-11-2008 16:45:05 global
    SEVERE: Failed due to the following reason: Java heap space
    11-11-2008 16:45:10 global
    SEVERE: MESSAGE:::Java heap space
    EXCEPTION CLASS::: java.lang.OutOfMemoryError
    This is repeated many times in the log. It manages to create some indexes, but eventually it shuts down the DAC windows service
    In the windows event viewer we then see this at 11-11-2008 16:
    "The Java Virtual Machine has exited with a code of 10, the service is being stopped."
    My guess is that we need to allocate more memory to the DAC Java VM, but how/where?
    Any ideas?
    best regards,
    Henrik Verup
    Edited by: [email protected] on Nov 20, 2008 10:34 AM
    We have managed to work around the problem, by changing the DAC Sytem Property (under Setup): CreateQueryIndexesAtTheEnd from true to false. This way, indexes are being rebuilt during the load - not at the end. This has helped in getting the execution pla to finisf succesfully. We are now working on how to increase Java heap memory of the DAC Server, when started as a windows service. We have installed a windows service to stop and start the DAC serve,r using a document by Olivier Lemaire from Oracle.
    Does anyone have experiences on this?

    java Heap memory in DAC can be increased from the Client Side .
    Open the file for editing----startclient
    echo off
    title Siebel DAC Client
    call config.bat
    Rem Uncomment the below if you want to see a DOS window with messages.
    Rem and comment out the JAVAW line.
    Rem
    Rem %JAVA% -Xms256m -Xmx1024m -cp %DACCLASSPATH% com.siebel.analytics.etl.client.view.EtlViewsInitializer
    Rem
    start %JAVAW% -Xms256m -Xmx1024m -cp %DACCLASSPATH% com.siebel.analytics.etl.client.view.EtlViewsInitializer
    edit 1024 and increase the heap memory sizee,this should work.We faced a similar issue and increasing the size of the java memory solved the issue.
    Let me know if this is solved

  • Problem with Java Memory "Could not reserve enough space for object heap"

    Hi gurus,
    I am not an expert with Java´s configuration, and I have a situation that I don´t understand. First of all, I am working at Centos 6.2 with jdk_1.6 and Tomcat 7.
    The problem is...
    - If I run Tomcat with JAVA_OPTS="-Xmx128m"* (at catalina.sh) all works fine.
    - If I run Tomcat with JAVA_OPTS="-Xmx512m"* (at catalina.sh) an error appears:
    Error occurred during initialization of VM
    Could not reserve enough space for object heap
    Could not create the Java virtual machine.
    This appear when I run java -version or when I try to stop Tomcat, and the Tomcat isn´t able to stop.
    The strange thing is that my server has more than 200M free in physical memory. So, why Tomcat isn´t able to stop? and Why Java doesn´t use the free memory in my server?
    Thanks in advanced.

    Hello EJP, thanks for your answer.
    I have explained bad.
    The server has 703M free when Tomcat is stopped. I had mentioned that my server has more than 200M free in physical memory when Tomcat is running with JAVA_OPTS="-Xmx512m", so I don´t understand why these errors appear.
    Do you understand me?
    Recently I have checked the swap memory, and it is disabled. In spite of swap memory is disabled I think java wouldn´t need this memory because it has free physical memory
    Thanks again.

  • Help with JAVA StringObject - & assign user input; StringMethod

    Hi Everyone! I need help with this Java Program, I need to write a program, single class, & file. That will prompt the user to enter a word. The output will be separted by hypens and do this until the user enters exit. I think this is done by using a string variable. Then use the length of the word to setup a loop to print each letter out with hypens. (example c-a-t)
    1. I think I should store the word like this: Word.Method(). Not sure of this the API was confusing for me because I wasn't sure of what to do.
    2. A string method to find out how many letters are in the user's word in order to setup a loop to print each letter out. I think I can use a While loop to accomplish this?
    3. A string method to access each letter in a string object individually in order to print individual letters to the screen with those hypens. This is really confusing for me? Can this be accomplished in the While loop? or do I declare variables in the main method.
    Any examples you can refer me to would be greatly appreciated. Thanks

    Getting user input:
    This may look strange to a newbie but there's nothing much you can do since you wanted a single class file:import java.io.*
    public class InputTest {
       public static void main(String[] args) {
          BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
          System.out.println("Hi! Please type a word and press enter.");
          String lineReadFromUser = in.readLine();
          System.out.println("You typed " + lineReadFromUser);
    }You can get the lenght of a String using the length() method. Example: int len = "Foobar".length();
    You can get the individual characters of a String with the charAt() method. Example: char firstCharOfString = string.charAt(0);
    (remember that the argument must be from 0 to length-1)
    You can access the documentation of all classes, including java.lang.String, at http://java.sun.com/j2se/1.3/docs/api/index.html You can also download the docs.

  • Help with Java assignments

    I need some help with some Java assignments. I'm new to it, and I am having some problems.

    People will help you - if you help them first by stating your problem. If it was a generic question wanting to know wether anyone will help you at all - the answer is yes, they would - you have to put your work in first however.
    Ironluca

  • Help with Java Web Start

    Hi everybody,
    I have a simple Java application that has a JFrame containing a TextField displaying some text inside it. I am using the NetBeans IDE. I am trying to Enable Java Web start for this application. The steps I have taken upto now are:
    1. Right click on Project, Java Web Start -> Enable Java Web Start. This created the jnlp file.
    2. In the Resources section, I added the jar file for swing. ( I am not sure if I have to add the path for jnlp.jar etc, or are these found automatically?)
    3. Right click on Project, Java Web Start -> Deploy with Java Web Start. This launches the browser with the Click me link, but on clicking this link, I get the following error.
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    javax.servlet.ServletException: Wrapper cannot find servlet class jnlp.sample.servlet.JnlpDownloadServlet or a class it depends on
         org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
         org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
         org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
         org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
         org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
         org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
         org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
         java.lang.Thread.run(Thread.java:534)
    root cause
    java.lang.ClassNotFoundException: jnlp.sample.servlet.JnlpDownloadServlet
         org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1332)
         org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1181)
         org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
         org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
         org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
         org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
         org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
         org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
         org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
         java.lang.Thread.run(Thread.java:534)I have all the jnlp files in my jdk directory, and I am not sure why it can't find it. Is there something I am missing?
    Thanks
    George

    I am not sure what it has to do with servlets, I just followed a tutorial on using Netbeans with Java Web Start, and did only the steps as mentioned in my first post. And ended up with the error.
    Anyways, I added the jnlp jar files(jnlp.jar, jnlp-servlet.jar, jardiff.jar) in the WEB-INF/lib directory. And it seems to deploying it now. I can get my application to load on clicking on the "Click me" link. But the controls on my application don't seem to be working.
    Also, when I try to Right click on my project -> Java Web Start -> Run with Java Web Start, I get the following error message,
    javaws-run: C:\Documents and Settings\Lux\Visualization\nbproject\build-jaws-impl.xml:36: Execute failed: java.io.IOException: CreateProcess: C:\j2sdk1.4.2_13\bin\javaws "file:///C:/Documents and Settings/Lux/Visualization/Visualization.jnlp" error=2
    BUILD FAILED (total time: 0 seconds)
    Any help appreciated.
    Thanks.
    George

  • Help with java error

    Hi I got this error and i don't know what it means or how to fix it
    if you understand it please help
    Bad installation. Error invoking java vm(execv)
    C:\program Files\java\ire1.5.0_10\bin\javaw.exe
    I got this error when i went to add and remove programs in winXP
    and highlighted a program called Goban3 and clicked on change\remove
    http://www.gokgs.com/
    goban3 is sign on link to KGS
    if you check the site KGS you can see some java related items that have to be done i use this sights for years without problems
    but now im having problems with java
    thanks for serious reply
    Message was edited by: r
    revest

    That looks alot like this.

  • Help with java digital signing code

    hello people.
    can anybody help me?
    i have find a java code to resolve my problem with sending pay in soap envelope with digital signature and attached certificate. i compiled it with jdk jdk1.6.0_37. and it works.
    i need it to work in built-in jvm in oracle 9i. in oracle 9i jvm release is 1.3.1. Java code does not work there. there is an error
    class import com.sun.org.apache.xerces.internal.impl.dv.util.Base64 not found in import.
    i did not find this class in network.
    can anybody help with rewriting it for jvm 1.3.1?
    thanks in advance.
    code below:
    import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
    import java.io.*;
    import java.security.Key;
    import java.security.KeyStore;
    import java.security.PrivateKey;
    import java.security.Signature;
    import java.security.cert.Certificate;
    public class Sign {
    public static void main(String[] args) throws Exception {
    // TODO code application logic here
    BufferedReader reader = new BufferedReader(new FileReader("c:\\cert.p12"));
    StringBuilder fullText = new StringBuilder();
    String line = reader.readLine();
    while (line != null) {
    fullText.append(line);
    line = reader.readLine();
    KeyStore p12 = KeyStore.getInstance("pkcs12");
    p12.load(new FileInputStream("c:\\cert.p12"), "Hfrtnf$5".toCharArray());
    //????????? ????????? ????, ??? ????? ????? ???????????? alias ? ??????
    //Key key = p12.getKey("my kkb key", "ryba-mech".toCharArray());
    Key key = (Key) p12.getKey("my kkb key", "Hfrtnf$5".toCharArray());
    Certificate userCert = (Certificate) p12.getCertificate("my kkb key");
    String base64Cert = new String(Base64.encode(userCert.getEncoded()));
    //signing
    Signature signer = Signature.getInstance("SHA1withRSA");
    signer.initSign((PrivateKey) key);
    signer.update(fullText.toString().getBytes());
    byte[] digitalSignature = signer.sign();
    String base64sign = new String(Base64.encode(digitalSignature));
    String base64Xml = new String(Base64.encode(fullText.toString().getBytes()));
    System.out.println("<certificate>" + base64Cert+"</certificate>");
    System.out.println("<xmlBody>" + base64Xml+"</xmlBody>");
    System.out.println("<signature>" + base64sign+"</signature>");
    Edited by: user13622283 on 22.01.2013 22:08

    My first search is to see if there is an Apache commons project that provides it. Lo and behold:
    http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html
    commons-codec.

  • Help with Java Printing-Custom paper sizes

    Hi,
    I'm trying to print documents with custom paper sizes out of java.
    I can print fine when I don't try to set the MediaSize to a custom size or when I use already named constants like: "MediaSizeName.JIS_B4"
    The error message I get is this:
    java.lang.ClassCastException
         at javax.print.attribute.AttributeSetUtilities.verifyAttributeValue(Unknown Source)
         at javax.print.attribute.HashAttributeSet.add(Unknown Source)
         at hello.Printy.printDocument(Printy.java:103)
         at hello.Printy.main(Printy.java:135)
    The offending line(103) looks like this:
    pras.add(new MediaSize(1,10,MediaSize.INCH ));The function that its from looks like this:
    public  void printDocument()
    try
              System.out.println("input file name is");
         System.out.println(inputFileName);
    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
    PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
    PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
    PrintService printPrintService = null;
    // didn't work pras.add(new MediaSize(1,10,MediaSize.INCH) );
    PrintService service = ServiceUI.printDialog(null, 200, 200,printService, defaultService, flavor, pras);
    if (service != null)
         System.out.println("There is a service aunty-may!!");
    DocPrintJob job = service.createPrintJob();
    FileInputStream fis = new FileInputStream(getInputFileName());
    DocAttributeSet das = new HashDocAttributeSet();
    //pras.add(new MediaSize((float)3.25, (float)4.75, Size2DSyntax.INCH ) );
    // - works
    //pras.add(MediaSizeName.JIS_B4);
    pras.add(new MediaSize(1,10,MediaSize.INCH ));
    //pras.add(new MediaSize(1,10,MediaSize.INCH) );
         System.out.println("Doc has been set to custom size");
    Doc doc = new SimpleDoc(fis, flavor, null);
    job.print(doc, pras);
         System.out.println("any doc for you?");
    catch (Exception e)
    e.printStackTrace();
    }Any help with this would be greatly appreciated. I'm new to java but I've programmed a bunch in c++.

    Hmm ... no real help, but I found this note in the API:
    MediaSize is not yet used to specify media. Its current role is as a mapping for named
    media (see MediaSizeName). Clients can use the mapping method
    MediaSize.getMediaSizeForName(MediaSizeName) to find the physical dimensions of
    the MediaSizeName instances enumerated in this API. This is useful for clients which
    need this information to format & paginate printing.

  • Help with java coding involving stacks and queues.

    I was wondering if anyone can help with tips on what to fill in for the coding.
    My project is to creating a word processor by the process of 2 stacks. The methods are given, but I'm not really sure what goes in them. So I was wonder if anyone can answer this for me, or give tips that would be great thanks.
    Example Code, similar to what were suppose to do, but instead it's CHARACTER stacks rather than String.
    [http://www.cs.jhu.edu/~jason/226/hw3/source/EditableString.java]

    /** Stack of Characters to the left of the cursor; the ones
       * near the top of the stack are closest to the cursor.
      private Stack left;
      /** Stack of Characters to the right of the cursor; the ones
       * near the top of the stack are closest to the cursor.
      private Stack right;Do you know how a stack works?
    No - Google it
    Yes - Continue on with this post
    /** Another constructor.
       * @param left The text to the left of the cursor.
       * @param right The text to the right of the cursor.
      public EditableString(String left, String right) {
        // fill this in
      }Do you know how to read?
    No - How did you answer this question then?
    Yes - Then why can't you read the comments above each method. Is it really that hard to understand?
    Mel

  • Help with Java Web Service

    Hi,
    I tried integrating java code with java embedding acitivity, but in em it is failing. Can anybody know how to convert the below java code to a webservice, so that I can pass the input paramaters directly to that webservice. I tried of converting java code to webservice in jdeveloper, but because of static void main it is not converting. Can somebody help me in this issue.
    this is the original executable java code.
    package com.holx.api.test;
    import java.util.HashMap;
    import com.agile.api.APIException;
    import com.agile.api.AgileSessionFactory;
    import com.agile.api.IAdmin;
    import com.agile.api.IAgileClass;
    import com.agile.api.IAgileList;
    import com.agile.api.IAgileSession;
    import com.agile.api.IAutoNumber;
    import com.agile.api.IDataObject;
    import com.agile.api.INode;
    import com.agile.api.IProperty;
    import com.agile.api.IServiceRequest;
    import com.agile.api.PropertyConstants;
    import com.agile.api.ServiceRequestConstants;
    import com.agile.px.ActionResult;
    import java.net.URL;
    public class TestAgileAPI {
    //     @Override
    //     public ActionResult doAction(IAgileSession arg0, INode arg1,
    //               IDataObject arg2) {
              // TODO Auto-generated method stub
    //          return null;
         * @param args
         public static void main(String[] args) {
              IAgileSession m_session = null;
              IAdmin admin = null;
              IAgileClass cls = null;
         String sr="PR-KB00028";
    String userName="*******";
    String password="*******";
    String URL="*********";
              try {
                   HashMap params = new HashMap();
                   params.put(AgileSessionFactory.USERNAME, userName);
                   params.put(AgileSessionFactory.PASSWORD, password);
                   AgileSessionFactory instance = AgileSessionFactory.getInstance(URL);     
                   m_session = instance.createSession(params);     
                   admin = m_session.getAdminInstance();
                   cls = admin.getAgileClass( "ProblemReport" );
                   IServiceRequest psr = (IServiceRequest)m_session.createObject( "ProblemReport", sr);
              psr.setValue(ServiceRequestConstants.ATT_COVER_PAGE_DESCRIPTION, "KB-Test-20121400");
              } catch (APIException e) {
                   e.printStackTrace();
              } finally {
                   m_session.close();
    Can somebody help me in converting this code into a webservice which accepts String SR as input from soa.
    Thanks,

    Hi Francois,
    I never tried to use a webservice in the value help wizzard, so I don't know if it works or not.
    But for your problem you can build your own value help to avoid the problem.
    You told us that the webservice works in the storyboard. The value help wizard "only" creates a popup iView in your model and assigns the output field of the popup to an input field in a form.
    Maybe as a solution you can insert a popup to the model by yourself. Assign the output field of your popup to the input field for which you want to have the value help. Inside the popup iView you can use your custom built webservice.
    I know that this is a little bit circuitous, but I think it will work.
    Regards
    Christophe

  • Help with java.lang.StackOverflowError

    my program crashed with java.lang.StackOverflowError... what does it mean? what should i do to fix it?
    thanks.

    Just to add on what paulcw said,
    Check for recursive routines. These are normally the culprits. In particular, recursive methods that have a loop condition that keeps executing.
    Check for circular references. Method A calls method B which calls method C which calls back to method A. These are harder to spot, but stepping through your program execution should quickly reveal the pattern.
    For your last resort, create some debugging code (System.out, etc.). You should eventually get to a point where you see the last line that executed properly. Erase the remaining debugging code and then place more after the last successful execution point.
    Now that I think about it, that's just generic debugging technique when all else fails. But with out of memory or stack overflows, it's sometimes your last option.
    - Saish
    "My karma ran over your dogma." - Anon

Maybe you are looking for

  • PSE 7: Preset Manager Grayed Out

    Hi, Any reason why the preset manager in PSE7 is grayed out?  The attachment will show it better than me explaining it.  It works fine in PSE 4. Tony

  • Manufacturer number: Adding Manufacturer Number in Purcahse Order and follo

    Hi Gurus, I want to populate manufacturer name into Purcahse order from APM (aprroved mfg part list : MP01/MP02) and want to be displayed in Inspection Lot. Can any one help me in this? Answer will be appreciated and points will be given too. Regards

  • How to use Unicode characters with TestStand?

    I'm trying to implement the use of Greek characters such as mu and omega for units. I enabled multi-byte support in the station options and attempted to paste some characters in. I was able to paste the mu character (μ) and import it from Excel with

  • Subsequent Lookup Operators causes OWB to generate undeployable mappings

    Hi, I am using OWB 11gR2 . I am trying to create a fact loading mapping based on datavault. That gives me error during deployment. Validating and Generate doesn't give me an error. So in trying to load the fact i tie various datavault tables together

  • c:set works in one page and not another.. rediculous problem

    Hi all, im having one hell of a strange problem.. i have this bit of code on one page.. profile_body.jsp <jsp:useBean id="user" scope="request" beanName="com.insaini.publogs.business.UserBean" type="com.insaini.publogs.business.ProfileInterface" /> <