PrintWriter() issue

Hi. I'm trying to write a version of HTCPCP for a university assignment and am having a really basic problem with my PrintWriter object server side.
I have to include a brew() and a get() method. My brew() method simply returns a String telling the client that they must wait 6.2 seconds for the coffee to brew. I just chose an arbitrary value.
Then I want to call my get() method, 6.2 seconds after my brew() method and return a String to the client telling them to come and get their coffee because it's ready.
The problem is that the PrintWriter that I'm using seems to close if I use a println() statement to return the brew() method, so the get() method never gets called. However, if I use a print() statement, the program waits for 6.2seconds THEN calls the brew() and get() one after the other instantly. I've put the wait time within the get() method intially but tried putting in the main method and it still happens.
Any help would be greatly appreciated as I've spent a day trying to sort this out and have got nowhere.
Section of main():
PrintWriter out = null;
        BufferedReader in = null;
        try {
            out = new PrintWriter(clientSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            input = in.readLine();
            if (checkPropFind(input) == true)
                out.println(propfind());
            else {
                checkAdditions(checkAddress(input));
            out.print(brew());
            out.print(get());
            out.close();
        } catch (IOException e) {
            System.out.println(e);
        }brew():
public static String brew() {
        return "You're drink will now brew for 6.2 seconds to ensure it is perfect.\n";
    }get():
public static String get() {
        try {
            Thread.sleep(6200);
        } catch (InterruptedException e) {
            System.out.println(e);
            System.exit(1);
        return "\tYou're coffee is ready for collection.\n" +
                "\tThank you for using the MyCoffee Browser.\n " +
                "\tThe program will now exit.\n";
    }

The thing about print streams is they're buffered, and won't always send the data imediately.
Try out.flush(); between the two print statments. Always use flush if you require data to be sent immediately.
BTW always use e.printStackTrace() in your general purpose catch clauses, you'll get far more data from exceptions.

Similar Messages

  • PrintWriter issue with Directory Traversal and Regular Expression

    This is a follow up to my previous question on the forum. I am developing a program traverses the hard drive for information. If it finds the said information in any of the file (based on the regular expression wriiten) it must print the output into the file. Currently I am able to traverse the harddrive perfectly, the regular expression and the search is perfect and when I print the output into the local console, I am able to derive perfect results. But when I use the PrintWriter to write the output into the flight, it writes NOTHING into the file. I have been scouring all over the Internet for an answer, but havent been able to find. Would highly appreciate if someone can tell me what I am doing wrong and provide some guidance on how to get it right.
    public class myClass{
        BufferedReader br;
        String pcv;
        Pattern scPattern = Pattern.compile("Some regular expression");
        Matcher match = null;
        Pattern newPattern = Pattern.compile("Some regular expression");
        Matcher newMatch = null;
        String mvCheckVal;
        Matcher mvMatch;
        PrintWriter pw;
        void recursiveMethod(File dir) throws Exception {
                pw = new PrintWriter(new FileWriter("outputFile.txt"));
                pw.println("Opening pw stream.....");
                File[] files = dir.listFiles();
                String[] fileList = dir.list();
                for (int i = 0;i < files.length; i++) {
                    if (files.isDirectory()) {
    continue;
    } else if (files[i].isFile()) {
    br = new BufferedReader(new FileReader(files[i]));
    pw.println("BR is opening....");
    String line;
    while((line = br.readLine()) != null) {
    match = scPattern.matcher(line);
    if (match.find()) {
    pcv = line.substring(match.start(), match.end());
    System.out.println("Match: " + pcv + " Context: " + match.replaceFirst(pcv)); //This is working perfectly
    pw.println("Match: " + pcv + " Context: " + match.replaceFirst(pcv)); //This does not print anything at all
    System.out.println("Files: " + files[i]);
    System.out.println("");
    pw.println(" Files: " + files[i]);
    pw.println("");
    System.out.println("Closing I/O....");
    br.close();
    pw.close();
    public static void main(String[]args) throws Exception {
    File dir = new File("C:/");
    myNewClass acf = new myNewClass();
    acf.myClass(dir);

    @ejp
    I am afraid that it is not working. Can you please tell me what I doing wrong.
    void myMethod(File dir) throws Exception {
                bw = new BufferedWriter(new FileWriter("outputFile.txt"));
                File[] files = dir.listFiles();
                String[] fileList = dir.list();
                for (int i = 0;i < files.length; i++) {
                    if (files.isDirectory()) {
    myMethod(files[i]);
    } else if (files[i].isFile()) {
    br = new BufferedReader(new FileReader(files[i]));
    String line;
    while((line = br.readLine()) != null) {
    match = scPattern.matcher(line);
    if (match.find()) {
    pcv = line.substring(match.start(), match.end());
    System.out.println("Match: " + pcv + " Context: " + match.replaceFirst(pcv));
    bw.write("Match: " + pcv + " Context: " + match.replaceFirst(pcv));
    br.close();
    bw.write("Files: " + files[i]);
    bw.write("");
    bw.close();
    public static void main(String[]args) throws Exception {
    File dir = new File("C:/");
    myClass acf = new myClass();
    acf.myMethod(dir);

  • Issues with JDBC Connection Pooling

    Hi all,
    I'm experiencing some unexpected behaviour when trying to use JDBC Connection Pooling with my BC4J applications.
    The configuraiton is -
    Web Application using BC4J in local mode
    Using Default Connection Stagegy
    Stateless Release Mode
    Retrieving Application Modules using Configuration.createRootApplicationModule( am , cf );
    Returning Application Modules using Configuration.releaseRootApplicationModule( am, false );
    Three application modules
    AppModuleA - connects to DatabaseConnection1
    AppModuleB - connects to DatabaseConnection2
    AppModuleC - connects to DatabaseConnection2
    My requirement is to -
    Use App Module Pooling and have individual pool for each Application Module
    Use JDBC Pooling and have individual pool for each Database connection
    Note: All configuration was achieved in design mode (i.e. right clicking AppModule->Configurations...)
    1. Initial approach -
    In the configuration for each Application Module I specified the connection type as 'JDBC Datasource' and specified to approriate datasource.
    Tried setting doConnecitonPooling to 'true' as well as 'false'
    In the data-sources.xml I specified all the appropriate info including min-connections and max-connections.
    I would expect, with the above config that BC4J would use OC4J's built in JDBC connection pooling.
    2. Second approach -
    In the configuration for each Application Module I specified the connection type as JDBC URL.
    In the configuration I specified doConnectionPooling = 'true' as well as the max connection, max available and min available
    What I experienced in both cases was that the max connections seem to be ignored as the number of connection as reported by the database (v$session) was exceeded by more than 10.
    In addition to this once the load was removed the number of JDBC connecitons did not drop (I would have expected it to drop to max available connections)
    My questions are -
    1. When specifying to use a 'JDBC Datasource' style of connection, is it in fact OC4J that is then responsible for pooling JDBC connections? And in this case should BC4J's doConnectionPooling parameter be set to true or false?
    2. Are there any known issues with the use of the JDBC Conneciton Pool as stated by the above to approaches?

    Thanks for the additional info. Please see my comments. below.
    Sorry should have been more specififc -
    1. Is each application pool using a different JDBC user? You mentioned DatabaseConnection1 and DatabaseConnection2
    above; are these connections to different schemas / users? If so, BC4J will create a separate connection pool for each
    JDBC user. Each connection pool will have its own maximum pool size.
    Each 'DatabaseConnection' refers to a different database, actually hosted on a seperate physical server, different
    schema and different user.BC4J will maintain a separate connection pool for each permutation of JDBC URL / schema. If each user is connecting
    to a different DB instance then I would expect no greater than 10 DB sessions. However, if a DB instance is hosting
    more than user then I would expect greater than 10 DB sessions (though still no more than 10 DB sessions per user).
    2. Are all the v$session sessions related to the JDBC clients? There should be at least one additional database
    session which will be related to the session that is querying v$session.
    When querying the v$session table I specifically look for connections from the user in quesiton and from the machine
    name in question and in doing so eliminate the database system's connections, as well as the query tools'
    connection. One area I'm not sure about is the connection BC4J uses to write to its temporary tables. I am using
    Stateless release mode and have not explicetly stated to save to the database but I'm wondering if it still does if so
    and how does it come into the equation with max connections?BC4J's internal connections are also pooled and the limits apply as mentioned above. So, if you have specified
    internal connection info for a schema which is different than the users above I would expect the additional conns.
    One helpful diagnostic tool, albeit programmatic, might be to print the information about the connection pools after
    your test client(s) have finished. This may be accomplished as follows:
    // get a reference to the BC4J connection pool manager
    import oracle.jbo.server.ConnectionPoolManagerFactory;
    import oracle.jbo.server.ConnectionPoolManagerImpl;
    import oracle.jbo.pool.ResourcePool;
    import java.io.PrintWriter;
    import java.util.Enumeration;
    // get the ConnectionPoolManager. assume that it is an instance of the supplied manager
    ConnectionPoolManagerImpl mgr = (ConnectionPoolManagerImpl)ConnectionPoolManagerFactory.getConnectionPoolManager();
    Enumeration keys = mgr.getResourcePoolKeys();
    PrintWriter pw = new PrintWriter(System.out, true);
    while (keys.hasMoreElements())
    Object key = keys.nextElement();
    ResourcePool pool = (ResourcePool)mgr.getResourcePool(key);
    System.out.println("Dumping pool statistics for pool: " + key);
    pool.dumpPoolStatistics(pw);
    }

  • NetBeans problem: Issue with servlets and Chinese character encoding

    Java Version: JDK1.5.0_01, JRE1.5.0_01 (International version)
    Netbeans Version: Netbeans IDE 4.0
    OS: Windows XP Personal Edition
    Dear Sirs,
    First at all thanks for reading this post. I am having the following issue. I am creating an application using html pages and servlets. I am using Chinese and English languages on them (html encoding UTF-8).
    I created a project in Netbeans and added an idex.html screen reporting to a servlet. Both index.html and in the servlet generated html page contains the line:
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    Additional, I setup the character code settings in Netbeans:
    (tools-options-Java sources-Expert-default encoding=UTF-8
    When I run the project, index.html displays itself perfectly, with the Chinese characters displayed properly. The problem comes when the html created servlet is displayed, which instead of the Chinese characters some strange characters are displayed (�� instead of Chinese).
    I have tried different encodings from http://java.sun.com/j2se/1.4.2/docs/guide/intl/encoding.doc.html without any luck. I also setup the encoding of the file itself (using right click-properties in the project menu of Netbeans).
    Also, when I am editing the servlet, the characters are displayed properly. I type them directly without any issue, but then the display is wrong at runtime.
    Also, just in case this have something to do with the problem, my PC was bought in US, therefore the default character set is not Chinese. I had to install the Chinese typing stuff later on. But like I said earlier, the html page is displayed properly, so I really think is some problem with Netbeans.
    After a week trying to find a solution, I decided to post it here in the hopes that someone will show me the way of the light.
    Thanks in advance for any ideas or help provided
    Aral.

    Ok, I found out some problems with Netbeans as well.
        public void doGet(HttpServletRequest request,
                          HttpServletResponse response)
            throws IOException, ServletException
            response.setCharacterEncoding("UTF-8");
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            byte[] st = {-25,-75,-124,-27,-100,-106,-17,-68,-102,-27,-80,-113,-27,-72,-125,-26,-118,-75,-26,-105,-91,-27,-82,-93};
            out.println("this works: ");
            out.println(new String(st,"UTF-8"));
            out.println("<br>");
            out.println("this doesn't: ");
            out.println("some chinese copied from the Internet<br>");Right click the .java file and choose properties -> encoding UTF-8
    Then I make a copy of the .java file, rename it to html and open it with IE sure enough
    the Chinise is allready unreadable (not it's still readable in the IDE);
    When I compile the file with F9 I get the following error:
    whatever.java:101: warning: unmappable character for encoding Cp1252
    Tried to set the encoding to UNICODE but then the file doesn't compile.
    I gues you have to download the Japanese version for it to work correctly.

  • URGENT!!! Java Gurus Please Help with adf issue!

    PLEASE SEE MY LATEST POST BELOW TIMO'S RESPONSE. THE REQUIREMENT HAS CHANGED. THAT IS THE ISSUE I AM LOOKING A SOLUTION FOR.
    Hello All,
    We have a requirement where our adf/jsf app needs to pick an EXCEL file from the server where the application is deployed. The sequence is :
    User comes to the page
    Clicks on "Open EXCEL" button
    EXCEL file located in the c:/ of the server opens up.
    How can this be done? I do not see any coding needed because the EXCEL file is being opened as is (and after user views it he closes the file) and the data is not being transferred to the jspx page.
    *We are totally flexible in how this is implemented - ie, using button, link , html etc etc. What ever works!!!!*
    Thanks,
    Edited by: user12054715 on Aug 17, 2010 8:54 PM
    Edited by: user12054715 on Aug 18, 2010 4:11 PM
    Edited by: user12054715 on Aug 18, 2010 4:13 PM

    Hello Timo,
    I am using 10.1.3g so your response is not going to help me.
    However, I have another question that I have already posted on the Forum. Please help me...
    Requirement:
    *1. Java application should be able to write "Hello World" in the excel file, when the user opens it.*
    I CAN DO THIS WITH THE FOLLOWING CODE:
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("newSheet");
    HSSFRow row = sheet.createRow(1);
    row.createCell(1).setCellValue("HelloWorld!!!!!!!!!");
    *2. A "Write To Excel" button on jsf page opens a dialog asking user to Save or Open the excel file. (user can save the file anywhere on his machine)*
    I CAN DO THIS WITH THE FOLLOWING CODE:
    In jsf:
    <af:commandButton text="Download" action="#{myBackingBean.writeToExcel}" useWindow="true"/>
    In backing bean:
    public static void writeToExcel() throws IOException
    String filename = "workbook.xls";
    // //Setup the output
    String contentType = "application/vnd.ms-excel";
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse)fc.getExternalContext().getResponse();
    response.setHeader("Content-disposition", "attachment; filename=" + filename);
    response.setContentType(contentType);
    PrintWriter out = response.getWriter();
    BOTTLENECK: When the user opens the excel how do I show "HelloWorld!!!!!!!!!" ?

  • JAXP XSLT transformation UTF-8 issue

    Hi all,
    I have XML file generated from Java app. File is valid and is in UTF-8.
    I have XSLT template created with Altova StyleVision. Template is to produce RTF output file from above XML.
    I Java app there are two variant for XSLT transformation - with and without Saxon. I have simplified the code and it is almost the same in two variants.
    File outputFile = new File("path");
    *if (saxonToBeUsed) {*
    ClassLoader saxonClassLoader = SaxonLoader.getInstance(saxonPath);
    TransformerFactory transFact = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", saxonClassLoader); //$NON-NLS-1$
    Transformer trans = transFact.newTransformer(xsltSource);
    trans.setOutputProperty("encoding", "UTF-8"); //$NON-NLS-1$
    StreamResult res = new StreamResult(outputFile);
    trans.transform(xmlSource, res);
    *} else {*
    TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer trans = transFact.newTransformer(xsltSource);
    trans.setOutputProperty("encoding", "UTF-8"); //$NON-NLS-1$
    StreamResult res = new StreamResult(outputFile);
    *// Same result -> StreamResult res = new StreamResult(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"));*
    *// Same result -> StreamResult res = new StreamResult(new PrintWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")));*
    trans.transform(xmlSource, res);
    XML file contains Arabic or Chinese text. RTF is generated.
    When RTF and XML are opened with text editor or web browser Arabic/Chinese whatever text is readable.
    The issue is that when RTF is opened with MSWord/WordPad/Open Office Writer :
    - Saxon generation -> RTF file can be opened and Arabic/Chinese text is normal i.e readable. English language is readable too.
    - JAXP generation -> RTF file can be opened but Arabic/Chinese is scrabmbled, messed up. English language is readable.
    All three files (XML,XSLT,RTF) are in UTF-8
    I have installed Chinese and Arabic true type fonts. When I create manual MSWord doc i can write some of their symbols.
    Please suggest some solution.
    Thanks

    Hi jtahlborn,
    I found the difference between two RTFs. This is one table cell containing random Arabic text
    XSLT 1.0 generated:
    {\*\bkmkstart محمود_شمام_لرويترز:_القذافي_قتل_في_هجوم_للمجلس_الانتقالي}{\fs16 محمود شمام لرويترز: القذافي قتل في هجوم للمجلس الانتقالي}
    XLST2.0 generated:
    {\*\bkmkstart محمود_شمام_لرويترز:_القذافي_قتل_في_هجوم_للمجلس_الانتقالي} {\fs16\u1605?\u1581?\u1605?\u1608?\u1583?\u32?\u1588?\u1605?\u1575?\u1605?\u32?\u1604?\u1585?\u1608?\u1610?\u1578?\u1585?\u1586?\u58?\u32?\u1575?\u1604?\u1602?\u1584?\u1575?\u1601?\u1610?\u32?\u1602?\u1578?\u1604?\u32?\u1601?\u1610?\u32?\u1607?\u1580?\u1608?\u1605?\u32?\u1604?\u1604?\u1605?\u1580?\u1604?\u1587?\u32?\u1575?\u1604?\u1575?\u1606?\u1578?\u1602?\u1575?\u1604?\u1610?}
    But I don't know how to fix it. Both files are generated with Saxon, same Java code, only XSLTs are different.
    Any ideas ?

  • Netbeans Issue: Servlet do not display Chinese UTF-8 properly

    Netbeans Issue: Servlet do not display Chinese UTF-8 properly
    Java Version: JDK1.5.0_01, JRE1.5.0_01 (International version)
    Netbeans Version: Netbeans IDE 4.0
    OS: Windows XP Personal Edition
    Dear Sirs,
    First at all thanks for reading this post. I am having the following issue. I am creating an application using html pages and servlets. I am using Chinese and English languages on them (html encoding UTF-8).
    I created a project in Netbeans and added an idex.html screen reporting to a servlet. Both index.html and in the servlet generated html page contains the line:
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    Additional, I setup the character code settings in Netbeans:
    (tools-options-Java sources-Expert-default encoding=UTF-8
    When I run the project, index.html displays itself perfectly, with the Chinese characters displayed properly. The problem comes when the html created servlet is displayed, which instead of the Chinese characters some strange characters are displayed (�� instead of Chinese).
    I have tried different encodings from http://java.sun.com/j2se/1.4.2/docs/guide/intl/encoding.doc.html without any luck. I also setup the encoding of the file itself (using right click-properties in the project menu of Netbeans).
    Also, when I am editing the servlet, the characters are displayed properly. I type them directly without any issue, but then the display is wrong at runtime.
    Also, just in case this have something to do with the problem, my PC was bought in US, therefore the default character set is not Chinese. I had to install the Chinese typing stuff later on. But like I said earlier, the html page is displayed properly, so I really think is some problem with Netbeans.
    After a week trying to find a solution, I decided to post it here in the hopes that someone will show me the way of the light.
    Thanks in advance for any ideas or help provided
    Aral.

    Hi, thanks for your help. However I think the problem his more complex than it seems. Here is my doPost method (the important parts anyway):
    response.setCharacterEncoding("UTF-8"); //Not necessary because the next line should take care of it, but anyways...
    response.setContentType("text/html; charset=UTF-8; pageEncoding=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<meta http-equiv='Content-Language' content='en-us'>");
    out.println("<meta http-equiv='Content-Type' content='text/html; charset=utf-8; pageEncoding=utf-8'>"); //Again not necessary line, but anyways
    out.println("<title>Servlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("this is a test &#20320;&#22909; this is a test");
    out.println("</body>");
    out.println("</html>");
    out.close();
    This servlet is called from a html file. Also, when I load this in the browser, I right click on the screen and I can see that UTF-8 is setup allright. Doing some detective job I found that:
    - If the editor displays the characters perfectly and...
    - Other html pages (no servlets) in the same application can display chinese characters well and...
    - I have configured the encoding as UTF-8 in the servlet properties and in general properties and...
    - The file "web.xml" contains the encoding UTF-8 in its first line then...
    ...my only guess is that something goes wrong during the building of the project itself (ant?). Unfortunately I have no idea about configuring ant to that level, but I began to think that the problem may be there, during the compilation...
    Any ideas?
    Once more, thanks for any help or advice provided.
    Aral.

  • Encoding issue with Servets

    I am facing a strange issue to display non-english characters in a servlet. I have an helper class produces non-english characters as below
    public String getContent()
    String content = "કેન્દ્ર સરકારે ચૂંટણી નજીક આવતાં સામાન્ય જનતાને ";
    char[] newch = content.toCharArray();
      byte[] bytes = Charset.forName("UTF-8").encode(CharBuffer.wrap(newch)).array();
      String text1 = new String(bytes);
    System.out.println("Non-english content :"+text1);
    return text1;
    I can see non-english text on console when run standalone but when called from servlet it shows some garbage e.g.
    ArticleLocalProcessor localProcessor = new ArticleLocalProcessor();
      String jsonString = localProcessor.parseNeko();
      resp.setHeader("Content-Type", "text/plain; charset=ISO-8859-1");
      resp.setCharacterEncoding("ISO-8859-1");
      PrintWriter out = resp.getWriter();
    out.println(jsonString);
    Output: કેન્દ્ર સરકારે ચૂંટણી
    Any help

    So perhaps if your characters turn into garbage, you're using the wrong character set then.
    I think the only "problem" here is that you labelled this is strange, don't ever do that because it is a flight response. You need to fight - find the mistake you're making.

  • Issue while installing SP2 on CQ5.5

    Hi,
    I have been trying to upgrade CQ5 5.5 to Service Pack 2.
    Out of 10, the upgrade gets successful 7 times but it fails for the rest of the times.
    Script that I am using:
    #cq5-update-pkg-5.5.10.zip and cq5-service-pack-2.zip
            curl -u ${crx_site_user}:${crx_site_password} -F package=@$PACKAGE_DIR/cq5-update-pkg-5.5.10.zip http://${privateIP}:${cq5_author_listen_port}/crx/packmgr/service/.json/?cmd=upload
            curl -u ${crx_site_user}:${crx_site_password} -F package=@$PACKAGE_DIR/cq5-service-pack-2.zip http://${privateIP}:${cq5_author_listen_port}/crx/packmgr/service/.json/?cmd=upload
            curl -u ${crx_site_user}:${crx_site_password} -X POST http://${privateIP}:${cq5_author_listen_port}/crx/packmgr/service/.json/etc/packages/day/cq550/upd ate/cq-update-pkg-5.5.10.zip?cmd=install
            curl -u ${crx_site_user}:${crx_site_password} -X POST http://${privateIP}:${cq5_author_listen_port}/crx/packmgr/service/.json/etc/packages/day/cq550/upd ate/cq-service-pack-5.5.2.20121012.zip?cmd=install
    CQ5 Update Package gets installed but it gets failed while installation of cq5-service-pack-2.zip
    <html><head><title>
    500
    Internal Server Error
    </title></head><body><h1>
    Internal Server Error
    Internal Server Error
    </title></head><body><h1>
    Internal Server Error
    </h1>
    </body></html>
    This error corrupts my cq5 Author Package. Same behavior is observed for Publisher Package. Though, this issue is intermittent, but the after-effects leads to fresh installation of CQ5.
    Any help would be appreciated.

    Error Logs
    21.06.2013 06:06:45.494 *INFO* [152.144.62.112 [1371794797261] POST /crx/packmgr/service/.json/?cmd=upload HTTP/1.1] com.day.jcr.vault.packaging.impl.JcrPackageDefinitionImpl unwrapping package day/cq550/update:cq-service-pack:5.5.2.20121012
    21.06.2013 06:10:49.575 *ERROR* [152.144.62.112 [1371795049335] POST /crx/packmgr/service/.json/etc/packages/day/cq550/update/cq-service-pack-5.5.2.20121012.z ip HTTP/1.1] org.apache.sling.engine.impl.SlingRequestProcessorImpl service: Uncaught SlingException java.io.IOException: Unable to get component of class 'interface org.apache.sling.rewriter.Transformer' with type 'linkchecker'.
            at org.apache.sling.rewriter.impl.PipelineImpl.getPipelineComponent(PipelineImpl.java:160)
            at org.apache.sling.rewriter.impl.PipelineImpl.init(PipelineImpl.java:102)
            at org.apache.sling.rewriter.impl.ProcessorManagerImpl.getProcessor(ProcessorManagerImpl.jav a:445)
            at org.apache.sling.rewriter.impl.RewriterResponse.getProcessor(RewriterResponse.java:172)
            at org.apache.sling.rewriter.impl.RewriterResponse.getWriter(RewriterResponse.java:110)
            at org.apache.sling.servlets.post.HtmlResponse.doSend(HtmlResponse.java:113)
            at org.apache.sling.servlets.post.AbstractPostResponse.send(AbstractPostResponse.java:376)
            at org.apache.sling.servlets.post.impl.SlingPostServlet.doPost(SlingPostServlet.java:225)
            at org.apache.sling.api.servlets.SlingAllMethodsServlet.mayService(SlingAllMethodsServlet.ja va:148)
    21.06.2013 06:10:49.706 *ERROR* [152.144.62.112 [1371795049335] POST /crx/packmgr/service/.json/etc/packages/day/cq550/update/cq-service-pack-5.5.2.20121012.z ip HTTP/1.1] org.apache.sling.servlets.resolver.internal.SlingServletResolver Calling the error handler resulted in an error org.apache.sling.api.scripting.ScriptEvaluationException:
            at org.apache.sling.scripting.core.impl.DefaultSlingScript.call(DefaultSlingScript.java:385)
            at org.apache.sling.scripting.core.impl.DefaultSlingScript.eval(DefaultSlingScript.java:170)
            at org.apache.sling.scripting.core.impl.DefaultSlingScript.service(DefaultSlingScript.java:4 56)
            at org.apache.sling.servlets.resolver.internal.SlingServletResolver.handleError(SlingServlet Resolver.java:764)
    Caused by: org.apache.sling.api.SlingException: Unable to setup processor: Unable to get component of class 'interface org.apache.sling.rewriter.Transformer' with type 'linkchecker'.
            at org.apache.sling.rewriter.impl.ProcessorManagerImpl.getProcessor(ProcessorManagerImpl.jav a:452)
            at org.apache.sling.rewriter.impl.RewriterResponse.getProcessor(RewriterResponse.java:172)
            at org.apache.sling.rewriter.impl.RewriterResponse.getWriter(RewriterResponse.java:110)
            at org.apache.sling.scripting.core.impl.helper.OnDemandWriter.getWriter(OnDemandWriter.java: 38)
            at org.apache.sling.scripting.core.impl.helper.OnDemandWriter.write(OnDemandWriter.java:61)
            at java.io.PrintWriter.write(PrintWriter.java:382)
            at org.apache.sling.scripting.jsp.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.jav a:119)
            at org.apache.sling.scripting.jsp.jasper.runtime.PageContextImpl.release(PageContextImpl.jav a:191)
            at org.apache.sling.scripting.jsp.jasper.runtime.JspFactoryImpl.internalReleasePageContext(J spFactoryImpl.java:99)
            at org.apache.sling.scripting.jsp.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactor yImpl.java:71)
            at org.apache.sling.scripting.jsp.jasper.compiler.JspRuntimeContext$JspFactoryHandler.releas ePageContext(JspRuntimeContext.java:120)
            at org.apache.jsp.libs.sling.servlet.errorhandler.default_jsp._jspService(default_jsp.java:3 20)
            at org.apache.sling.scripting.jsp.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
            at org.apache.sling.scripting.jsp.jasper.servlet.JspServletWrapper.service(JspServletWrapper .java:420)
            ... 52 more
    Caused by: java.io.IOException: Unable to get component of class 'interface org.apache.sling.rewriter.Transformer' with type 'linkchecker'.

  • Issue with using sockets

    Please help me, im having problems with the java socket it class, i seem to be gettting I/O problems...ibe created a simple chat problem, with a client application and server application..very basic, the client needs to enter a port number and ip number before proceeding....if i set up the server on say port 4444 then connect to it via the server using localhost and port 4444, theres no problems wotsoeva. The problem occurs when i try it over the internet with a friend. Im sure ive got the correct ip address in every instance. In some cases it will work, depending on who im testing the application on. Is this a firewall issue that im having? How do i get round it? Any advice would be welcomed as im working on a project which is reliant on this fundamental design working. Thanks

    Ok this is the basic try catch in the client:-
    try
    socket = new Socket(InetAddress.getByName(ip), 30001);
    out = new PrintWriter(socket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    sl = new SocketListener(in, serverText);
    Thread t = new Thread(sl);
    t.start();
    out.println("**SERVER NOTICE** - "+name + " has joined.");
    catch (UnknownHostException e)
    System.out.println("Unknown host: " + ip);
    System.exit(1);
    catch (IOException e)
    System.out.println("No I/O");
    System.exit(1);
    The error i get is the IOException. Im 100% the host ip is correct, and ive sent the server to them which is definately running correctly. Im running this from my machine at home, which uses a software firewall Kerio...ive just tried running the application on my home network, this also gives the same problem.

  • JFileChooser issue - open at the back of the browser

    Hello All,
    I have a strange issue using JFileChooser. I have implemented a WebApplication with a browse option to a folder(not files). For this JFileChooser has been used. Strangely when I click on "Browse" button, the controller calls the JAVA class, and the dialog opens behind the browser (only for the first time). and next time onwards it opens on the browser only. Here is the code i have written:
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.List;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.awt.Container;
    import java.awt.Point;
    import java.awt.Frame;
    import java.io.File;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.UIManager;
    import org.json.JSONException;
    //few more imports for SynchronizeService, and for JSON
    public class FolderChooser1 extends SynchronizeService {
         private String selectedFolder = "";
         static final String RETURN_TYPE = "text/json";
         private PrintWriter out;
         private HttpServletRequest request;
         private MessageJSON folderNameJSON;
         int folderCounter = 0;
         String saveSelectedFolder = "";
                    static String selectedDirectory = "";
    @Override
         public List service(Connection conn) throws IOException {
              HttpServletResponse response = null;
              List<Object> list = null;
              try {
                        super.service(conn);
                        list = serviceClientInput(conn);
                        request = conn.getRequest();
                        response = conn.getResponse();
                        response.setContentType(RETURN_TYPE);
                        out = response.getWriter();
                        folderCounter = Integer.parseInt(request.getParameter("folderCounter"));
                        if(request.getParameter("saveSelectedFolder")!=null)
                             saveSelectedFolder = request.getParameter("saveSelectedFolder");
                        System.out.println("**** Save selected folder:"+saveSelectedFolder);
                        if (folderCounter > 0)
                             System.out.println("**** Folder Count:"+folderCounter);
                             //dialog(new JFrame(), "Browse For Folder", new File("/"+saveSelectedFolder));
                             dialog(new JFrame(),"Browse For Folder");
                        else
                             System.out.println("** In else");                         
                             //dialog(new JFrame(), "Browse For Folder", new File(System.getProperty("user.home")+ "/Desktop"));
                             dialog(new JFrame(),"Browse For Folder");
                        if (selectedDirectory != "") {
                        folderNameJSON = new MessageJSON();
                        folderNameJSON.setMessage(selectedDirectory);
                        out.write(folderNameJSON.toJSONString());
                   } catch (JSONException je) {
                        System.out.println("****");
                        je.printStackTrace();
                   } catch (Exception e) {
                        System.out.println("*********");
                        e.printStackTrace();
              return list;
                    public static void dialog(Container frame, String title) {
              while (!(frame instanceof Frame)) {
                   frame = frame.getParent();               
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch (Exception exception) {
                   exception.printStackTrace();
              JFileChooser dirChooser = new JFileChooser();
              dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              if (selectedDirectory!=null | selectedDirectory==""){
                   dirChooser.setCurrentDirectory(new File(selectedDirectory));
              dirChooser.setDialogType(JFileChooser.OPEN_DIALOG);
              dirChooser.setDialogTitle(title);
              dirChooser.setMultiSelectionEnabled(false);
              dirChooser.setAcceptAllFileFilterUsed(false);
              dirChooser.setEnabled(true);
              dirChooser.setVisible(true);
              // Display the folder chooser dialog:
              int returnVal = dirChooser.showDialog(frame, "SELECT");
              // If a folder was chosen:
              if (returnVal == JFileChooser.APPROVE_OPTION) {
                   System.out.println("Is selected a directory:"+dirChooser.getSelectedFile().isDirectory());
                   selectedDirectory = dirChooser.getSelectedFile().getAbsolutePath();
                   //selectedDirectory = dirChooser.getCurrentDirectory().getAbsolutePath();               
                   System.out.println("**** selected Directory:"+selectedDirectory);
              }else if (returnVal == JFileChooser.CANCEL_OPTION) {               
                   selectedDirectory = selectedDirectory;
    }So please let me know where it is going wrong.
    Thank you.

    showDialog(frame) didnot work for me.
    Sorry, I have to resolve it as earlier as possible, hence I took all the possible ways to find a solution and posted the query in other forums also.
    Kindly help.

  • JCA Issue with migration from EP 6.0 SP2 to SAP NW2004s (EP 7.00 SP7)

    We are currently using JCA on EP 6.0 SP2 platform to connect to SAP R/3 backend system for custom java iviews as shown below ...
    Context ctx = null;
    IConnectionFactory connectionFactory = null;
    IConnection client = null;
    IConnection aConnection = null;
    try
         //Obtain the initial JNDI context
         ctx = new InitialContext();
         //Perform JNDI lookup to obtain connection factory
         connectionFactory = (IConnectionFactory) ctx.lookup("EISConnections/SAPFactory");
         connectionFactory.setConnectionTimeOut( 900 );          
         IConnectionSpec spec = connectionFactory.getConnectionSpec();
         // FOR MiniP     
         ((Map) spec).put("client", "100");
         ((Map) spec).put("UserName", "USER_ID");
         ((Map) spec).put("Password", "password");
         ((Map) spec).put("logonmethod", "UIDPW");
         ((Map) spec).put("Language", "EN");
         ((Map) spec).put("ashost", "10.14.17.44");
         ((Map) spec).put("sysnr", "02");                              
         aConnection = connectionFactory.getConnectionEx(spec);
    catch (Throwable th)
         StringWriter sw = new StringWriter();
         th.printStackTrace( new PrintWriter( sw ) );
         log("Caught an exception (Throwable) : \n" + sw.toString() );                 
    When we migrated the code, the connection to SAP R/3 system is failing. Searching servicemarketplace for some solution, we found a note 820857 and made the necessary code change for JNDI lookup from "EISConnections/SAPFactory" to "deployedAdapters/SAPFactory/shareable/SAPFactory" but we are still getting the following connection failure errors ...
    (R3/BW) Failed to get connection. Please contact your admin.
    com.sapportals.connector.connection.ConnectionFailedException: Connection Failed: Nested Exception. Failed to get connection. Please contact your admin.
         at com.sapportals.connectors.SAPCFConnector.SAPConnectorException.getNewConnectionFailedException(SAPConnectorException.java:107)
    Also, the help link is not updated for any changes ...
    http://help.sap.com/saphelp_nw04s/helpdata/en/89/8a185c148e4f6582560a8d809210b4/content.htm
    I really appreciate any help being provided for solving the issue.

    Hello! Bhabesh,
    Could you please check your stack against mine, i am pasting that stack here.
    Please let me know if you are getting the same error or something else.
    FYI, i am pasting my code too. Please check if you are using the same way.
    Stack
    #1.5#00306EE9EE3A001A0000064F00003A28000422D070FB68FD#1164178553286#com.sap.portal.iView#sap.com/irj#com.sap.portal.iView#z10002722#42##asap86.symbol.com_NPQ_6376950#Guest#d2b1aed079f511db93d200306ee9ee3a#SAPEngine_Application_Thread[impl:3]_21##0#0#Error#1#/System/Server#Java###Connection Failed: Nested Exception. Failed to get connection. Please contact your admin. 
    [EXCEPTION]
    #1#com.sapportals.connector.connection.ConnectionFailedException: Connection Failed: Nested Exception. Failed to get connection. Please contact your admin.
         at com.sapportals.connectors.SAPCFConnector.SAPConnectorException.getNewConnectionFailedException(SAPConnectorException.java:137)
         at com.sapportals.connectors.SAPCFConnector.connection.SAPCFConnectorConnectionFactory.getConnectionEx(SAPCFConnectorConnectionFactory.java:184)
         at com.symbol.intr.cs.authcheck.beans.AuthorizationChecker.getConnection(AuthorizationChecker.java:182)
         at com.symbol.intr.cs.authcheck.beans.AuthorizationChecker.connectionOK(AuthorizationChecker.java:79)
         at com.symbol.intr.cs.authcheck.beans.AuthorizationChecker.isAuthorizedRunCheck(AuthorizationChecker.java:294)
         at com.symbol.intr.cs.authcheck.beans.AuthorizationChecker.isAuthorized(AuthorizationChecker.java:289)
         at com.symbol.intr.cs.authcheck.main.Controller$MyController.onCheckAuthorizations(Controller.java:68)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at com.sapportals.htmlb.page.DynPage.doProcessCurrentEvent(DynPage.java:172)
         at com.sapportals.htmlb.page.PageProcessor.handleRequest(PageProcessor.java:115)
         at com.sapportals.portal.htmlb.page.PageProcessorComponent.doContent(PageProcessorComponent.java:134)
         at com.sapportals.portal.prt.component.AbstractPortalComponent.serviceDeprecated(AbstractPortalComponent.java:209)
         at com.sapportals.portal.prt.component.AbstractPortalComponent.service(AbstractPortalComponent.java:114)
         at com.sapportals.portal.prt.core.PortalRequestManager.callPortalComponent(PortalRequestManager.java:328)
         at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:136)
         at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:189)
         at com.sapportals.portal.prt.component.PortalComponentResponse.include(PortalComponentResponse.java:215)
         at com.sapportals.portal.prt.pom.PortalNode.service(PortalNode.java:646)
         at com.sapportals.portal.prt.core.PortalRequestManager.callPortalComponent(PortalRequestManager.java:328)
         at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:136)
         at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:189)
         at com.sapportals.portal.prt.core.PortalRequestManager.runRequestCycle(PortalRequestManager.java:753)
         at com.sapportals.portal.prt.connection.ServletConnection.handleRequest(ServletConnection.java:240)
         at com.sapportals.portal.prt.dispatcher.Dispatcher$doService.run(Dispatcher.java:545)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sapportals.portal.prt.dispatcher.Dispatcher.service(Dispatcher.java:405)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.sap.engine.services.servlets_jsp.server.servlet.InvokerServlet.service(InvokerServlet.java:156)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.runServlet(HttpHandlerImpl.java:390)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.handleRequest(HttpHandlerImpl.java:264)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:347)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:325)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.invokeWebContainer(RequestAnalizer.java:887)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.handle(RequestAnalizer.java:241)
         at com.sap.engine.services.httpserver.server.Client.handle(Client.java:92)
         at com.sap.engine.services.httpserver.server.Processor.request(Processor.java:148)
         at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:33)
         at com.sap.engine.core.cluster.impl6.session.MessageRunner.run(MessageRunner.java:41)
         at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:100)
         at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:170)
    Code
         protected IConnection getConnection(StringBuffer sb)
              throws Exception {
              Hashtable env = null;
              Context initctx = new com.sapportals.portal.prt.jndisupport.InitialContext(env);
              IConnectionSpec spec = connectionFactory.getConnectionSpec();
              spec.setPropertyValue("client", "095");
              spec.setPropertyValue("user", "Z10002722");//CPICR3Q095 - Chandu's ID: Z10002434
              spec.setPropertyValue("passwd", "initpass");
              spec.setPropertyValue("lang", "EN");
              spec.setPropertyValue("ashost", "157.235.1.24");//157.235.1.24 asap84.symbol.com
              spec.setPropertyValue("sysnr", "02");
              IConnection connection = null;
              try {
                   connection = connectionFactory.getConnectionEx(spec);
              } catch (Exception e1) {
                   StringBuffer exceptionMessage = new StringBuffer();
                   exceptionMessage.append("<font color='red'>");
                   exceptionMessage.append(
                        "<br>A connection to SAP could not be achieved.  ");
                   exceptionMessage.append(
                        "The possible cause is a bad definition of the connection ");
                   exceptionMessage.append(
                        "as loaded from the connection_specs.properties file.  ");
                   exceptionMessage.append("Please check this file.  ");
                   exceptionMessage.append("Check the user ID shown above and the password.  ");
                   exceptionMessage.append("Also, check the host and system number as shown above.");
                   exceptionMessage.append("</font>");
                   ILogger logger =
                        PortalRuntime.getLogger(IPortalConstants.IVIEW_LOGGER);
                   logger.log(e1, e1.getMessage(), Level.SEVERE);
    //               throw new ConnectionFailedException(exceptionMessage.toString());
                   throw new Exception(exceptionMessage.toString());
              return connection;
    Thanks!
    Regards,
    Kishore

  • Issue using Runtime.exec() in Vista

    I've coded a simple method using Runtime.exec() to get the client MAC ID , and it worked alright on XP. Now my client want to switch to vista , and the method is not working. Here's my code
    import java.io.*;
    import java.util.regex.*;
    public class GetMac
         public static String getMacAddress()
              String mac="";
              System.out.println("getMacAddress");
              try {
                   RunTimeExecutor re=new RunTimeExecutor("ipconfig /all");
                    mac=re.executeAndReturnMac();
                    re.destroy();
              } catch (Exception e) {
                   e.printStackTrace();
              return mac;
    import java.io.IOException;
    import java.io.InputStream;
    * @author amal
    public class RunTimeExecutor
              String cmd;
              Process proc;
               * @param cmd
              public RunTimeExecutor(String cmd)
                        this.cmd=cmd;
               * @return boolean
               * @throws WIException
              public  String executeAndReturnMac() throws Exception
                   System.out.println("run");
                   String mac="";
                        if(cmd==null)
                                  throw new Exception("No Commands");
                        try
                              final Runtime rt = Runtime.getRuntime();
                              proc = rt.exec(cmd);
                              final StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream());
                              InputStream iis=proc.getInputStream();
                              final StreamGobbler outputGobbler = new StreamGobbler(iis);
                              errorGobbler.start();
                              outputGobbler.start();
                              int exit=proc.waitFor();
                              System.out.println("exitVAl "+exit);
                              if(exit==0)
                                   mac=outputGobbler.MAC;
                              return (exit==0) ? mac :null;
                    catch (IOException e)
                              e.printStackTrace();
                    catch (InterruptedException e)
                              e.printStackTrace();
                    catch(Exception e)
                         e.printStackTrace();
                    return null;
              public void destroy()
                        if(proc!=null )
                                  proc.destroy();
    * @author amal
    import java.io.*;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    * @author amal
    public class StreamGobbler extends Thread
        InputStream is;
        OutputStream os;
        public String MAC;
        StreamGobbler(InputStream is)
            this(is,null);
        StreamGobbler(InputStream is,OutputStream redirectTo)
            this.is = is;
            this.os = redirectTo;
         * @see java.lang.Thread#run()
        public void run()
            try
                PrintWriter pw = null;
                if (os != null)
                    pw = new PrintWriter(os);
                InputStreamReader isr = new InputStreamReader(is);
                int c=0;
                BufferedReader br = new BufferedReader(isr);
                String line=null;
    System.out.println("Start Reading");
                     while ( (line = br.readLine()) != null)
                          System.out.println(line);
                         if (pw != null)
                             pw.println(line);
                         Pattern p = Pattern.compile(".*Physical Address.*: (.*)");
                            Matcher m = p.matcher(line);
                            if (m.matches())
                                 MAC = m.group(1);
                                 System.out.println("seting MAC to "+MAC);
                                 break;
                if (pw != null)
                    pw.flush();
            } catch (Exception e)
                e.printStackTrace(); 
    }The inputStream of the process doesnt get printed at all , the loop condition in StreamGobbler 'while ( (line = br.readLine()) != null)
    ' is never true.
    Also , in random cases i've seen the System.out.println("exitVAl "+exit); line executing before the System.out.println("Start Reading"); line , and i though proc.waitFor() would guarentee otherwise.

    thx guys for ur replies . The issue was because of some browser security system ( or so they said . ).However i'm still puzzled about the 'waiting for the stream to finish' part .
    paul.miner wrote:
    {I think the process is allowed to end with output still in the >>buffers, ..so this would be expected. You should be waiting for >>your .streams to finish, since that's what you really >>care .about. .Also, .you need to add synchronization between your >>threads so you can accurately retrieve "MAC". Also, do not break out >>of the loop when you find what you're looking for, you should >>continue .reading until the end of the stream.Wasn't I suppose to be reading out of the stream to prevent an overflow?Also the break is done there are multiple lines like 'Physical address .....: xxxxxxxxxx ' in the output , and the macid is the first one.About the ProcessBuilder , I'll look into it . Thx for your advice.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Multi-Thread logging with PrintWriter

    Hi,
    I'm trying to buffer up some log information and flush it out to a log file at the end of servlet.
    If I do something like following in a servlet where multiple threaded are doing the same thing, would System.out be a bottleneck? I can see that sometimes, some flush() might get called prematuarely, but I guess that is ok.. any issues with following approach in a servlet?
    Thanks
    PrintWriter pw = new PrintWriter( System.out );
    pw.print( "some info" );
    pw.print( "more info" );
    pw.print( "more info" );
    pw.flush();

    If you are writing to a log file...why not use a Logger class.
    the latest java JDK come with a Logger class. I prefer log4j (apache.jakarta site). The logger can display the thread name, time, what method is being invoked.
    Otherwise, just use a StringBuffer and append the System.out until you are ready to print. then create the printer there and print. IO is expensive.

  • .substring issues

    hi, i am learning java in class for school, and in my project i have one issue with the .substring method of strings.
    my code is
    import java.util.Scanner;
    public class Valid
         private String lastName;
         private String email;
         private boolean oneSymbol;
         private boolean nonBlankLeft;
         private boolean onePeriod;
         private boolean nonBlankBoth;
         Valid()
         public void readData(Scanner input)
              lastName = input.next();
              email = input.next();
         public void checkSymbol()
              String s = email.substring(0);
              int count = 0;
              int x;
              x = s.indexOf('@');
              while (!(x == -1))
                   s = s.substring(0,x) = s.substring(x+1);
                   count++;
                   x = s.indexOf('@');
              if (count == 1)
                   oneSymbol = true;
              else
                   oneSymbol = false;
         public void checkNonBlankLeft()
              int x = email.indexOf(" @");
              if (x == -1)
                   nonBlankLeft = true;
              else
                   nonBlankLeft = false;
         public void checkOnePeriod()
              String s = email.substring(0);
              int count = 0;
              int x;
              x = s.indexOf('.');
              while (!(x == -1))
                   s = s.substring(0,x) = s.substring(x+1);
                   count++;
                   x = s.indexOf('.');
              if (count >= 1)
                   onePeriod = true;
              else
                   onePeriod = false;
         public void checkNonBlank()
              int x = email.indexOf(" . ");
              if (x == -1)
                   nonBlankBoth = true;
              else
                   nonBlankBoth = false;
         public void writeResults(java.io.PrintWriter outputValid, java.io.PrintWriter outputInvalid)
              if (oneSymbol && nonBlankLeft && onePeriod && nonBlankBoth)
                   outputValid.printf("%-15s%-30s", lastName, email + "\n");
              else
                   outputInvalid.printf("%-15s%-30s", lastName, email + "\n");
                   if (oneSymbol == false)
                        outputInvalid.printf("%45s%-30s", " ", "@ symbol must occur once\n");
                   if (nonBlankLeft == false)
                        outputInvalid.printf("%45s%-30s", " ", "Must be a character before the @ symbol\n");
                   if (onePeriod == false)
                        outputInvalid.printf("%45s%-30s", " ", "Must contain one . (period)\n");
                   if (nonBlankBoth == false)
                        outputInvalid.printf("%45s%-30s", " ", "Both sides of . must be contain a character\n");
    } i have issues with both .substring methods and i get these errors.
    .\Valid.java:31: unexpected type
    required: variable
    found : value
    s = s.substring(0,x) = s.substring(x+1);
    ^
    .\Valid.java:58: unexpected type
    required: variable
    found : value
    s = s.substring(0,x) = s.substring(x+1);
    ^
    2 errors

    georgemc wrote:
    boulbrokdrm wrote:
    thank you, you just showed me that i am a complete idiot lol
    i ment to use + instead of =, just forgot to press the shift key i guess, but it should work now, thank youLol, easiest 10 dukes I ever made.If you made them why are they still just sitting there waiting to be awarded?
    Hint, hint - OP, YOU NEED TO AWARD THEM

Maybe you are looking for

  • Websense URL Filtering is not working in transparent proxy mode

    The "sh ip wccp web-cach detail" show that the redirection to CE cluster (5 of them)is working but the url filtering doesnt work at all. The Websense server is on the same VLAN as all the 5 CE. This thing happened when we reconfigured the wccp router

  • Quick strange beginners design question

    I have a non-crystal report whose format I need to duplicate EXACTLY or all heck will break loose. It contains a simple group with some detail records. I need the count of the detail records on the first line of the details as follows: GH1:         

  • Re:Profit center as mandatory for VA01

    Hi Experts, Good Morning, my issue is if i didnt give profit center in va01 the document should not be saved, so in OMS9 which field sel.group (eg:name-0001,0002.....) i need to go and maintain as "Reqd Entry" Thanks in advance & points will be assig

  • Can't use it

    I've installed and deleted and re-installed the latest version of Adobe Flash several times.  I've tried it on Firefox and IE it's not working for either one.  I've made sure it was enabled on both.  I've even uninstalled my Adobe pro (now I can't ge

  • Kreditkarte geht nicht

    Hallo Zusammen, Ich wollte soeben im Store ein Spiel kaufen. Jedoch wurde der Vorgang abgebrochen. Wenn ich versuche direkt Geld von der Kreditkarte aufzuladen (aufs PSN Konto) bekomme ich die Meldung das die Karte ungültig ist. Dies kann jedoch nich