PayloadZipBean - Problems
Hi,
I want to reduce the traffic on our network so I try to send most of the data to XI as ZIP file. Thereby I found the PayloadZipBean Module.
Setup of the Module was very easy. But now I get always an error in the communication channel
Error: java.util.zip.ZipException: invalid entry size (expected 4388736 but got 4387325 bytes)
In the meantime I tried 3 diffrent Zip solutions and I get always the same result. Although with a java application that using the ZipException to Zip the file.
Had anybody similar issues?
Some ideas how that problem can be solved?
cheers,
Stefan
Hi all,
@Satish, the Weblogs I know. I used it to setup my szenario / File adapter
@Stefan, really a good idea especially in the past I did a lot of funny expirience with Codepages within XI.
But id did not help. I tried to save the file included to the ZIP as Ansi, UTF8, DOS, Unicode Codepage and it did not help.
What s sh......
Similar Messages
-
Problem using payloadZipBean to unzip a file
I would like to run OS command to zip large amount of xml into one zip file before XI pick it up, then use unzip option in payloadZipBean to unzip all the xml files so XI can process them one by one from memory, this will reduce lots file I/O time.
But I am getting this warning message:
Warning Zip: message is empty or has no payload
But if I display this message in RWB, the only payload is this zip file.
Why the payloadZipBean is not unzipping this file as supposed to.Did you check this blog
/people/stefan.grube/blog/2007/02/20/working-with-the-payloadzipbean-module-of-the-xi-adapter-framework
Sameer -
Unzip file using PayloadZipBean in Sender FILE adapter
I am trying to unzip a flat file in Sender FILE adapter using PayloadZipBean.
I am getting mapping error. The problem is File adapter is reading data without unzipping. I am getting weird characters/data, so mapping error.
I searched all the blogs/ forum threads and help.sap.com, everywhere the focus is on zipping, not unzipping.
the file I have is with .gz extension, but I tried with .zip extension also.
Please help in resolving this issue.
Edited by: Gopal Janagama on May 2, 2008 11:42 PMGopal,
GZIP and ZIP format are slightly different, as stated here :
"GZIP compresses only one file and does not have a header. ZIP contains header information about what files are contained in the file."
So I'm not sure the PayloadZipBean supports GZIP format ... Try to ungzip and then zip its content and see if the bean works for it
Rgds
Chris -
Controlling filenames using PayloadZipBean
Hello
I am struggling with names of the zipped files using payloadzipbean. The Scenario is as follows: we want to transfer an invoice including attachments to an external partner consisting of an xml message and one or more pdf files as attachments. the attachments are added to the message in an ABAP proxy on the sending R/3 system. The message is transferred to PI,where it si routed to an ftp communication channel. The xml message is zipped using the payloadzip bean and transferred to the external partner using ftp. The partner requires an approriate file extension to identify the types of files on the receiving side. Originally we managed this pay using the parameter zip.filenameKey and set it ContentType. The files inside the zip file are then named "untitled.xml" for the xml message and "untitled.pdf" for the attachments. However when there is more than one attachment the zipping of the file crashed, as both attachments have the same filename. We can fix this by adding an unique name to the attachment when it is attached to the proxy, and changing the zip.filenameKey to payloadName. The problem then is that the main payload file is called MainDocument without the .xml extension. I need to change the name of the payload or find another way to make the attachment filenames unique with zip.filenameKey set to ContentTyoe, Any suggestions ?
Eivind Langsæterit is a bit tricky.
You might have to code a module to build the attachments and then use zipbean to zip it for you.
to set the name of the main document you can have a look into the sinppet of code below;
Vector_attachementFileName contains the name for the attachment
attachmentFileMainPayload has the data of the main payload
XMLPayload MainDocumentPayload = message.createXMLPayload();
MainDocumentPayload.setContent(
this.attachmentFileMainPayload.getBytes());
message.setDocument(MainDocumentPayload);
Audit.addAuditLogEntry(
this.auditMKey,
AuditLogStatus.SUCCESS,
"Main Document Successfully Set");
TextPayload txtpayload = message.getDocument();
txtpayload.setContentType("text/plain");
txtpayload.setName(
this.Vector_attachementFileName
.elementAt(lengthOfVector - 1)
.toString());
Audit.addAuditLogEntry(
this.auditMKey,
AuditLogStatus.SUCCESS,
"File Created: " +
this.Vector_attachementFileName
.elementAt(lengthOfVector - 1)
.toString()); -
Error Archiving File in File Sender Adapter using AF_Modules/PayloadZipBean
Hi everybody.
I have to pick a zip file up from ftp server, unzip an convert the file in xml.
Im using this modules in file sender adapter:
AF_Modules/PayloadZipBean --> To unzip de file
AF_Modules/MessageTransformBean --> file to xml
The problem is when I try to archive de file. Im getting this error and I dont know why (This path exists /out/ProcesadosSinError/)
Could not archive file 'test.zip' as '/out/ProcesadosSinError/20100518-091029-155_test.zip' after processing: java.io.FileNotFoundException: /out/ProcesadosSinError/20100518-091029-155_test.zip (A file or directory in the path name does not exist.)
Could it be that is not possible to archive with AF_Modules/PayloadZipBean?
Thank u so muchHi Stefan.
Absolutely. This path exists. It's an absolute path from root. I can´t understand the error!!!!
Thanks!!!
Edited by: Christian Abad Chico on May 18, 2010 9:35 AM -
PayloadZIPBean with Mail Package... is it possible?
Hi,
In proxy to file scenario, I send mails from PI with data received from proxy as attachment. I also need to zip the attachment.
I will be getting the email address dynamically, hence I should use Mail Package with 'Keep Attachments' option. Now the problem is if I use mail package since the <content> tag data is taken as mail attachment, can I use PayloadZipBean in receiver mail adapter to zip the attachemnt?
I tried using the follwoing adapter module in receiver mail mail adapter but ended with an error.
Module Name: AF_Modules/PayloadZipBean Module Key: zip
Module Config:
zip zip.filenameKey payloadName
zip zip.mode zipOne
Error:
org.xml.sax.SAXParseException: Content is not allowed in prolog
Regards,
SreedharHi Sreedhar,
Have you looked at this help link?
http://help.sap.com/saphelp_nwpi711/helpdata/en/45/da9358a1772e97e10000000a155369/content.htm
Also see :
Zip Payload using PayloadZipBean Module Processor
Regards,
Ravi Kanth Talagana
Edited by: Ravi Kanth Talagana on Oct 22, 2009 5:13 PM -
Problem in the picking up the file
hi all,
i am working on agile to sap,
here PI has to pick .pdx (or) .axml files and thses files are zip files again, open these files winzip, then those can be extracted in xml files.
now PI has to pick the .pdx file and put it as .pdx filein the reciever side.
now my problem is iam able to pick the .pdx file but it is not pushing the file in reciever side.
in sxmb_moni, iam gettingh this error.
SAP:Code area="MAPPING">EXCEPTION_DURING_EXECUTE</SAP:Code>
<SAP:P1>com/sap/xi/tf/_mm_axml_</SAP:P1>
<SAP:P2>java.lang.NullPointerException</SAP:P2>
<SAP:P3 />
<SAP:P4 />
<SAP:AdditionalText />
<SAP:ApplicationFaultMessage namespace="" />
<SAP:Stack>java.lang.NullPointerException thrown during application mapping com/sap/xi/tf/_mm_axml_:</SAP:Stack>
<SAP:Retry>M</SAP:Retry>
thanks
madhavHi Madhav,
In your case you need to unzip the files from .pdx format to xml format for that you need to use the PayloadZipBean module in the sender communication channel.
The details you need to specify in the processing sequense are as follows:
Modulename: AF_Modules/PayloadZipBean
This should be placed before the callsapadapter
Than in the module configuration you need to specify the following:
paramatername :zip.mode
parametermode:unzip
Thanks,
Bhargav.
Note:Award points if found useful -
Unzip char conversion problems
Hi everyone.
I've got a zipped .txt that i unzip ussing PayloadZipBean module. It works fine but my problem is that i get some rare characters.
Instead of á or ó or ì, i get a ? or # and so long.
Does anybody know how to keep 'original' characters?
Regards,
Inigo.Hi Stefan.
I receive an attachment in a sender webservice. This attachment is a ZIP file that contains a TXT file inside.
What i have in file receiver adapter is :
localejbs/AF_Modules/PayloadSwapBean Local Enterprise Bean transform
localejbs/AF_Modules/PayloadZipBean Local Enterprise Bean zip
localejbs/AF_Modules/MessageTransformBean Local Enterprise Bean contentType
CallSapAdapter Local Enterprise Bean 0
************************************************************************************++++
transform swap.keyName payload-name
transform swap.keyValue attachment-1
zip zip.mode unzip
contentType Transfer.ContentType text/plain;charset="ISO-8859-1"
With this, i still haven't got the correct characters (á, é, í, ó, ú, ò, è and so long)
Kind regards,
Inigo. -
Unzip using Payloadzipbean/file content conversion
Experts,
I have a scnario, I get a zip file with .gz extension, unzip it read th file using file adapter.
I am using Payloadzipbean module to unzip(zip.mode = unzip).
The problem is File adapter converting the zip file into xml and unzipping the file.
How do I force File adapter to unzip first and do content conversion.
thanksHi man.
How did you solve this. I have to pick up a zip file with a .txt file then I need to convert this file to xml with module MessageTransformBean but Im getting this error:
com.sap.aii.messaging.adapter.trans.TransformException: Error converting Message: 'sun.io.MalformedInputException'; nested exception caused by: sun.io.MalformedInputException
This is my structure
row (1..n)
>TRANSPORTES (1)
>ENTREGAS (1..n)
I have configured the module tag in this way:
AF_Modules/PayloadZipBean - zip
AF_Modules/MessageTransformBean - transform
CallSapAdapter - 0
zip - zip.mode - unzip
transform - Transform.Class - com.sap.aii.messaging.adapter.Conversion
transform - xml.ENTREGAS.endSeparator - 'nl'
transform - xml.ENTREGAS.fieldFixedLengths - 1,30
transform - xml.ENTREGAS.fieldNames - TIPO,NUM_ENTREGA
transform - xml.ENTREGAS.keyFieldValue - E
transform - xml.TRANSPORTES.endSeparator - 'nl'
transform - xml.TRANSPORTES.fieldFixedLengths - 1,30
transform - xml.TRANSPORTES.fieldNames - TIPO,NUM_TRANSPORTE
transform - xml.TRANSPORTES.keyFieldValue - T
transform - xml.keyFieldType - CaseSensitiveString
transform - Transform.ContentType - text/plain;charset=utf-8
transform - xml.conversionType - StructPlain2XML
transform - xml.documentName - MPrueba_Zip
transform - xml.documentNamespace - http:/XXXXXX.es/XXXX/sap/prueba
transform - xml.keyFieldName - TIPO
transform - xml.processFieldNames - fromConfiguration
transform - xml.recordsetName - row
transform - xml.recordsetStructure - TRANSPORTES,1,ENTREGAS,*
If I use only the MessageTransformBean directly from .txt everything works ok!!!
What am I doing wrong???
Thanks a lot!!! -
Adapter PI7.1 Module Problem
hi,
i'm facing a weird problem , i'll explain:
I developed a module adapter to be able get the dynamic file name into a zip file because i'm using the AF_Modules/PayloadZipBean and as we know the name of the file inside the zip in a standar way is static.
The things is that i could do the task using the following code :
public ModuleData process(ModuleContext moduleContext, ModuleData inputModuleData) throws ModuleException {
//String SIGNATURE = "process(ModuleContext moduleContext, ModuleData inputModuleData)";
Location location = null;
AuditAccess audit = null;
String unidadE,centro,unidadO =null;
// Create the location always new to avoid serialization/transient of location
try {
location = Location.getLocation(this.getClass().getName());
}catch (Exception t) {
t.printStackTrace();
ModuleException me = new ModuleException("Unable to create trace location", t);
throw me;
Object obj = null;
Message msg = null;
MessageKey key = null;
try {
obj = inputModuleData.getPrincipalData();
msg = (Message) obj;
key = new MessageKey(msg.getMessageId(), msg.getMessageDirection());
audit = PublicAPIAccessFactory.getPublicAPIAccess().getAuditAccess();
audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS, "BuildFileName: Module called");
catch (Exception e) {
ModuleException me = new ModuleException(e);
throw me;
try {
TextPayload xmlpayload = msg.getDocument();
DocumentBuilderFactory factory;
factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse((InputStream)xmlpayload.getInputStream());
NodeList nodosTablaProcesa = document.getElementsByTagName("TablaProcesa");
Element elementFPVM00 = (Element) nodosTablaProcesa.item(0);
NodeList nodoFPVM00 =elementFPVM00.getElementsByTagName("FPVM00");
Element elementRegistro =(Element) nodoFPVM00.item(0);
NodeList nodoRegistro = elementRegistro.getElementsByTagName("reg");
Element element = (Element)nodoRegistro.item(0);
NodeList valorNumcia = element.getElementsByTagName("NUMCIA");
Element valNumcia =(Element) valorNumcia.item(0);
NodeList valorNumAlm = element.getElementsByTagName("NUMALM");
Element valNumalm = (Element)valorNumAlm.item(0);
NodeList valorSubAlm = element.getElementsByTagName("SUBALM");
Element valSubalm = (Element) valorSubAlm.item(0);
unidadE =getCharacterDataFromElement(valNumcia);
centro = (getCharacterDataFromElement(valNumalm)).replace("'","");
unidadO =(getCharacterDataFromElement(valSubalm)).replace("'","");
String fileName = "RT"unidadEcentrounidadO".xml";
audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS, "BuildFileName:" +fileName);
if(fileName == null)
xmlpayload.setContentType("text/plain;charset = "UTF-8";filename="defaultbeanfile.txt"");
else
xmlpayload.setContentType("text/plain;charset = "UTF-8";filename="" + fileName + """);
audit.addAuditLogEntry(key, AuditLogStatus.SUCCESS, "BuildFileName:" +xmlpayload.getContentType());
inputModuleData.setPrincipalData(msg);
} catch (Exception e) {
ModuleException me = new ModuleException(e);
audit.addAuditLogEntry(key, AuditLogStatus.ERROR, "BuildFileName: Module Fail");
throw me;
return inputModuleData;
the problem is when we transport this module to QA environment isn´t working , instead of put the dynamic file name is putting "untitled.txt" , in DEV everything is fine , do you know about some bugs in PI 7.1 ?? some notes that could help?
thanks in advanced
my config in the file adapter is the following
PROCESSING SEQUENCE
BuildFileName Local Enterprise Bean contentType
AF_Modules/PayloadZipBean Local Enterprise Bean zip
CallSapAdapter Local Enterprise Bean 2
MODULE CONFIGURATION
zip zip.filenameKey contentType
zip zip.mode zipOneHi Stefan ,
for example in QA we have some diferences ,
QA SAP_XIAF -> 1000.7.10.6.18.20090211173100
DEV SAP_XIAF-> 1000.7.10.6.13.20081124173200
It seems like QA has an updated , but in QA is not working, do you know what packages could be causing this problem? at first sight i choose SAP_XIAF because the adapter framework ,
The code seems correct on sight. Is the audit log entry with the file name available? Is this correct?
Yes , when i saw the audit log in MessagingSystem monitor , i can see the well file name formed (ex "RT213AC00AC0000.xml") ,
thanks -
I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
Thank you in advance,
LeftyThis was one solution from the socket programming forum, have you tried this??
public Thread MyThread extends Thread{
boolean active = true;
public void run(){
ss.setSoTimeout(90);
while (active){
try{
serverSocket = ss.accept();
catch (SocketTimeoutException ste){
// do nothing
// interrupt thread
public void deactivate(){
active = false;
// you gotta sleep for a time longer than the
// accept() timeout to make sure that timeout is finished.
try{
sleep(91);
}catch (InterruptedException ie){
interrupt();
} -
A problem with Threads and MMapi
I am tring to execute a class based on Game canvas.
The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
The MIDI tone "Stammers".
How to over come the problem?
Thanks in advance
Kobi
See Code example below:
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
public class MainScreenCanvas extends GameCanvas implements Runnable {
private MainMIDlet parent;
private boolean mTrucking = false;
Image imgBackgound = null;
int imgBackgoundX = 0, imgBackgoundY = 0;
Player player;
public MainScreenCanvas(MainMIDlet parent)
super(true);
this.parent = parent;
try
imgBackgound = Image.createImage("/images/area03_bkg0.png");
imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
catch(Exception e)
System.out.println(e.getMessage());
* starts thread
public void start()
mTrucking = true;
Thread t = new Thread(this);
t.start();
* stops thread
public void stop()
mTrucking = false;
public void play()
try
InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
player = Manager.createPlayer(is, "audio/midi");
player.setLoopCount(-1);
player.prefetch();
player.start();
catch(Exception e)
System.out.println(e.getMessage());
public void run()
Graphics g = getGraphics();
play();
while (true)
tick();
input();
render(g);
* responsible for object movements
private void tick()
* response to key input
private void input()
int keyStates = getKeyStates();
if ((keyStates & LEFT_PRESSED) != 0)
imgBackgoundX++;
if (imgBackgoundX > 0)
imgBackgoundX = 0;
if ((keyStates & RIGHT_PRESSED) != 0)
imgBackgoundX--;
if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
* Responsible for the drawing
* @param g
private void render(Graphics g)
g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
this.flushGraphics();
}You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
Regds,
SD
N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM -
Hi all,
I would like to ask you for a help. I need to write a small program at my university. I started to write a midlet which function would be to countdown time for sports activities. I woul like to start a new thread - the one that counts down - and at the same time make the main thread sleep. After the "countdown" thread finishes, the main thread wakes up and waits for user input. The problem is that when the "countdown" thread finishes his work, I've got Uncaught exception java/lang/NullPointerException. error and the midlet halts.
Below you can find the code
import java.lang.*;
import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class intervals extends MIDlet implements CommandListener
public Display ekran;
private SweepCanvas sweeper;
private Form rundy;
private TextField round0, round1, round2, round3, round4, round5, round6, round7, round8;
private long czas,x;
private Command exitCommand;
private Command addRound;
private Command delRound;
private Command start;
private TextField repeat;
private Form odliczanie;
private Alert ostrz;
Licznik thread;
String test;
StringItem test1;
int parz,i,j,k;
static int l;
int ilrund;
int ilpowt;
Item sec;
long sec1;
public intervals()
rundy = new Form("Interwały sportowe");
exitCommand = new Command("Wyjście", Command.EXIT, 2);
addRound = new Command("Dodaj","Dodaj rundę", Command.ITEM,1);
delRound = new Command("Usuń","Usuń ostatnią rundę", Command.ITEM,1);
start = new Command("Start", Command.ITEM,1);
odliczanie = new Form("Odliczanie");
TextField dodaj(TextField kolej)
kolej=new TextField("Podaj czas (s) rundy "+parz,null, 4, TextField.NUMERIC);//stworzenie nowej instancji do wybierania czasu trwania rundy
if(rundy.size()==0)
rundy.insert(rundy.size(),kolej);
else
rundy.insert(rundy.size()-1, kolej);
return kolej;
void odliczanie(TextField round)
monitor m=new monitor();
k=Integer.parseInt(round.getString());
ekran.setCurrent(odliczanie);
thread=new Licznik(k,odliczanie);
thread.start();
ekran.setCurrent(rundy);
public void startApp()// throws MIDletStateChangeException
rundy.deleteAll();
repeat = new TextField("Podaj ilość powtórzeń",null,1,TextField.NUMERIC);
rundy.addCommand(addRound);
rundy.addCommand(exitCommand);
rundy.setCommandListener(this);
Canvas obrazek = new MyCanvas();
ekran = Display.getDisplay(this);
ekran.setCurrent(obrazek);
czas=System.currentTimeMillis();
while (System.currentTimeMillis()<czas+1000)
continue;
ekran.setCurrent(rundy);
public void pauseApp()
public void destroyApp(boolean unconditional)
notifyDestroyed();
public void commandAction(Command c, Displayable s)
if (c == exitCommand)
destroyApp(false);
notifyDestroyed();
else if(c==addRound)
if(rundy.size()==0)//Sprawdzenie ilości elementów w celu poprawnego wyświetlania liczby rund w formie
parz=1;
else
parz=rundy.size();
switch(parz)
case 1:
round0=dodaj(round0);break;
case 2:
round1=dodaj(round1);break;
case 3:
round2= dodaj(round2);break;
case 4:
round3=dodaj(round3);break;
case 5:
round4=dodaj(round4);break;
default:
ostrz=new Alert("Uwaga","Maksymalna liczba rund wynosi 9", null, AlertType.INFO);
ostrz.setTimeout(3000);
ekran.setCurrent(ostrz);
if(rundy.size()==1)
rundy.append(repeat);
rundy.addCommand(start);
rundy.addCommand(delRound);
else if(c==delRound)
if(rundy.size()!=0)
rundy.delete(rundy.size()-2);
if (rundy.size()==1)
rundy.deleteAll();
if(rundy.size()==0)
rundy.removeCommand(delRound);
rundy.removeCommand(start);
else if(c==start)
ilrund=rundy.size()-1;
if(this.repeat.size()>0)
ilpowt=Integer.parseInt(this.repeat.getString());
ekran = Display.getDisplay(this);
for (i=1; i<=ilpowt;i++)
odliczanie= new Form("Odliczanie");
for (j=0;j<ilrund;j++)
switch(j)
case 0:
odliczanie(round0);
break;
case 1:
odliczanie(round1);
break;
case 2:
odliczanie(round2);
break;
case 3:
odliczanie(round3);
break;
case 4:
odliczanie(round4);
break;
case 5:
odliczanie(round5);
break;
case 6:
odliczanie(round6);
break;
case 7:
odliczanie(round7);
break;
case 8:
odliczanie(round8);
break;
class Licznik extends Thread
int czas1,k;
Form forma;
monitor m;
public Licznik(int k,Form formap)
czas1=k;
forma=formap;
public synchronized void run()
while(czas1>0)
forma.deleteAll();
forma.append("Czas pozostały (s): "+czas1);
try{Thread.sleep(1000);} catch(InterruptedException e){e.printStackTrace();}
czas1--;
if(czas1<=0)
m.put();
}and monitor class
public class monitor
boolean busy=false;
synchronized void get()
if(!busy)
try
wait();
}catch(InterruptedException e){e.printStackTrace();}
notify();
synchronized void put()
if(busy)
try
wait();
}catch(InterruptedException e){e.printStackTrace();}
busy=true;
notify();
}Can anybody help me with this?Groovemaker,
Your Licznik class has a member m of type monitor, which has not been instantiated (in other words is null) hence, when calling m.put() you get NullPointerException. Please also mind, that using Thread.sleep(1000) is not an accurate way of measuring time.
If I may, please use recommended for Java class naming conventions - some of your names use lower case, while other don't which is confusing to the reader.
Daniel -
Problem with threads within applet
Hello,
I got an applet, inside this applet I have a singleton, inside this singleton I have a thread.
this thread is running in endless loop.
he is doing something and go to sleep on and on.
the problem is,
when I refresh my IE6 browser I see more than 1 thread.
for debug matter, I did the following things:
inside the thread, sysout every time he goes to sleep.
sysout in the singleton constructor.
sysout in the singleton destructor.
the output goes like this:
when refresh the page, the singleton constructor loading but not every refresh, sometimes I see the constructor output and sometimes I dont.
The thread inside the singleton is giving me the same output, sometime I see more than one thread at a time and sometimes I dont.
The destructor never works (no output there).
I don't understand what is going on.
someone can please shed some light?
thanks.
btw. I am working with JRE 1.1
this is very old and big applet and I can't convert it to something new.Ooops. sorry!
I did.
public void start() {
public void stop() {
public void destroy() {
try {
resetAll();
Configuration.closeConnection();
QuoteItem.closeConnection();
} finally {
try {
super.finalize();
} catch (Throwable e) {
e.printStackTrace();
} -
Problem with Threads and a static variable
I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please.
Code functionality:
A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. Then notifies a main process thread to check if the state changed to send a message.
The problem as far I understand is:
Assume the timer Thread calls SetState twice before the main process Thread runs. As a result, "changed" is set to true twice. However, since the main process is blocked twice during the two calls to SetState, when it runs it would have the two SetState timer threads blocked on its synchronized body. It will pass the first one, send the message and set "changed" to false since it was true. Now, it will pass the second thread, but here is the problem, "changed" is already set to false. As a result, it won't send the message even though it is supposed to.
Would you please let me know if my understanding is correct? If so, what would you propose to resolve the problem? Should I call wait some other or should I notify in a different way?
Thanks,
B.D.
Code:
private static volatile boolean bChanged = false;
private static Thread objMainProcess;
protected static void Init(){
objMainProcess = new Thread() {
public void run() {
while( objMainProcess == Thread.currentThread() ) {
GetState();
objMainProcess.setDaemon( true );
objMainProcess.start();
public static void initStatusTimer(){
if(objTimer == null)
objTimer = new javax.swing.Timer( 1000, new java.awt.event.ActionListener(){
public void actionPerformed( java.awt.event.ActionEvent evt){
SetState();
private static void SetState(){
if( objMainProcess == null ) return;
synchronized( objMainProcess ) {
bChanged = true;
try{
objMainProcess.notify();
}catch( IllegalMonitorStateException e ) {}
private static boolean GetState() {
if( objMainProcess == null ) return false;
synchronized( objMainProcess ) {
if( bChanged) {
SendMessage();
bChanged = false;
return true;
try {
objMainProcess.wait();
}catch( InterruptedException e ) {}
return false;
}Thanks DrClap for your reply. Everything you said is right. It is not easy to make them alternate since SetState() could be called from different places where the state could be anything else but a status message. Like a GREETING message for example. It is a handshaking message but not a status message.
Again as you said, There is a reason I can't call sendMessage() inside setState().
The only way I was able to do it is by having a counter of the number of notifies that have been called. Every time notify() is called a counter is incremented. Now instead of just checking if "changed" flag is true, I also check if notify counter is greater than zero. If both true, I send the message. If "changed" flag is false, I check again if the notify counter is greater than zero, I send the message. This way it works, but it is kind of a patch than a good design fix. I am yet to find a good solution.
Thanks,
B.D.
Maybe you are looking for
-
Attachment is not visible if user logins with chinees langauge
Hello Experts I have developed one custom workflow, attachment is working. But when the user switsches to the language Chineese;user is not able to see the attachments in notification. How to resolve this issue with multiligual with attachments; Than
-
Java.lang.NoSuchMethodException when invoke method dynamic
hi! i have some trouble when i invoked hibernate PO class method dymaic by parameters, here is a piece of code, can someone help me? thanks in advance! please! String fieldname = field.getName().toLowerCase(); String methodName = "get" + fieldname.re
-
I am having a problem with my G5. when i burn discs on this computer, they come out fine, i can load and open them on my laptop, but if i try to put back into the G5 they are just ejected after about 30 seconds. The discs never show up on the desktop
-
ITunes(?) wiped out half my apps on iPad and iPhone today
iPhone 4, iPad2 - both set up for wifi sync to my iMac. Latest and greatest software all around. My last sync (on purpose) was last night. Plugged both devices into their chargers just as I got ready for bed. Got up this morning and all was well o
-
More and more often these days my PC, which is equipped with a P6N Diamond MoBo does not boot. There is no power, no nothing. It's just dead as if it were not plugged in. Then after a bit it will work. The thing that I am noticing is that the orange