Alex_

I found out the problem! It is a bug in JSF 2.0. The whole problem is in a commented line... [B][/B] Without it everything works like a charm!
[CODE]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"

<ui:composition>
    <h:form>
            <h:commandLink  actionListener="#{nav.setSelected('Books')}" 
                styleClass="#{nav.getCSSStyle('Books')}">
            <!--    <f:actionListener binding="#{books.}"/> -->
            Books
            </h:commandLink> 
    <br/>
            <h:commandLink actionListener="#{nav.setSelected('Electronics')}" 
            styleClass="#{nav.getCSSStyle('Electronics')}">Electronics</h:commandLink>
    <br/>   
            <h:commandLink actionListener="#{nav.setSelected('Tools')}" 
            styleClass="#{nav.getCSSStyle('Tools')}">Tools</h:commandLink>
    </h:form>
</ui:composition>

</h:body>

[/CODE]

Alex_ Junior Poster

The project (JSF 2.0.6!) executes fine, some pages load with no problem, others don't.
This is the full stack trace. If there is any code needed, ask for.

org.apache.el.parser.ParseException: Encountered " "}" "} "" at line 1, column 9.
Was expecting:

... at org.apache.el.parser.ELParser.generateParseException(ELParser.java:2215) at org.apache.el.parser.ELParser.jj_consume_token(ELParser.java:2097) at org.apache.el.parser.ELParser.DotSuffix(ELParser.java:1064) at org.apache.el.parser.ELParser.ValueSuffix(ELParser.java:1033) at org.apache.el.parser.ELParser.Value(ELParser.java:978) at org.apache.el.parser.ELParser.Unary(ELParser.java:948) at org.apache.el.parser.ELParser.Multiplication(ELParser.java:712) at org.apache.el.parser.ELParser.Math(ELParser.java:632) at org.apache.el.parser.ELParser.Compare(ELParser.java:444) at org.apache.el.parser.ELParser.Equality(ELParser.java:338) at org.apache.el.parser.ELParser.And(ELParser.java:282) at org.apache.el.parser.ELParser.Or(ELParser.java:226) at org.apache.el.parser.ELParser.Choice(ELParser.java:183) at org.apache.el.parser.ELParser.Expression(ELParser.java:175) at org.apache.el.parser.ELParser.DeferredExpression(ELParser.java:113) at org.apache.el.parser.ELParser.CompositeExpression(ELParser.java:41) at org.apache.el.lang.ExpressionBuilder.createNodeInternal(ExpressionBuilder.java:116) at org.apache.el.lang.ExpressionBuilder.build(ExpressionBuilder.java:172) at org.apache.el.lang.ExpressionBuilder.createValueExpression(ExpressionBuilder.java:217) at org.apache.el.ExpressionFactoryImpl.createValueExpression(ExpressionFactoryImpl.java:67) at com.sun.faces.facelets.el.ELText$ELTextVariable.apply(ELText.java:201) at com.sun.faces.facelets.el.ELText$ELTextComposite.apply(ELText.java:182) at com.sun.faces.facelets.compiler.CommentInstruction.apply(CommentInstruction.java:81) at com.sun.faces.facelets.compiler.UIInstructionHandler.apply(UIInstructionHandler.java:141) at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137) at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:184) at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120) at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:98) at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137) at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:184) at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120) at com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:166) at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93) at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:86) at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:308) at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:367) at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:346) at com.sun.faces.facelets.impl.DefaultFaceletContext.includeFacelet(DefaultFaceletContext.java:199) at com.sun.faces.facelets.tag.ui.IncludeHandler.apply(IncludeHandler.java:120) at com.sun.faces.facelets.tag.ui.InsertHandler.apply(InsertHandler.java:113) at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:98) at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137) at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:184) at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120) at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:98) at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93) at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:98) at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:86) at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:308) at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:367) at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:346) at com.sun.faces.facelets.impl.DefaultFaceletContext.includeFacelet(DefaultFaceletContext.java:199) at com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:155) at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93) at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:86) at com.sun.faces.facelets.impl.DefaultFacelet.apply(DefaultFacelet.java:152) at com.sun.faces.application.view.FaceletViewHandlingStrategy.buildView(FaceletViewHandlingStrategy.java:769) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:100) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:306) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:550) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:380) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:288) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662)

Alex_

Oh...
Validate initialize project by Peter
Name is T-E-S-T
Name is required.
Name is required.

