Synchronized File Writing

Hi,
I have a written a Java Program which Splits any File into two Parts. These parts can again later be rejoined to restore the Original File.
This is how Splitting Operation is performed
1. Read the SourceFile into Array of Bytes
2. Open two FileOutputStreams and Write these Bytes, half of it in each stream. This is Done using a Thread for Each stream, Obviously to save time.
3. Now i have two Files which contain Bytes for Original File.
Now in Restoring Operation:
1. Read the two Files(split using above technique) and store in Byte Arrays.
2. Open the FileOutputStream to a File and write the Above byte Arrays ONE BY ONE into this Stream.
Please note that i had to write Bytes from two byte arrays in the Order i had read it.
Which means to say that i first have to write From First Byte Array, wait for it to finish it and than write from Second Byte Array. I cannot start Threads for Writing Bcoz the Target File is Same. Also, i wouldn't know where to start writing the bytes from Second Byte Array in the target File since, the First Thread may still be performing the Write Operation from the First Byte Array
If i had been writing a C program, this would be fairly easy since i have File Pointers. I can use two programs and use fseek() operation to Know exactly where to start writing from second set of Byte Array.
Please give ur suggestion to above problem. How can i simulate File Pointer operations of C in Java.
I hope i am Clear in describing the Problem. If not, then please let me know......and Thnx for u Patience

try not to cross post.
http://forum.java.sun.com/thread.jsp?forum=4&thread=165965&start=0&range=30#501577

Similar Messages

  • File writing serialization

    I have to build a web application using servlet and jsp. The user should edit some
    text file (maybe displaying the file fields in a HTML form).
    I need some suggestions about implementing the synchronization on file writing (since different
    users should try to save the same file simultaneously).
    Do some standard pattern exist about this feature ?
    I suppose to do that using a java bean whith application scope shared by the jsp pages. In this bean
    I will implement all write methods using synchronized.
    Any suggestions ?
    Thanks in advance,
    Mauro.

    well, if you have a single method which does the actual file writing, then you make that method synchronized and you'll have no problems. You can build up the data to write in some object at any time and pass that to that method.
    However, that's still going to present problems when users actually modify the file at the same time. Why does every user have to share 1 file?

  • Issue in Synchronous File Read in clustered environment

    Hi,
    We are using clustered environment (4 managed servers) in Unix. In a OSB 11gR3 proxy service we are using Synchronous File Read. Randomly we are getting the below error. Let us know what could cause the issue. But the same code is working fine in a single stand-alone server configuration.
    Error Code : BEA-380002 , Error Reason : Invoke JCA outbound service failed with connection error, exception: com.bea.wli.sb.transports.jca.JCATransportException: oracle.tip.adapter.sa.api.JCABindingException: oracle.tip.adapter.sa.impl.fw.ext.org.collaxa.thirdparty.apache.wsif.WSIFException: servicebus:/WSDL/wsdlPathAndName [ SynchRead_ptt::SynchRead(Empty,body) ] - WSIF JCA Execute of operation 'SynchRead' failed due to: No Data to process.
    No Data to process.
    File /root/oracle/domains/osb/11.1.1.4/cluster/data/osb2/FolderName/Filename.txt to be processed was not found or not available or has no content ; nested exception is:
    BINDING.JCA-11007
    No Data to process.
    No Data to process.
    File /root/oracle/domains/osb/11.1.1.4/cluster/data/osb2/FolderNamer/Filename.txt to be processed was not found or not available or has no content Please make sure that the file exists in the specified directory.
    com.bea.wli.sb.transports.jca.JCATransportException: oracle.tip.adapter.sa.api.JCABindingException: oracle.tip.adapter.sa.impl.fw.ext.org.collaxa.thirdparty.apache.wsif.WSIFException: servicebus:/WSDL/wsdlPathAndName [ SynchRead_ptt::SynchRead(Empty,body) ] - WSIF JCA Execute of operation 'SynchRead' failed due to: No Data to process.
    No Data to process.
    File /root/oracle/domains/osb/11.1.1.4/cluster/data/osb2/FolderName/Filename.txt to be processed was not found or not available or has no content ; nested exception is:
    BINDING.JCA-11007
    No Data to process.
    No Data to process.
    File /root/oracle/domains/osb/11.1.1.4/cluster/data/osb2/FolderName/Filename.txt to be processed was not found or not available or has no content Please make sure that the file exists in the specified directory.
    at com.bea.wli.sb.transports.jca.binding.JCATransportOutboundOperationBindingServiceImpl.invoke(JCATransportOutboundOperationBindingServiceImpl.java:153)
    at com.bea.wli.sb.transports.jca.JCATransportEndpoint.sendRequestResponse(JCATransportEndpoint.java:209)
    at com.bea.wli.sb.transports.jca.JCATransportEndpoint.send(JCATransportEndpoint.java:170)
    at com.bea.wli.sb.transports.jca.JCATransportProvider.sendMessageAsync(JCATransportProvider.java:598)
    at sun.reflect.GeneratedMethodAccessor1115.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.bea.wli.sb.transports.Util$1.invoke(Util.java:83)
    at $Proxy142.sendMessageAsync(Unknown Source)
    at com.bea.wli.sb.transports.LoadBalanceFailoverListener.sendMessageAsync(LoadBalanceFailoverListener.java:148)
    at com.bea.wli.sb.transports.LoadBalanceFailoverListener.sendMessageToServiceAsync(LoadBalanceFailoverListener.java:603)
    at com.bea.wli.sb.transports.LoadBalanceFailoverListener.sendMessageToService(LoadBalanceFailoverListener.java:538)
    at com.bea.wli.sb.transports.TransportManagerImpl.sendMessageToService(TransportManagerImpl.java:558)
    at com.bea.wli.sb.transports.TransportManagerImpl.sendMessageAsync(TransportManagerImpl.java:426)
    at com.bea.wli.sb.pipeline.PipelineContextImpl.doDispatch(PipelineContextImpl.java:670)
    at com.bea.wli.sb.pipeline.PipelineContextImpl.dispatchSync(PipelineContextImpl.java:551)
    at stages.transform.runtime.WsCalloutRuntimeStep$WsCalloutDispatcher.dispatch(WsCalloutRuntimeStep.java:1391)
    at stages.transform.runtime.WsCalloutRuntimeStep.processMessage(WsCalloutRuntimeStep.java:236)
    at com.bea.wli.sb.stages.StageMetadataImpl$WrapperRuntimeStep.processMessage(StageMetadataImpl.java:346)
    at com.bea.wli.sb.stages.impl.SequenceRuntimeStep.processMessage(SequenceRuntimeStep.java:33)
    at com.bea.wli.sb.pipeline.PipelineStage.processMessage(PipelineStage.java:84)
    at com.bea.wli.sb.pipeline.PipelineContextImpl.execute(PipelineContextImpl.java:1055)
    at com.bea.wli.sb.pipeline.Pipeline.processMessage(Pipeline.java:141)
    at com.bea.wli.sb.pipeline.PipelineContextImpl.execute(PipelineContextImpl.java:1055)
    at com.bea.wli.sb.pipeline.PipelineNode.doRequest(PipelineNode.java:55)
    at com.bea.wli.sb.pipeline.Node.processMessage(Node.java:67)
    at com.bea.wli.sb.pipeline.PipelineContextImpl.execute(PipelineContextImpl.java:1055)
    at com.bea.wli.sb.pipeline.Router.processMessage(Router.java:214)
    at com.bea.wli.sb.pipeline.MessageProcessor.processRequest(MessageProcessor.java:96)
    at com.bea.wli.sb.pipeline.RouterManager$1.run(RouterManager.java:593)
    at com.bea.wli.sb.pipeline.RouterManager$1.run(RouterManager.java:591)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
    at com.bea.wli.sb.security.WLSSecurityContextService.runAs(WLSSecurityContextService.java:55)
    at com.bea.wli.sb.pipeline.RouterManager.processMessage(RouterManager.java:590)
    at com.bea.wli.sb.transports.TransportManagerImpl.receiveMessage(TransportManagerImpl.java:375)
    at com.bea.wli.sb.transports.jca.binding.JCATransportInboundOperationBindingServiceImpl$4.run(JCATransportInboundOperationBindingServiceImpl.java:415)
    at com.bea.wli.sb.transports.jca.binding.JCATransportInboundOperationBindingServiceImpl$4.run(JCATransportInboundOperationBindingServiceImpl.java:413)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
    at weblogic.security.Security.runAs(Security.java:61)
    at com.bea.wli.sb.transports.jca.binding.JCATransportInboundOperationBindingServiceImpl.sendMessage(JCATransportInboundOperationBindingServiceImpl.java:413)
    at com.bea.wli.sb.transports.jca.binding.JCATransportInboundOperationBindingServiceImpl.invokeOneWay(JCATransportInboundOperationBindingServiceImpl.java:126)
    at com.bea.wli.sb.transports.jca.binding.JCAInboundRequestListener.post(JCAInboundRequestListener.java:39)
    at oracle.tip.adapter.sa.impl.inbound.JCAInboundListenerImpl.onMessage(JCAInboundListenerImpl.java:170)
    at oracle.tip.adapter.fw.jca.messageinflow.MessageEndpointImpl.onMessage(MessageEndpointImpl.java:502)
    at oracle.tip.adapter.file.inbound.Publisher.onMessageDelegate(Publisher.java:493)
    at oracle.tip.adapter.file.inbound.Publisher.publishMessage(Publisher.java:419)
    at oracle.tip.adapter.file.inbound.InboundTranslatorDelegate.xlate(InboundTranslatorDelegate.java:484)
    at oracle.tip.adapter.file.inbound.InboundTranslatorDelegate.doXlate(InboundTranslatorDelegate.java:121)
    at oracle.tip.adapter.file.inbound.ProcessorDelegate.doXlate(ProcessorDelegate.java:388)
    at oracle.tip.adapter.file.inbound.ProcessorDelegate.process(ProcessorDelegate.java:174)
    at oracle.tip.adapter.file.inbound.ProcessWork.run(ProcessWork.java:349)
    at weblogic.work.ContextWrap.run(ContextWrap.java:41)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:528)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:207)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:176)
    Caused by: oracle.tip.adapter.sa.api.JCABindingException: oracle.tip.adapter.sa.impl.fw.ext.org.collaxa.thirdparty.apache.wsif.WSIFException: servicebus:/WSDL/wsdlPathAndName [ SynchRead_ptt::SynchRead(Empty,body) ] - WSIF JCA Execute of operation 'SynchRead' failed due to: No Data to process.
    No Data to process.
    File /root/oracle/domains/osb/11.1.1.4/cluster/data/osb2/FolderName/Filename.txt to be processed was not found or not available or has no content ; nested exception is:
    BINDING.JCA-11007
    No Data to process.
    No Data to process.
    File /root/oracle/domains/osb/11.1.1.4/cluster/data/osb2/FolderName/Filename.txt to be processed was not found or not available or has no content Please make sure that the file exists in the specified directory.
    at oracle.tip.adapter.sa.impl.JCABindingReferenceImpl.request(JCABindingReferenceImpl.java:259)
    at com.bea.wli.sb.transports.jca.binding.JCATransportOutboundOperationBindingServiceImpl.invoke(JCATransportOutboundOperationBindingServiceImpl.java:150)
    ... 56 more
    Caused by: oracle.tip.adapter.sa.impl.fw.ext.org.collaxa.thirdparty.apache.wsif.WSIFException: servicebus:/WSDL/wsdlPathAndName [ SynchRead_ptt::SynchRead(Empty,body) ] - WSIF JCA Execute of operation 'SynchRead' failed due to: No Data to process.
    No Data to process.
    File /root/oracle/domains/osb/11.1.1.4/cluster/data/osb2/FolderName/Filename.txt to be processed was not found or not available or has no content ; nested exception is:
    BINDING.JCA-11007
    No Data to process.
    No Data to process.
    File /root/oracle/domains/osb/11.1.1.4/cluster/data/osb2/FolderName/Filename.txt to be processed was not found or not available or has no content Please make sure that the file exists in the specified directory.
    at oracle.tip.adapter.sa.impl.fw.wsif.jca.WSIFOperation_JCA.performOperation(WSIFOperation_JCA.java:662)
    at oracle.tip.adapter.sa.impl.fw.wsif.jca.WSIFOperation_JCA.executeOperation(WSIFOperation_JCA.java:353)
    at oracle.tip.adapter.sa.impl.fw.wsif.jca.WSIFOperation_JCA.executeRequestResponseOperation(WSIFOperation_JCA.java:312)
    at oracle.tip.adapter.sa.impl.JCABindingReferenceImpl.invokeWsifProvider(JCABindingReferenceImpl.java:350)
    at oracle.tip.adapter.sa.impl.JCABindingReferenceImpl.request(JCABindingReferenceImpl.java:253)
    ... 57 more
    Caused by: BINDING.JCA-11007
    No Data to process.
    No Data to process.
    File /root/oracle/domains/osb/11.1.1.4/cluster/data/osb2/FolderName/Filename.txt to be processed was not found or not available or has no content Please make sure that the file exists in the specified directory.
    at oracle.tip.adapter.file.outbound.FileReader.readFile(FileReader.java:277)
    at oracle.tip.adapter.file.outbound.FileReader.executeFileRead(FileReader.java:181)
    at oracle.tip.adapter.file.outbound.FileInteraction.executeFileRead(FileInteraction.java:331)
    at oracle.tip.adapter.file.outbound.FileInteraction.execute(FileInteraction.java:395)
    at oracle.tip.adapter.sa.impl.fw.wsif.jca.WSIFOperation_JCA.performOperation(WSIFOperation_JCA.java:529)
    ... 61 more
    Edited by: 842347 on Jul 6, 2011 3:11 AM

    I face the same issue and I have given all permissions to the folder for OS user.
    Because of this error my server is not starting up . Is there any way I can undeploy this composite to get my server running.
    I cant do this from EM because SOA server is failing to start up.
    I have tried removing it from $DOMAIN_HOME/deployed-composites but still when i try restarting the soa server the composite comes up there. Do we need to delete the entry some where else too. Kindly help.
    Thanks,
    Sri.

  • Synchronous File Read on Invoke Problem

    I am trying to invoke file adapter to read the file once(Synchronous File Read) as described in Bpeltechadapter guide.
    Read about Synchronous File Reading Capability here download.oracle.com/otndocs/products/bpel/bpeltechadp.pdf
    Also read this: Re: Help! Three questions about FileAdapater. .
    I get this process generation failed when i try to build it. The Empty_msg in inputvariable of invoke works but problem is with Charges_msg in output variable.
    I am sure its something to do with ns but not getting it to work.
    PL_FileInbound.WSDL code*********************
    <definitions
    name="PL_FileInbound"
    targetNamespace="http://xmlns.oracle.com/pcbpel/adapter/file/PL_FileInbound/"
    xmlns="http://schemas.xmlsoap.org/wsdl/"
    xmlns:tns="http://xmlns.oracle.com/pcbpel/adapter/file/PL_FileInbound/"
    xmlns:plt="http://schemas.xmlsoap.org/ws/2003/05/partner-link/"
    xmlns:jca="http://xmlns.oracle.com/pcbpel/wsdl/jca/"
    xmlns:imp1="http://TargetNamespace.com/FA_ReadFile"
    xmlns:hdr="http://xmlns.oracle.com/pcbpel/adapter/file/"
    >
    <import namespace="http://xmlns.oracle.com/pcbpel/adapter/file/" location="fileAdapterOutboundHeader.wsdl"/>
    <types>
    <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://xmlns.oracle.com/pcbpel/adapter/file/PL_FileInbound/">
    <import namespace="http://TargetNamespace.com/FA_ReadFile" schemaLocation="PipeDelimitedNIX_Charges.xsd" />
    <element name="empty"><complexType/></element>
    </schema>
    </types>
    <message name="Chargesheet_msg">
    <part name="Chargesheet" element="impl:Chargesheet"/>
    </message>
    <message name="Empty_msg">
    <part name="Empty" element="tns:empty"/>
    </message>
    <portType name="SynchronousRead_ptt">
    <operation name="SynchronousRead">
    <input message="tns:Empty_msg"/>
    <output message="tns:Chargesheet_msg"/>
    </operation>
    </portType>
    <binding name="SynchronousRead_binding" type="tns:SynchronousRead_ptt">
    <jca:binding />
    <operation name="SynchronousRead">
    <jca:operation
    PhysicalDirectory="C:\Incoming"
    InteractionSpec="oracle.tip.adapter.file.outbound.FileReadInteractionSpec"
    FileName="abcl.txt"
    DeleteFile="false"
    OpaqueSchema="false">
    </jca:operation>
    <input>
    <jca:header message="hdr:OutboundHeader_msg" part="outboundHeader"/>
    </input>
    </operation>
    </binding>
    <service name="PL_FileInbound">
    <port name="SynchronousRead_pt" binding="tns:SynchronousRead_binding">
    <jca:address location="eis/FileAdapter" />
    </port>
    </service>
    <plt:partnerLinkType name="Read_plt" >
    <plt:role name="Read_role" >
    <plt:portType name="tns:SynchronousRead_ptt" />
    </plt:role>
    </plt:partnerLinkType>
    </definitions>
    BPEL Source ******************************************
    <!--
    // Oracle JDeveloper BPEL Designer
    // Created: Sat Apr 29 16:52:43 CDT 2006
    // Author: dpatel
    // Purpose: Synchronous BPEL Process
    -->
    <process name="SynchronousFileRead"
    targetNamespace="http://xmlns.oracle.com/SynchronousFileRead"
    xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/"
    xmlns:bpws="http://schemas.xmlsoap.org/ws/2003/03/business-process/"
    xmlns:xp20="http://www.oracle.com/XSL/Transform/java/oracle.tip.pc.services.functions.Xpath20"
    xmlns:ns1="http://xmlns.oracle.com/pcbpel/adapter/file/PL_FileInbound/"
    xmlns:ldap="http://schemas.oracle.com/xpath/extension/ldap"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:bpelx="http://schemas.oracle.com/bpel/extension"
    xmlns:client="http://xmlns.oracle.com/SynchronousFileRead"
    xmlns:ora="http://schemas.oracle.com/xpath/extension"
    xmlns:orcl="http://www.oracle.com/XSL/Transform/java/oracle.tip.pc.services.functions.ExtFunc">
    <!-- ================================================================= -->
    <!-- PARTNERLINKS -->
    <!-- List of services participating in this BPEL process -->
    <!-- ================================================================= -->
    <partnerLinks>
    <!--
    The 'client' role represents the requester of this service. It is
    used for callback. The location and correlation information associated
    with the client role are automatically set using WS-Addressing.
    -->
    <partnerLink name="client" partnerLinkType="client:SynchronousFileRead"
    myRole="SynchronousFileReadProvider"/>
    <partnerLink myRole="Read_role" name="PL_FileInbound"
    partnerRole="Read_role" partnerLinkType="ns1:Read_plt"/>
    </partnerLinks>
    <!-- ================================================================= -->
    <!-- VARIABLES -->
    <!-- List of messages and XML documents used within this BPEL process -->
    <!-- ================================================================= -->
    <variables>
    <!-- Reference to the message passed as input during initiation -->
    <variable name="inputVariable"
    messageType="client:SynchronousFileReadRequestMessage"/>
    <!--
    Reference to the message that will be returned to the requester
    -->
    <variable name="outputVariable"
    messageType="client:SynchronousFileReadResponseMessage"/>
    <variable name="Invoke_1_SynchronousRead_InputVariable"
    messageType="ns1:Empty_msg"/>
    <variable name="Invoke_1_SynchronousRead_OutputVariable"
    messageType="ns1:Chargesheet_msg"/>
    </variables>
    <!-- ================================================================= -->
    <!-- ORCHESTRATION LOGIC -->
    <!-- Set of activities coordinating the flow of messages across the -->
    <!-- services integrated within this business process -->
    <!-- ================================================================= -->
    <sequence name="main">
    <!-- Receive input from requestor.
    Note: This maps to operation defined in SynchronousFileRead.wsdl
    -->
    <receive name="receiveInput" partnerLink="client"
    portType="client:SynchronousFileRead" operation="process"
    variable="inputVariable" createInstance="yes"/>
    <!-- Generate reply to synchronous request -->
    <invoke name="Invoke_1" partnerLink="PL_FileInbound"
    portType="ns1:SynchronousRead_ptt" operation="SynchronousRead"
    inputVariable="Invoke_1_SynchronousRead_InputVariable"
    outputVariable="Invoke_1_SynchronousRead_OutputVariable"/>
    <!--outputVariable="Invoke_1_SynchronousRead_OutputVariable"-->
    <reply name="replyOutput" partnerLink="client"
    portType="client:SynchronousFileRead" operation="process"
    variable="outputVariable"/>
    </sequence>
    </process>
    I would really appreciate your help here.

    I face the same issue and I have given all permissions to the folder for OS user.
    Because of this error my server is not starting up . Is there any way I can undeploy this composite to get my server running.
    I cant do this from EM because SOA server is failing to start up.
    I have tried removing it from $DOMAIN_HOME/deployed-composites but still when i try restarting the soa server the composite comes up there. Do we need to delete the entry some where else too. Kindly help.
    Thanks,
    Sri.

  • Synchronous file adapter sender side configuration in sap pi

    Hi Experts
    synchronous file adapter sender side configuration in sap pi
    can you explain any one tell me step by step procedure?
    Regards
    Sagar

    Hi,
    You can use RequestResponseBean in the sender file adapter module .
    RequestResponseBean (SAP Library - SAP Exchange Infrastructure)
    Request/Response Bean for IDOC_AAE adapter
    Instead of IDOC_AAE adapter you can use FILE adapter.
    Regards,

  • How shall I use my IMac and MacBookPro, with synchronized files

    Hi, how shall I use my IMac and MacBookPro, with synchronized files? I used to work at home and office with those to machines and finally always have different version of my documents. Is there any dispositive that I should use, where all my files are moving with me? os there is something to synchronized the computers using WiFi or bluetooth?

    The following has instructions: OS X Mavericks: Share your Internet connection

  • Why when I'm trying to reinstall my OS, Tiger 10.4, at 56% at files writing, it shuts off?

    Please someone, help me,
    Why when I'm trying to reinstall my OS, Tiger 10.4, at 56% of the installation, at files writing, it keeps on shutting off?

    Does it feel extra hot on top?
    Are you reinstalling because you had several problems? If so what were they?
    "Try Disk Utility
    1. Insert the Mac OS X Install disc, then restart the computer while holding the C key.
    2. When your computer finishes starting up from the disc, choose Disk Utility from the Installer menu at top of the screen. (In Mac OS X 10.4 or later, you must select your language first.)
    *Important: Do not click Continue in the first screen of the Installer. If you do, you must restart from the disc again to access Disk Utility.*
    3. Click the First Aid tab.
    4. Select your Mac OS X volume.
    5. Click Repair Disk, (not Repair Permissions). Disk Utility checks and repairs the disk."
    http://docs.info.apple.com/article.html?artnum=106214

  • File Writing with JSP

    Hi all,
    I'm creating a simple app that gets form data and populates it to a file. I want to make sure that each instance (thread?) is able to write to the file and not throw an exception since the file may be currently open by another instance of the jsp. Now I did basic thread programming in C++ a long time ago, so I'm aware of thread waiting conceptually, but I'm not familiar with the java implementation. Can someone show me some basic syntax on how I would go in essentially putting a lock on the file writing portion of the code.
    Thanx much

    I disagree that you should override anything in Threa, especiially the sleep method.
    What you should do is handle the file writing in a producer/consumer fashion. Have a single class that extends Runnable be the consumer. It handles all the file writing issues. You will run this in its own thread.
    Your JSPs (or other threads) fill in a collection, or some other holder, which informs the consumer to write to the file.
    As a brief example, this is a mini logger type of program. I use a class (LogCenter) to log data put in it from other sources (client1 and client2). For the sake of using newer API, I make use of the java.util.concurrent.BlockingQueue (and java.util.concurrent.LinkedBlockingQueue) to make a thread-safe collection and reporting system for text to come in and out of the logger.
    Note, this is far from production. Just something I whipped up when playing with blocking queues a while ago...
    package net.thelukes.steven.thread.test;
    import java.io.PrintWriter;
    import java.util.concurrent.BlockingQueue;
    import java.util.concurrent.LinkedBlockingQueue;
    public class LoggingCenter implements Runnable {
      private PrintWriter output;
      private BlockingQueue<String> toPrint;
      public LoggingCenter() {
        toPrint = new LinkedBlockingQueue<String>(10);
      public void setOutput(PrintWriter pw) {
        if (pw == null)  {
          if (output != null)
            return; //do not replace output with null
          else //pw is null and output is null
            throw new IllegalArgumentException("Ouput PrintWriter must not be NULL");
        else {
          if (output != null) closeOutput(); //if output exists already, close it.
          output = pw;
      public void log(String text) {
        boolean added = false;
        while (!added)
          try {
            toPrint.put(text);
            added=true;
          } catch (InterruptedException ie) {
            ie.printStackTrace();
            try { Thread.sleep(300L); }
            catch (InterruptedException ie2) { ie2.printStackTrace();}
      public void run() {
        try {
          while (true) {
            printLn(toPrint.take());
        } catch (InterruptedException ie) {ie.printStackTrace();}
      private void closeOutput() {
        output.flush();
        output.close();
      private void printLn(String text) {
        if (output == null)
          throw new IllegalStateException
            ("The Output PrintWriter must be set before any output can occur.");
        output.println(text);
        output.flush();
    package net.thelukes.steven.thread.test;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    public class LoggingTest {
      public static void main(String[] args) throws IOException {
        PrintWriter output = new PrintWriter(
          new FileWriter(new File("log.txt")));
        //PrintWriter output = new PrintWriter(System.out, true);
        final LoggingCenter logger = new LoggingCenter();
        logger.setOutput(output);
        Thread t = new Thread(logger);
        t.start();
        Thread client1 = new Thread(
            new Runnable() {
              public void run() {
                while (true) {
                  logger.log("Client 1: "+System.currentTimeMillis());
                  try {
                    Thread.sleep(1250L);
                  } catch (InterruptedException e) {}
        Thread client2 = new Thread(
            new Runnable() {
              public void run() {
                while (true) {
                  logger.log("Client 2: "+System.currentTimeMillis());
                  try {
                    Thread.sleep(2500L);
                  } catch (InterruptedException e) {}
        client1.start();
        client2.start();
    }

  • File writing permissions??

    is there any file writing permissions in jsp?
    i can create folders with my code on my localhost Tomcat 5.5.
    but now i have a webhost which has Tomcat 5.0...with my same jsp code i can see the content of my folders but cannot create any new folders under wwwroot or somewhere else on my webhost...
    so i am thinking if it is related with permissions or something like that?please show me a way
    thanks
    Burak

    my host admin responded;
    Hi,
    We can enable write permission, but this will put you in high security risk in tomcat shared hosting, as any other user also from his jsp/servlet script can write anything into your directory or delete file.
    Now what you think?what i want to do is i have a photo album site...users can create their own folders and upload their photo albums...but this users' main folder must be somewhere in a protected area that users musnt directly link to this photos...like before wwwroot or after WEB-INF folder...where can it be?
    please help me in this subject..need really help..
    thanks

  • Does UTL_FIL utility supports file writing in to remote Host ??

    Hi,
    I am checking the possibility with UTL_FIL utility whether supports file writing in to remote Host. My database is on different server from UNIX server but i want to make use of Oracle directory objects or UTL_FILES functions to be able to write files directly from Oracle to remote UNIX server.
    Is this possible ?
    Thanks
    Anand

    UTL_FILE, and any other PL/SQL package running on the database server, can only access objects that the database server has access to. Unless the remote Unix server's file system is mounted from the Oracle server's file system, UTL_FILE would be unable to create a file there.
    Now, there may well be alternateives. For example, you could generate the file locally and FTP the file to the remote Unix server, assuming the remote Unix server is running a FTP server.
    Justin

  • Synchronized File

    i want write synchronized File Class, it extends File Class, it has
    two new method "readfile"and"deletefile",
    but deleting file must be afer reading file , if current directory has no
    file, any of the two method is not allow to run.
    anyone has idea?

    Try this...
    public synchronized void readFile(){
    boolean check = checkFileExists();
    if(!check){           
    return;
    doReadFile();
    public synchronized void deleteFile(){
    boolean check = checkFileExists();
    if(!check){           
    return;
    doReadFile();
    doDeleteFile();
    // Below are not thread safe
    // called only from either readFile() or deleteFile()
    private boolean checkFileExists(){
    // returns true if file exists, false otherwise
    // called only from either readFile() or deleteFile()
    private void doReadFile(){
    // Read the file
    // called only from either readFile() or deleteFile()
    private void doDeleteFile(){
    // Delete the file
    Hope this helps

  • FileLock vs. synchronized(file)

    Hi,
    In a web app I have a servlet that writes several files to disk if they don't already exist--a cache. I have enclosed the write operation in a synchronized block like the following to prevent collisions:
    File outFile = new File("file.txt");
    FileOutputStream out;
    synchronized (outFile) {
    out = new FileOutputStream(outFile);
    [write stuff to stream];
    out.close();
    It dawned on me that maybe I should be locking the file instead of using the synchronized block, however, no other application, or servlet for that matter, would ever write these files. Also, the way my web app is structured, it's impossible that another servlet would try to read the files unless they already have been written (otherwise the writing servlet is invoked and the worst case is that the second, slightly later thread, re-writes the exact same file--not really a problem).
    What are the considerations?
    At what moment would a test for the existence of the file from another thread return true--at the completion of "out.close();"? I hope so, or that will be a problem for threads trying to read the incomplete file.
    Thanks.

    Hiya. What I would do is have a counter
    int read_access_count; // This would be 0 or higher.
    boolean file_blocked // true or false
    Every time someone opens the file for reading the read_access_count gets incremented by one, and when someone finishes reading the file it goes down by one.
    So when someone wants to write to the file they first make sure read_access_count is 0. If read_access_count is say for example 5, then the thread marks the file_blocked as true and waits for the read_access_count to go to 0. Once 0 it opens the file and writes to it. Then it finishes and sets file_blocked to false. Now all the files waiting to read can read and increment read_access_count by one again.
    A thread that wants to read the file must check file_blocked to make sure it isn't true. This prevents reading incomplete files and all sorts of situations.
    And you are correct to use synchronization in the methods controlling these variables, read_access_count and file_blocked.

  • Synchronous File Read in a High Availability Scenario

    Hi All,
    We have Oracle SOA Suite 10.1.3.4 which is a High Availability instance. As per Oracle's doc Id 730515.1 we have edited the bpel.xml file with the property for Adapter cluster only in the cases where a BPEL process was polling for a file and instantiating the process to avoid the race around condition.
    However, we have not made this change for BPEL process which contain a synchronous read. As I understand, such processes(which contain a synchronous read) are already instantiated before the file is read and hence the race around scenario does not exist.
    Please correct me if my understanding is incorrect. Also, will I need to make any changes for the process in such a case.
    Thanks and regards.

    Hi Marcio,
    The Oracle Document I mentioned available on Metalink states:
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    Applies to:
    Oracle9i AS Integration Platform - Version: 10.1.3.3
    Information in this document applies to any platform.
    Goal
    You have installed BPEL cluster. However, you expect that adapters doing the same work on two different nodes might encounter a race condition. So you would like to configure a singleton adapter. This note describes how to do it.
    Solution
    1. In collaxa-config.xml change from
    <property id="clusterName">
    <name>Cluster Id</name>
    <value>machine_name:port</value>
    <comment>
    to
    <property id="clusterName">
    <name>Cluster Id</name>
    <value>bpelCluster</value>
    <comment>
    The value: 'bpelCluster'
    can be anything but has to be the same on both instances.
    2. Multicast host and port in jgroups-properties.xml have to be same on both instances.
    3. To enable a singleton adapter add the following property in bpel.xml of the process using the adapter in question:
    <property name="clusterGroupId">adapterCluster</property>
    where the actual value - 'adapterCluster' in this case can be anything but has to be different from the value used before (bpelCluster) when configuring BPEL cluster. The reason for that is that BPEL engine and an adapter will use different communication channels.
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    I would Like to know if this is applicable incase we have a BPEL Process which contains a synchronous read.
    Thanks and Regards.

  • Synchronous File- Soap scenario with fault message

    Hi!
    I have a File to Soap synchronous scenario.
    All is right when no exception is returned by the web service.
    I want to use fault messages to catch thoses exceptions, so I have added fault message in message interfaces and in the mapping program in the interface mapping.
    Now, when the web service return an exception like :
    <soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
       <soap-env:Body>
          <soap-env:Fault>
             <faultcode>soap-env:Client</faultcode>
             <faultstring xml:lang="en">NOT_CREATED</faultstring>
             <detail>
                <n0:Z_WS_CREATE_WAGON.Exception xmlns:n0="urn:sap-com:document:sap:rfc:functions">
                   <Name>NOT_CREATED</Name>
                   <Text> does not have packaging material type and is therefore not a pack.mat.</Text>
                   <Message>
                      <ID>HUSELECT</ID>
                      <Number>041</Number>
                   </Message>
                </n0:Z_WS_CREATE_WAGON.Exception>
             </detail>
          </soap-env:Fault>
       </soap-env:Body>
    </soap-env:Envelope>
    I get the following error :
    <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="1">
       <SAP:Category>XIServer</SAP:Category>
       <SAP:Code area="MAPPING">NO_MAPPINGPROGRAM_FOUND</SAP:Code>
       <SAP:P1>http://www.arcelormittal.com/radis/rad IM_RAD_to_ZWsCreateWagon</SAP:P1>
       <SAP:P2 />
       <SAP:P3 />
       <SAP:P4 />
       <SAP:AdditionalText />
       <SAP:ApplicationFaultMessage namespace="" />
       <SAP:Stack>Interface mapping http://www.arcelormittal.com/radis/rad IM_RAD_to_ZWsCreateWagon does not exist in runtime cache</SAP:Stack>
       <SAP:Retry>N</SAP:Retry>
    </SAP:Error>
    My mapping program for fault message is well defined (I tested it with the exception message received from the web service).
    I have also refresh caches, but without success...
    Can anyone help me ?
    Thanks in advance,
    Laurence

    Hey Laurence,
    A File adapter is aysnchronous u cant use for synchrous because it cant acknwlodge the response it gets or itt sends.
    regarding two asynchoronus
    1. file to SOAP asychn.
    2. triggger the second one if SOAP has exception then pass the error from SOAP to New File.
    using BPM we have to use Transportion level acknowledgments
    please reward points if it helps
    Regards
    Sreeram.G.Reddy

  • File Writing - Missing some files without any error

    I am executing the following code:
    String message = XMLHelper.getDocumentXML(_doc);
         File outFile = getFile();
         RandomAccessFile raf = new RandomAccessFile(outFile, "rw");
         FileChannel channel = raf.getChannel();
         ByteBuffer buf = ByteBuffer.allocateDirect(19600);
         buf.clear();
         buf.put(message.getBytes());
         buf.flip();
         channel.write(buf);
         channel.close();
         raf.close();
    This code is in a loop and it must write a lot of files. I am trying with 426 but thje problem i have is that many times i do get 425 files insted of 426 or some other times i do get 425 files. No error or exception is thrown. Other times id do get my 426 files.
    The problem increase when i process like 50000 files, the quantity it is supposed to treat.
    Please can any body tell me what happen with the missing files? How can i detect what is happening?
    Thank you very much to any one who can help me with this extrange error

    Hard to tell based on the info you supplied. How are you generating filenames? Are you accidently writing over an existing ouput file? Can you post more code, speciifcally the loop code around the code below?

Maybe you are looking for