Validate initialize project
Name is T-E-S-T
Name is required.
Exception in thread "main" java.lang.NullPointerException
at NullObjectTest.validate(NullObjectTest.java:22)
at NullObjectTest.main(NullObjectTest.java:15)
Shame on me. So it's the || operator that doesn't verify its second parameter ?

Ok, but the problem still persists because it's the string returned that is null. So why didn't struts initialised it? It initialised the second parameter, why not the first?

Alex_

Hehe. :) Wrong. The && operator doesn't verify it's right value if it's left is false. It's no sense: the scope is to have two logic "trues", so why bother checking the second if the first is already known to be false.
My code now is:[code=java]
if (project != null) {
String str = project.getName();
if (str.length() == 0)
addFieldError("project.name", "Name is required.");
}
[/code] and it gives me the error on line [B]if (str.length() == 0)[/B]. So, it's the String that is null here.
This changes my question: Why didn't struts initialized the name field? I do have a I Organization.setName(String name)[/I] method and i have inserted a name in my form. Any ideas?
This is my form
[code=jsp]



</s:form>[/code]
My CreateProjectAction.properties
[code]project.name=Projects name
project.users=Multiple Users
project.president.name=Presidents name
project.id=DB ID[/code]
Btw, the project.president.name key has been initialized. Odd.
PS: i have changed my Organization a bit: Organization.name="No name yet". This was done so that i can get pass the NullExceptionError.

Alex_

Yes, i'm sure. I want to check if it's null, if it isn't then proceed getting the object's name and compare it's length with 0.
The problem is that it passes the null verification (meaning that the reference has a concrete object), but when i want to call a method, it says "Hey, null.getName() is never possible!"... as far as i understand
[url]http://download.oracle.com/javase/1.4.2/docs/api/java/lang/NullPointerException.html[/url]

Alex_ Junior Poster

How can this be...
Another odd thing is that the error appears on the page but no trace in console
This is my code
[code=java]
package actions;

import com.opensymphony.xwork2.ActionSupport;

import logic.*;
import logic.organizations.Project;
public class CreateProjectAction extends ActionSupport{
private Project project =null;
private String message = "NULL";
public void setProject(Project pr){
this.project = pr;
}

public String execute(){

// if (project !=null && project.getName().length()==0){
// message = "Execute: "+project.toString();
// }
message = "Execute";
return SUCCESS;
}
public String dummy(){
return null;
}
public void validate(){
if(project !=null && project.getName().length()==0){
addFieldError( "project.name", "Name is required." );
}
message = "Validate";
}

public void setMessage(String message) {
    this.message = message;
}

public String getMessage() {
    return message;
}

}
[/code]
error code

Struts Problem Report

Struts has detected an unhandled exception:
Messages:
File: actions/CreateProjectAction.java
Line number: 26
Stacktraces
java.lang.NullPointerException

actions.CreateProjectAction.validate(CreateProjectAction.java:26)
com.opensymphony.xwork2.validator.ValidationInterceptor.doBeforeInvocation(ValidationInterceptor.java:249)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:261)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:142)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:166)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:190)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:244)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:541)
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:383)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:288)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
java.lang.Thread.run(Thread.java:636)

Alex_

Thanks for replying. I just wanted to say that i'm busy now and that i solved my problem, but in a less elegant way.So I'll get back to this thread later.

Alex_ Junior Poster

Hello. I am trying to make a thread pool for a server that will process incoming socket connections. The purpose is to have limited available connections at a time.
I can't grasp this concept fully to implement it. Perhaps some of you can help me! Please try.

Below is my current thread "launcher"
[CODE=java]while (listening){
System.out.println("Listening...");
new MyServerThread(serverSocket.accept()).start();
}[/CODE]
But i don't understand how to do it through a fixedThreadPool.

[B]My speculations[/B]
As far as i understand, though, is that i need to satisfy the following steps: (Correct me if i'm wrong!)

  • Design a ThreadFactory that will create my threads.
  • Make a pool of desired maxNr of threads; associate my ThreadFactory to it.
  • On an incoming connection: invoke any thread, sending to it the client's socket connection. (after the thread will finish it will wipe client's socket connection)
    But the problem here is that i can't find a way to send the client's socket to the thread.

[I]Possbile solution[/I]
I could instantiate all the threads beforehand, then launch them all to race for the first client. But that would mean that i have to constantly launch the ones that have just finished, thus currentRunningThreads=maxNrOfThreads, always. Totally not elegant.

Alex_

Thank you. I separated the classes and the serialization works.

Alex_

I don't see why, but i added one anyway... and corrected some logic bugs, but the error is the same.
This is my source code now:
[code=java]/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */

package ppc2;

import java.io.Serializable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Main {

Main(){

    SerializedThread [] threads = new SerializedThread[7];
    for(int i =1; i < 8; i++) {
        switch (i) {
            case 1:
                threads[i - 1] = new SerializedThread(new String[]{"f2", "f3", "f4"});
                break;
            case 2:
                threads[i - 1] = new SerializedThread(new String[]{"f5"});
                break;
            case 3:
                threads[i - 1] = new SerializedThread(new String[]{"f6"});
                break;
            case 4:
                threads[i - 1] = new SerializedThread(new String[]{"f7"});
                break;
            default:
                threads[i - 1] = new SerializedThread(null);
        }
    }
    for(int i =0;i<7;i++){
        writeMyObjectToFile(threads[i],"f"+(i+1));
    }
    readMyObjectFromFile("f1");
}

private void writeMyObjectToFile(SerializedThread runner, String fileName){
    FileOutputStream fos = null;
    ObjectOutputStream oos = null;
    try{
        fos = new FileOutputStream(fileName);
        oos = new ObjectOutputStream(fos);
        oos.writeObject(runner);
        oos.close();
    }catch(IOException e){
        e.printStackTrace();
    }

}
private SerializedThread readMyObjectFromFile(String fileName){
    FileInputStream fis = null;
    ObjectInputStream ois = null;
    SerializedThread runner = null;
    try{
        fis = new FileInputStream(fileName);
        ois = new ObjectInputStream(fis);
        runner = (SerializedThread)ois.readObject();
        ois.close();
    }catch(IOException e){
        e.printStackTrace();
    }catch(ClassNotFoundException ex){
        ex.printStackTrace();
    }
    return runner;
}

public static void main(String[] args) {
    new Main();

}

class SerializedThread implements Serializable, Runnable {

    transient private SerializedThread[] children = null;
    transient public Thread self = null;
    private String[] childrenFileNames = null;

    SerializedThread() {}
    SerializedThread(String[] childrenFileNames) {
        setNames(childrenFileNames);
    }

    public void setNames(String[] ...

Alex_ Junior Poster

Hello. I'm trying to serialize a class that implements Serializable and a Runnable. My class has a transient Thread object as a field that is created and started after the restoration of my class(object).

This is proven possibile by a tutorial from Oracle, [URL="http://java.sun.com/developer/technicalArticles/Programming/serialization/"]here[/URL]. But i fail to compile my program which is very similar to the one in the tutorial(i think).

So in the following i attach my source code and the exception's trace in hope that someone can help me out.
[code=java]
/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */

package ppc2;

import java.io.Serializable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Main {

Main(){

    SerializedThread [] threads = new SerializedThread[7];
    for(int i =1 ;i<8;i++){
        if(i==1)
            threads[i] = new SerializedThread(new String[]{"f2","f3","f4"});
        if(i==2)
            threads[i] = new SerializedThread(new String[]{"f5"});
        if(i==3)
            threads[i] = new SerializedThread(new String[]{"f6"});
        if(i==4)
            threads[i] = new SerializedThread(new String[]{"f7"});
    }
    for(int i =0;i<7;i++){
        writeMyObjectToFile(threads[i],"f"+(i+1));
    }
    readMyObjectFromFile("f1");
}

private void writeMyObjectToFile(SerializedThread runner, String fileName){
    FileOutputStream fos = null;
    ObjectOutputStream oos = null;
    try{
        fos = new FileOutputStream(fileName);
        oos = new ObjectOutputStream(fos);
        oos.writeObject(runner);
        oos.close();
    }catch(IOException e){
        e.printStackTrace();
    }

}
private SerializedThread readMyObjectFromFile(String fileName){
    FileInputStream fis = null;
    ObjectInputStream ois = null;
    SerializedThread runner = null;
    try{
        fis = new FileInputStream(fileName);
        ois = new ObjectInputStream(fis);
        runner = (SerializedThread)ois.readObject();
        ois.close();
    }catch(IOException e){
        e.printStackTrace();
    }catch(ClassNotFoundException ex){
        ex.printStackTrace();
    }
    return runner;
}

public static void main(String[] args) {
    new Main();

}

class SerializedThread implements Serializable, Runnable {

    transient private ...

Alex_

Techwriter10, what about multitasking? Computers and phones where able to multi task decades ago... but iphone decided to disable multitasking in iphone3g,3gs,ipad... and just now they enabled it with iphone4. They planned not to multitask until now. That's a planned obsoleteness so that they can sell as many as products possible.

Alex_

In other words you pay a lot of money over and over again for phone that is PLANNED to be obsolete after a year or two so they can brag about the iphone 5 that it's the best thing ever happened (best plan for obsoleteness that ever happened,that is ).

They fool you: and you LIKE it!

Alex_

Hm, trying to make the demo proved to myself that it does work when calling the setFocusable method. I realized that the problem was that i forgot to add my label to the JScrollPane. I set it as a viewport only.. my bad.
Current initializations work with the keyListener:
[code] MyListener ml = new MyListener();
MyKeyListener mkl = new MyKeyListener();
label.addMouseListener(ml);
label.addMouseMotionListener(ml);

    label.setFocusable(true);
    label.addKeyListener(mkl);
    this.scrollPane.add(label);
    this.scrollPane.setViewportView(label);[/code]

Alex_

Tried doing a separate keyListener and adding to it but nothing changed.
[code]MyKeyListener mkl = new MyKeyListener();
label.setRequestFocusEnabled(true);
label.setFocusTraversalKeysEnabled(true);
label.setFocusable(true);
label.addKeyListener(mkl);[/code]

Alex_

yes, i tried. It's not a focus problem.

Alex_

I'm sorry, i didn't understood what you meant by "[I]and I'm afraid it's not even going to be touched by the XXX domain.[/I]"
Did you meant that this will not help filtering a porn link domain because some my not want a .XXX ?

Alex_ Junior Poster

Hi, i want to do a listener and this is what i have at the moment:
[code] class MyListener extends MouseInputAdapter implements KeyListener{

    @Override
    public void mousePressed(MouseEvent e) {
        if(e.getButton()==1){
            out.println("MSE press "+e.BUTTON1_MASK);
        }else if (e.getButton()==2){
            out.println("MSE press "+e.BUTTON2_MASK);
        }else if (e.getButton()==3){
            out.println("MSE press "+e.BUTTON3_MASK);
        }
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        out.println("MSE move "+x+" "+y);
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        out.println("MSE drag "+x+" "+y);
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        if(e.getButton()==1){
            out.println("MSE release "+e.BUTTON1_MASK);
        }else if(e.getButton() ==2) {
            out.println("MSE release "+e.BUTTON2_MASK);
        }else if(e.getButton() ==3) {
            out.println("MSE release "+e.BUTTON3_MASK);
        }
    }
    @Override
    public void keyTyped(KeyEvent e){

    }
    @Override
    public void keyPressed(KeyEvent e){
        out.println("KEY press "+e.getKeyCode());
        System.out.println("Say it!");
    }
    @Override
    public void keyReleased(KeyEvent e){
        out.println("KEY release "+e.getKeyCode());
        System.out.println("Say it!");
    }
}[/code]

and then i add it to a JLabel this way:
[code] MyListener ml = new MyListener();
label.addMouseListener(ml);
label.addMouseMotionListener(ml);
label.addKeyListener(ml);[/code]
My label catches the mouse events but no key events. Can this be done somehow... or should i just make a separate key listener?

Alex_

Thanks very much. That did it.
I have some questions concerning the code you changed:

  1. Why does this logic work:
    [code]while(nbrLeftToRead > 0){
    int rd =in.read(byteArray, nbrRd, nbrLeftToRead);
    if(rd < 0)
    break;
    nbrRd += rd; // accumulate bytes read
    nbrLeftToRead -= rd;
    System.out.println("Got part of image. rd=" + rd + ", nbrLeftToRead= " + nbrLeftToRead

    • " avail=" + in.available());
      }[/code]
      I mean, "[I]int rd =in.read(byteArray, nbrRd, nbrLeftToRead);[/I]", if you read from the input stream into a byteArray, from the offset nbrRD, nbrLeftToRead bytes then they should get read all at once. Which is not the case when i run it.
  2. Why did you changed this line
    [code]fromServer.indexOf("image") >= 0[/code]
    Is it because its faster/optimized?

Alex_

Nevermind about my previous post.I corrected the error but didn't managed to edit it in time.
My client side code:
[code] //Accepting connection and initilizing streams
Socket incoming = conn.accept();
System.out.println("Data connection Established");
in = incoming.getInputStream();
reader = new BufferedReader (new InputStreamReader(in));

        //Reading from server
        fromServer = reader.readLine();
        System.out.println("First message from dataSender:"+fromServer);

        //Getting the images
        BufferedImage buffImg = null;
        for(;fromServer.contains("image");){//fromServer.contains("image")
            str = fromServer.split(" ");
            byteArray = new byte [Integer.parseInt(str[2].trim())];
            in.read(byteArray);
            System.out.println("Got image.");

            //Converting the image
            ByteArrayInputStream byteArrayI = new ByteArrayInputStream(byteArray);
            buffImg = ImageIO.read(byteArrayI);

            //Displaying the image
            label = new JLabel(new ImageIcon(buffImg));
            scrollPane.setViewportView(label);
            fromServer = reader.readLine();
            System.out.println(""+fromServer);
        }

        in.close();
        conn.close();
        System.out.println("Data Reciever has ended!");[/code]

Client side output:[code]Data connection Established
First message from dataSender:image 1440x900 95895
Got image.
��X�`��������ߥ����QLCw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)�Pw�7�F����)����"�����[/code]

Server side code:[code] dim = toolkit.getScreenSize();
captureSize = new Rectangle(dim);

        for (int i = 0; i < 50; i++) {
            bufferedImage = robot.createScreenCapture(captureSize);
            System.out.println("Got image!");

            byteArrayO = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage,"jpg",byteArrayO);
            byte [] byteArray = byteArrayO.toByteArray();
            str = "image " + dim.width + "x" + dim.height+ " "+(byteArray.length);
            writer.println(str);
            System.out.println(str);

            out.write(byteArray);
            System.out.println("Sent image!");
            //out.flush();
        }[/code]

Server side output:[code]Got image!
image 1440x900 95895
Sent image!
Got image!
image 1440x900 95981
java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:124)
at myserver.DataSender.sendImage(DataSender.java:98)
at myserver.DataSender.run(DataSender.java:77)[/code]
I do manage to get a image on the other side, but it's half-way interrupted. I've attached a screenshot. Is it because i'm capturing my own screen, or because the size wasn't estimated correct. Please help me understand where the estimation was done wrong, if it's the second.

Alex_

I didn't created my PrintWriter from the server side correct, that was the problem.
However...now i have : [code]Data connection Established
First message from dataSender:image 1440x900 0
Exception in thread "Thread-2" java.lang.NullPointerException
at screenviewer.DataReciever.run(DataReciever.java:92)[/code]
The last zero there is the size of the image in bytes. That's strange because my image is still there (1440x900). Perhaps the conversion to byte array wasn't successful. Any hints?

Alex_

[QUOTE]What do you want the code to do? [/QUOTE]
I thought the title was there for making it clear.

I want to send multiple images over a socket and show them on the client side.
It looks like my code stops on this line.
[code]fromServer = reader.readLine();[/code]
Can you please tell me why, if your see the problem? And provide a solution, perhaps, please.

Alex_

my Client side:
[code] //Accepting connection and initilizing streams
Socket incoming = conn.accept();
System.out.println("Data connection Established");
in = incoming.getInputStream();
reader = new BufferedReader (new InputStreamReader(in));

        //Reading from server
        fromServer = reader.readLine();
        System.out.println("First message from dataSender:"+fromServer);

        //Getting the images
        BufferedImage buffImg = null;
        for(;fromServer.contains("image");){
            str = fromServer.split(" ");
            byteArray = new byte [(int) Integer.getInteger(str[2])];
            in.read(byteArray);
            System.out.println("Got image.");

            //Converting the image
            ByteArrayInputStream byteArrayI = new ByteArrayInputStream(byteArray);
            buffImg = ImageIO.read(byteArrayI);

            //Displaying the image
            label = new JLabel(new ImageIcon(buffImg));
            scrollPane.setViewportView(label);
            fromServer = reader.readLine();
        }

        in.close();
        conn.close();
        System.out.println("Data Reciever has ended!");[/code]

And Server side:
[code]dim = toolkit.getScreenSize();
System.out.println("Got screen size:" + dim.width + "x" + dim.height);

        captureSize = new Rectangle(dim);

        for (int i = 0; i < 50; i++) {
            bufferedImage = robot.createScreenCapture(captureSize);
            System.out.println("Got image!");

            byte [] byteArray = byteArrayO.toByteArray();
            writer.println("image " + dim.width + "x" + dim.height+ " "+(byteArray.length));
            System.out.println("Sent dimensions.");

            out.write(byteArray);
            System.out.println("Sent image!");
            out.flush();
        }[/code]

Client's output (not showing any image):
[code]Data connection Established[/code]
Server wrote (probably) 50 messages (did 50 iterations). Where did i go wrong?

Alex_

I tried to do the primitive way , but how to get the image's size?

Or maybe you can help writing an image IO the grammar way... having a look at Image IO API i noticed i can use a ImageWriter to write into a stream... and it seems i should do it with these functions:
[code]prepareWriteEmpty(IIOMetadata streamMetadata, ImageTypeSpecifier imageType, int width, int height, IIOMetadata imageMetadata, List thumbnails, ImageWriteParam param)// Begins the writing of a complete image stream, consisting of a single image with undefined pixel values and associated metadata and thumbnails, to the output.[/code]
and end it with
[code]endWriteEmpty()//Completes the writing of a new image that was begun with a prior call to prepareWriteEmpty.[/code]
but there are a lot of params that i don't understand. :S . And how knows if my interpretations are correct...

Alex_

Make a document over that file, then just write:
[code]doc.insertString(offset,"The String",null)[/code].

The easiest way to do :
[code]
JTextArea text = new JTextArea();
text.setText("Your string");
AbstractDocument doc = text.getDocument();
doc.insertString(offset,"The String",null)[/code]
Offset is the position from which to start.

Alex_ Junior Poster

Sending one image works, but when i repeat the cycle again it just doesn't work.
my Client side code (excerpt):
[code] for(int i=0;i<50;i++){//fromServer.contains("image")
img = ImageIO.read(in);
System.out.println("Got image.");
label = new JLabel(new ImageIcon(img));
scrollPane.setViewportView(label);
fromServer = reader.readLine();
}[/code]On the client side i have this output [code]Got image.
Got image.
Exception in thread "Thread-2" java.lang.NullPointerException
at javax.swing.ImageIcon.(ImageIcon.java:190)
at screenviewer.DataReciever.run(DataReciever.java:84)[/code]
my Server side code (excerpt):
[code]dim = toolkit.getScreenSize();
System.out.println("Got screen size:" + dim.width + "x" + dim.height);
captureSize = new Rectangle(dim);

        for (int i = 0; i < 50; i++) {
            bufferedImage = robot.createScreenCapture(captureSize);
            ImageIO.write(bufferedImage, "JPG", out);
            System.out.println("Sent image!");
            //out.flush(); this didn't helped
        }[/code]

Please help this is for my "end of the year thesis". I need to finish my project fast.

Alex_

Hey thanks. But i still can't add something to the scroll pane.
my code
[code] Component[] comps = theFrame.getContentPane().getComponents();
int i =-1;
do{i++; }while(!(comps[i] instanceof JScrollPane) );
JScrollPane scrollPane = (JScrollPane) comps[i];
JTextArea ta = new JTextArea ("texttttt");
ta.setText("testsetsetsetsetset");
scrollPane.add(ta);
scrollPane.setViewportView(ta);[/code]
Can you please tell me what i'm missing?

[EDIT]
Nevermind. I fixed it. :)

Alex_ Junior Poster

I have a class that gets a JFrame as a parameter. I want to get a certain component from it and do some operations with it.
Something like this:
[code]
class A {
A (JFrame frame){
a_certain_Component jScrollPane = (a_certain_Component) frame.getThatComponent();
jScrollPane.setViewPort(new JTextPane());
}
}[/code]

Alex_

Done a clean install of ubuntu 10.04. Installed the Sun JDK instead of OpenJDK and i'm all good to go. Took a 32 bit system because ubuntu's site recommended such and after some research i came to the conclusion that i would have more advantages this way.

Alex_

Hm, it looks like this is a [URL="https://bugs.launchpad.net/ubuntu/+source/appmenu-gtk/+bug/593474"]bug[/URL] rather than a corrupt file issue. (i've reinstalled the liglib file via synaptic and got no good results.)