/********************************************************* begin of preamble
**
** Copyright (C) 2003-2010 Software- und Organisations-Service GmbH.
** All rights reserved.
**
** This file may be used under the terms of either the
**
** GNU General Public License version 2.0 (GPL)
**
** as published by the Free Software Foundation
** http://www.gnu.org/licenses/gpl-2.0.txt and appearing in the file
** LICENSE.GPL included in the packaging of this file.
**
** or the
**
** Agreement for Purchase and Licensing
**
** as offered by Software- und Organisations-Service GmbH
** in the respective terms of supply that ship with this file.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
** IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
** THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
** PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
** POSSIBILITY OF SUCH DAMAGE.
********************************************************** end of preamble*/
package com.sos.JSHelper.io.Files;
/**
* \class JSFile
*
* \brief JSFile - Wrapper f�r die Klasse java.io.File
*
* \section JSFile_intro_sec Introduction
* Von dieser Klasse werden eine Reihe von anderen, spezielleren Klassen abgeleitet.
* Diese Klasse stellt insbesondere die
*
* \li Listener- und
* \li eine Archiver-Funktionalit�t
*
* sowie
*
* \li eine Pushback-Funktion
* \li streamed-io
* \li dump-utilities
* \li Text-Ersetzungsfunktionen
* \li diverse Statistiken
*
* zur Verf�gung.
*
* \subsection JSFile_Listener Listener-Funktionalit�t
*
* \subsection JSFile_Archiver Archiver-Funktionalit�t
*
* \subsection JSFile_Pushback Pushback-Funktionalit�t
*
* \subsection JSFile_streamed-io Streamed-IO
*
* \subsection JSFile_dumper Dump-Utilities
*
* \subsection JSFile_Textreplacing Text-Ersetzungsfunktionen
*
* \subsection JSFile_Statistiken Statistiken
*
* \section JSFile_samples Some Samples
*
* \code
* .... code goes here ...
* \endcode
*
* \todo Funktionalit�t f�r das Schreiben �ber tempor�re Datei-Namen implementieren: beim beenden den
* Namen dann auf permanent �ndern (also file.x~ beschreiben und im Close auf file.x umbenennen).
*
* <p style="text-align:center">
* <br />---------------------------------------------------------------------------
* <br /> APL/Software GmbH - Berlin
* <br />##### generated by ClaviusXPress (http://www.sos-berlin.com) #########
* <br />Mittwoch, 22. Oktober 2008, sgx2343 (sgx2343)
* <br />---------------------------------------------------------------------------
* </p>
* \author sgx2343
* @version $Id: JSFile.java 14731 2011-07-05 20:50:42Z sos $0.9
* \see JSListener
* \see IJSArchiver
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import org.apache.log4j.Logger;
import com.sos.JSHelper.Archiver.IJSArchiver;
import com.sos.JSHelper.Archiver.JSArchiver;
import com.sos.JSHelper.Archiver.JSArchiverOptions;
import com.sos.JSHelper.DataElements.JSDataElementDate;
import com.sos.JSHelper.DataElements.JSDataElementTimeStampISO;
import com.sos.JSHelper.Exceptions.JobSchedulerException;
import com.sos.JSHelper.Listener.JSListener;
import com.sos.JSHelper.Options.SOSOptionFolderName;
public class JSFile extends java.io.File implements JSListener, IJSArchiver {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(JSFile.class);
private final String conClassName = "JSFile";
private static final long serialVersionUID = -1430552107244301112L;
public SOSOptionFolderName BackupFolderName = new SOSOptionFolderName(null, "BackupFolderName", "Name of Folder for Backup of this file", "", "",
false);
protected String strFileName;
protected File fleFile;
protected FileReader fleFileReader;
protected BufferedReader bufReader;
private StringBuffer strRecordBuffer;
private String strPushBackBuffer = "";
protected long lngNoOfLinesRead = 0;
private long lngNoOfLinesWritten = 0;
private long lngNoOfCharsInBuffer = 0;
private String strCharSet4InputFile = null; // spezifiziert den Zeichensatz wie er in der
// eingabedatei verwendet wird, z.B. UTF-8
private RandomAccessFile randomFile = null; // Used for FileLocking
private FileLock fleLock = null;
private boolean flgFileIsLocked = false;
private boolean flgIsExclusive = false;
private JSFile fleExclusiveFile = null;
private String strExclusiveFootPrint = "";
// private long lngBytesCopies = 0;
public JSFile(final String pstrFileAndPathName) {
super(pstrFileAndPathName);
strFileName = pstrFileAndPathName;
doInit();
}
public JSFile(final File parent, final String child) {
super(parent, child);
// - <remark who='EQALS' when='Montag, 14. September 2009' id='Fehlerkorrektur' >
/**
* \change Montag, 14. September 2009 EQALS Fehlerkorrektur
* Fehlerkorrektur
*/
// - <oldcode>
// strFileName = child;
// - </oldcode>
// - <newcode>
strFileName = getAbsolutePath();
// - </newcode>
// - </remark> <!-- id=<Fehlerkorrektur> -->
doInit();
}
public JSFile(final String parent, final String child) {
super(parent, child);
// - <remark who='EQALS' when='Montag, 14. September 2009' id='Fehlerkorrektur' >
/**
* \change Montag, 14. September 2009 EQALS Fehlerkorrektur
* Fehlerkorrektur
*/
// - <oldcode>
// strFileName = child;
// - </oldcode>
// - <newcode>
strFileName = getAbsolutePath();
// - </newcode>
// - </remark> <!-- id=<Fehlerkorrektur> -->
doInit();
}
/**
*
* \brief JSFile
*
* \details
*
* @param pobjUri
* @throws MalformedURLException
*/
public JSFile(final URI pobjUri) throws MalformedURLException {
super(pobjUri);
strFileName = pobjUri.toURL().getFile();
doInit();
}
/**
*
* \brief doInit - Initialisierung der Klasse
*
* \details
* Wird im Konstruktur explizit gerufen.
*
* \return void
*
*/
private void doInit() {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::FileName";
try {
fleFile = this;
}
catch (final Exception e) {
logger.error("doInit()", e); //$NON-NLS-1$
}
}
/**
*
* \brief Reader - liefert eine BufferedReader-Instanz f�r die Datei
*
* \details
* \return BufferedReader
* @throws Exception
*/
protected BufferedReader Reader() throws IOException {
final String conMethodName = conClassName + "::Reader";
if (bufReader == null) {
if (this.checkExclusiveDeny() == true) {
throw new IOException(String.format("%1$s - Exclusive usage of file %1$s not possible. User is %$2s", conMethodName, strFileName));
}
if (randomFile != null) {
fleFileReader = new FileReader(randomFile.getFD());
}
else {
fleFileReader = new FileReader(this);
}
// - <remark who='eqbfd' when='Dienstag, 27. Oktober 2009' id='Unicode' >
// - <oldcode>
// bufReader = new BufferedReader(fleFileReader);
// - </oldcode>
// - <newcode>
if (strCharSet4InputFile == null) {
bufReader = new BufferedReader(fleFileReader);
}
else {
bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(this), strCharSet4InputFile));
}
// - </newcode>
// - </remark> <!-- id=<Unicode> -->
/**
* \change Dienstag, 27. Oktober 2009 eqbfd Unicode
* Unicode lesen k�nnen
*/
// if (strFileName.endsWith(".gz")) {
// bufReader = new java.util.zip.GZIPInputStream(bufReader);
// }
message(conMethodName + ": " + "File opened for read: " + strFileName + "(CharSet:" + strCharSet4InputFile + ")");
}
return bufReader;
}
// - <remark who='eqbfd' when='Dienstag, 27. Oktober 2009' id='Unicode' >
// - <oldcode>
// - </oldcode>
// - <newcode>
/**
* \change Dienstag, 27. Oktober 2009 eqbfd Unicode
* Unicode lesen k�nnen
*/
/**
*
* \brief CharSet4InputFile
*
* \details
* If an IDoc-File is written using Unicode, this Option must be set to "UTF-8" to ensure, that the content of the file
* is properly processed, e.g. that unicode-character-sequences are recognized.
*
* If the Root-Segment is marked with EDI_DC40_U instead of EDI_DC40, the IDoc is written by using Unicode.
*
* \return void
*
* @param pstrCharSet4InputFile
*/
public void CharSet4InputFile(final String pstrCharSet4InputFile) {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::CharSet4InputFile";
strCharSet4InputFile = pstrCharSet4InputFile;
// return void;
} // public void CharSet4InputFile
/**
*
* \brief CharSet4InputFile - Define the character set for the file
*
* \details
*
* \return String
*
* @return
*/
public String CharSet4InputFile() {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::CharSet4InputFile";
return strCharSet4InputFile;
} // public String CharSet4InputFile
// - </newcode>
// - </remark> <!-- id=<Unicode> -->
/**
* \brief CopyTimeStamp - Copy the File with a new filename extended by a time-stamp
*
* \details
* Kopiert die Datei mit einem um einen Zeitstempel erweiterten Dateinamen.
*
* \return String - der Dateiname mit dem Zeitstempel
*
* \see {@link #getTimeStamp()}
*/
public String CopyTimeStamp() throws Exception {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::CopyTimeStamp";
try {
String strNewFileName = null;
final String strTimeStamp = getTimeStamp();
final int i = strFileName.lastIndexOf(".");
if (i > 0) {
strNewFileName = strFileName.substring(0, i) + "-" + strTimeStamp + strFileName.substring(i);
}
else {
strNewFileName = strFileName + "-" + strTimeStamp;
}
copy(strNewFileName);
return strNewFileName;
}
catch (final Exception e) {
throw e; // new Exception("Error in [" + conClassName + "::" + conMethodName + "]: " + e);
//
}
} // public void CopyTimeStamp ()
/**
*
* \brief CreateBackup
*
* \details
*
* \return String
*
* @throws Exception
*/
public String CreateBackup() throws Exception {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::CreateBackup";
String strExtension4BackupFile = ".bak";
return this.doCreateBackUp(strExtension4BackupFile);
} // private String CreateBackup
/**
*
* \brief CreateBackup
*
* \details
*
* \return String
*
* @param pstrExtension4BackupFile
* @throws Exception
*/
public String CreateBackup(String pstrExtension4BackupFile) throws Exception {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::CreateBackup";
return this.doCreateBackUp(pstrExtension4BackupFile);
} // private String CreateBackup
private String doCreateBackUp(final String pstrExtension4BackupFileName) throws Exception {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::doCreateBackUp";
String strNewFileName = "";
String strBackupFolderName = this.BackupFolderName.Value();
if (strBackupFolderName.length() > 0) {
strNewFileName = strBackupFolderName + this.getName() + pstrExtension4BackupFileName;
}
else {
strNewFileName = this.strFileName + pstrExtension4BackupFileName;
}
copy(strNewFileName);
return strNewFileName;
} // private String doCreateBackUp
/**
*
* \brief getTimeStamp - liefert einen Zeitstempel in der Form YYYY-MM-DD-HH-II-SS
*
* \details
* \return String
*
* @return
*/
private String getTimeStamp() {
// DateFormat dteF = DateFormat.getDateTimeInstance();
final Date now = new Date();
String strT = null;
// strT = dteF.format(now).toString();
// strT = strT.replace(":", "-");
// strT = strT.replace(".", "-");
// strT = strT.replace(" ", "-");
// strT = strT.substring(6,10) + strT.substring(2,5) + '-' + strT.substring(0,2) + strT.substring(10);
SimpleDateFormat formatter;
final Locale currentLocale = new Locale("de", "DE");
formatter = new SimpleDateFormat("yyyy-MM-dd-H-mm-ss", currentLocale);
strT = formatter.format(now);
return strT;
}
/**
* \brief move - move/rename actual file to new file
*
* \details
*/
public JSFile move(final String pstrNewFileName) throws Exception {
final String conMethodName = conClassName + "::move";
final JSFile RetVal = null;
try {
final File fleNewFile = new File(pstrNewFileName);
if (fleNewFile.exists()) {
// \TODO: SignalError if no overwrite is specified and the new file already exist
message(String.format("%1$s: File '%2$s' deleted before, because exist", conMethodName, fleNewFile.getAbsoluteFile()));
fleNewFile.delete();
}
copy(pstrNewFileName);
try {
delete();
message(String.format("%1$s: File '%2$s' deleted", conMethodName, getAbsoluteFile()));
}
catch (final Exception e) {
// TODO kopierte Datei wieder l�schen, weil sonst doppelt
SignalError(String.format("%1$s: delete not succesfull for file '%2$s'", conMethodName, getName()));
throw e;
}
}
catch (final Exception e) {
throw e;
}
// message (String.format("%1$s: File '%2$s' moved to '%3$s'.", conMethodName, this.getAbsoluteFile(), pstrNewFileName));
return RetVal;
} // public JSFile move ()
/**
*
* \brief RenameTimeStamp
*
* \details
*
* \return void
*
*/
public void RenameTimeStamp() {
// \todo coding erstellen
}
/**
*
* \brief MustExist - l�st eine Exception aus, wenn die Datei nicht existiert.
*
* \details
* \return void
*
* @throws Exception
*/
public void MustExist() throws Exception {
final String conMethodName = conClassName + "::MustExist";
if (!exists()) {
final String s = String.format("%1$s: file '%2$s' does not exist", conMethodName, strFileName);
message(s);
throw new Exception(s);
}
}
private FileWriter fleFileWriter = null;
protected BufferedWriter bufWriter = null;
/**
*
* \brief Writer - liefert eine BufferedWriter-Instanz f�r die Datei
*
* \details
* \return BufferedWriter
*
* @return
* @throws IOException
*/
protected BufferedWriter Writer() throws IOException {
final String conMethodName = conClassName + "::Writer";
if (bufWriter == null) {
if (this.checkExclusiveDeny() == true) {
throw new IOException(String.format("%1$s - Exclusive usage of file %2$s not possible. User is %3$s", conMethodName, strFileName,
strExclusiveFootPrint));
}
fleFileWriter = new FileWriter(this);
// - <remark who='eqbfd' when='Dienstag, 27. Oktober 2009' id='Unicode' >
// - <oldcode>
// bufWriter = new BufferedWriter(fleFileWriter);
// - </oldcode>
// - <newcode>
if (strCharSet4InputFile == null) {
bufWriter = new BufferedWriter(fleFileWriter);
message(conMethodName + ": " + "File opened for write: " + strFileName);
}
else {
bufWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(this), strCharSet4InputFile));
message(conMethodName + ": " + "File opened for write: '" + strFileName + "' with Charset: '" + strCharSet4InputFile + "'.");
}
// - </newcode>
// - </remark> <!-- id=<Unicode> -->
/**
* \change Dienstag, 27. Oktober 2009 eqbfd Unicode
* Unicode lesen k�nnen
*/
}
return bufWriter;
}
public boolean isExclusive() {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::isExclusive";
return flgIsExclusive;
} // private boolean isExclusive
/**
*
* \brief NewLine - LineBuffer flush
*
* \details
* \return JSFile
*
* @return
* @throws Exception
*/
public JSFile NewLine() throws Exception {
WriteLine("");
lngNoOfCharsInBuffer = 0;
return this;
}
/**
*
* \brief NoOfCharsInBuffer - Size of LineBuffer
*
* \details
* \return long - Number of Chars in Line-Buffer
*
*/
public long NoOfCharsInBuffer() {
return lngNoOfCharsInBuffer;
}
/**
*
* \brief OutChar - put out a single character to the file
*
* \details
* Without line end, use it as a stream-output buffer.
*
* \return JSFile
*
* @param pchrC
* @return
* @throws IOException
*/
public JSFile OutChar(final char pchrC) throws IOException {
bufWriter.write(pchrC);
lngNoOfCharsInBuffer++;
return this;
}
/**
*
* \brief OutString
*
* \details
* \return void
*
* @param pstrLine
* @throws Exception
*/
public void OutString(final String pstrLine) throws Exception {
if (bufWriter == null) {
Writer();
}
bufWriter.write(pstrLine);
lngNoOfCharsInBuffer += pstrLine.length();
}
/**
*
* \brief Write - see WriteLine
*
* \details
* Wrapper for the WriteLine Method
* \return void
*
* @param pstrLine
* @throws Exception
*/
public void Write(final String pstrLine) throws Exception {
WriteLine(pstrLine);
}
/**
*
* \brief WriteLine
*
* \details
* \code
private void TestWriteLine() throws IOException {
JSTextFile objF = new JSTextFile("C:/temp/HalloWelt.txt");
for (int i = 1; i <= 10; i++) {
objF.WriteLine("Hallo, Welt ...");
}
objF.close();
}
* \endcode
* \return void
*
* @param pstrLine
* @throws IOException
*/
public JSFile WriteLine(final String pstrLine) throws IOException {
if (bufWriter == null) {
Writer();
}
String strBuff = pstrLine + System.getProperty("line.separator");
if (randomFile == null) {
bufWriter.write(strBuff);
bufWriter.flush();
}
else {
// randomFile.seek(randomFile.length());
// randomFile.writeUTF(pstrLine + System.getProperty("line.separator"));
randomFile.writeBytes(strBuff);
}
lngNoOfLinesWritten++;
return this;
}
/**
*
* \brief WirteLine
*
* \details
*
* \return void
*
* @throws IOException
* @throws Exception
*/
// - <remark who='EQALS' when='Donnerstag, 17. September 2009' id='Fehlerkorrektur' >
/**
* \change Donnerstag, 17. September 2009 EQALS Fehlerkorrektur
* Fehlerkorrektur
*/
// - <oldcode>
// public void WriteLine() throws IOException {
// - </oldcode>
// - <newcode>
public void WriteLine() throws IOException, Exception {
// - </newcode>
// - </remark> <!-- id=<Fehlerkorrektur> -->
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::WriteLine";
WriteLine("");
} // public void WriteLine
/**
*
* \brief GetLine - get a single line from a file
*
* \details
* This Method is using the PushBackBuffer if needed.
*
* \return StringBuffer - the content of the line
*
* @return
*/
public StringBuffer GetLine() {
String strT;
StringBuffer strSB = new StringBuffer("");
try {
if (strPushBackBuffer.length() > 0) {
strSB.append(strPushBackBuffer);
strPushBackBuffer = "";
strRecordBuffer = strSB;
}
else {
// System.out.println ("Try to read a record...");
if (bufReader == null) {
Reader();
}
strT = bufReader.readLine();
if (strT != null) {
lngNoOfLinesRead++;
strSB = new StringBuffer(strT);
strRecordBuffer = strSB;
// System.out.println(strT);
}
else {
bufReader.close();
bufReader = null;
strSB = null;
}
}
}
catch (final Exception e) {
logger.error("GetLine()", e); //$NON-NLS-1$
strSB = null;
}
return strSB;
}
public void PushBack() {
strPushBackBuffer = strRecordBuffer.toString();
}
/**
*
* \brief copy - FileCopy actual to new file
*
* \details
* \return void
*
* @param pstrTargetFileName
* @throws Exception
*/
public void copy(final String pstrTargetFileName) throws Exception {
final String conMethodName = conClassName + "::copy";
final File infile = new File(strFileName);
if (!infile.getAbsoluteFile().exists()) {
SignalError(String.format("%1$s: File '%2$s' not exist. copy not possible", conMethodName, strFileName));
return;
}
final File outfile = new File(pstrTargetFileName);
if (infile.getCanonicalPath().equals(outfile.getCanonicalPath())) {
message(String.format("%3$s: File '%1$s' is equal to '%2$s'. copy is useless", strFileName, pstrTargetFileName, conMethodName));
return;
}
try {
final FileOutputStream out = new FileOutputStream(outfile);
try {
final FileInputStream in = new FileInputStream(infile);
ExecuteCopy(in, out);
}
catch (final FileNotFoundException e) {
SignalError(String.format("%1$s: File '%2$s' not exist. can not copy to '%3$s'", conMethodName, strFileName, pstrTargetFileName));
}
}
catch (final Exception e) {
SignalError(String.format("%1$s: copy not succesfull for file '%2$s' to '%3$s'", conMethodName, getName(), pstrTargetFileName));
}
finally {
//
}
message(String.format("%3$s: File '%1$s' copied to '%2$s'", strFileName, pstrTargetFileName, conMethodName));
}// public void copy(String pstrTargetFileName)
/**
*
* \brief ReplaceWith - Textersetzungen in der Datei durchf�hren
*
* \details
\code
private void replaceText () throws Exception {
String strFileName = "data/sample4write.csv";
JSCsvFile objCsvFile = new JSCsvFile(strFileName);
objCsvFile.dumpAscii(System.out);
objCsvFile.ReplaceWith("dadis.schering.de", "dadis.eu.schering.net");
objCsvFile.dumpAscii(System.out);
}
\endcode
* \return void
*
* @param strReplaceWhatAsRegEx
* @param strReplaceWith
* @throws Exception
*/
public void ReplaceWith(final String strReplaceWhatAsRegEx, final String strReplaceWith) throws Exception {
final String conMethodName = conClassName + "::ReplaceWith";
final File infile = fleFile;
if (!infile.exists()) {
SignalError(String.format("%1$s: File '%2$s' not exist. nothing to do", conMethodName, strFileName));
return;
}
final File fleTempfile = java.io.File.createTempFile("JSFile", ".tmp");
try {
FileInputStream in = new FileInputStream(infile);
FileOutputStream out = new FileOutputStream(fleTempfile);
ExecuteReplace(in, out, strReplaceWhatAsRegEx, strReplaceWith);
// \todo Datei erst umbenennen (mit Tilde) und erst nach dem Kopieren umbenennen
fleFile.delete();
in = new FileInputStream(fleTempfile);
out = new FileOutputStream(infile);
ExecuteCopy(in, out);
fleTempfile.delete();
}
catch (final FileNotFoundException e) {
SignalError(String.format("%1$s: File '%2$s' not exist. nothing to do", conMethodName, strFileName));
}
catch (final Exception e) {
SignalError(String.format("%1$s: replace not succesfull for file '%2$s' ", conMethodName, getName()));
}
message(String.format("%1$s: Replacing in File '%2$s' done ", conMethodName, strFileName));
} // public void ReplaceWith(String strReplaceWhatAsRegEx, String strReplaceWith)
private void ExecuteReplace(final FileInputStream in, final FileOutputStream out, final String strReplaceWhatAsRegEx, final String strReplaceWith)
throws IOException {
final int intBuffsize = 4096;
synchronized (in) {
synchronized (out) {
byte[] buffer = new byte[intBuffsize];
while (true) {
final int bytesRead = in.read(buffer);
if (bytesRead == -1) {
break;
}
if (bytesRead < intBuffsize) {
byte[] tmpB = new byte[bytesRead];
tmpB = buffer;
buffer = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++) {
buffer[i] = tmpB[i];
}
}
String strLine = new String(buffer);
strLine = strLine.replaceAll(strReplaceWhatAsRegEx, strReplaceWith);
byte[] outB = new byte[intBuffsize + strReplaceWith.length()];
outB = strLine.getBytes();
out.write(outB, 0, strLine.length());
} // while (true)
}
}
in.close();
out.close();
}
private long in2out(final FileInputStream in, final FileOutputStream out) throws IOException {
long lngBytesCopies = 0;
synchronized (in) {
synchronized (out) {
final byte[] buffer = new byte[256];
while (true) {
final int bytesRead = in.read(buffer);
if (bytesRead == -1) {
break;
}
out.write(buffer, 0, bytesRead);
lngBytesCopies += bytesRead;
}
}
}
return lngBytesCopies;
}
private long ExecuteCopyWOClose(final FileInputStream in, final FileOutputStream out) throws IOException {
return in2out(in, out);
}
private long ExecuteCopy(final FileInputStream in, final FileOutputStream out) throws IOException {
final long lngBytesCopied = in2out(in, out);
in.close();
out.close();
return lngBytesCopied;
}
/**
*
* \brief ExecuteCopy
*
* \details
*
* \return void
*
* @param in
* @param out
* @throws IOException
*/
private void ExecuteCopy(final FileInputStream in, final PrintStream out) throws IOException {
synchronized (in) {
synchronized (out) {
final byte[] buffer = new byte[1024];
while (true) {
final int bytesRead = in.read(buffer);
if (bytesRead == -1) {
break;
}
out.write(buffer, 0, bytesRead);
}
}
}
in.close();
// out.close();
}
/**
*
* \brief File2String
*
* \details
*
* \return String
*
* @return
*/
public String File2String() {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::File2String";
final String strT = getContent();
return strT;
} // public String File2String}
/**
*
* \brief getContent
*
* \details
*
* \return String
*
* @return
*/
public String getContent() {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::getContent ";
String strB = "";
FileInputStream fin = null;
int lngFileSize = 0;
try {
if (randomFile == null) {
fin = new FileInputStream(strFileName);
}
else {
fin = new FileInputStream(randomFile.getFD());
}
final byte[] buffer = new byte[4096];
while (true) {
final int bytesRead = fin.read(buffer);
if (bytesRead == -1) {
break;
}
lngFileSize += bytesRead;
strB = strB + new String(buffer);
}
}
catch (final IOException e) {
logger.error("getContent() - " + e, e); //$NON-NLS-1$
throw new JobSchedulerException("Error in JSFile", e);
}
finally {
try {
if (fin != null) {
fin.close();
}
}
catch (final IOException e) {
}
}
// final int i = strB.indexOf('\0');
// if (i > 0) {
final String strT = strB.substring(0, lngFileSize);
// strB = strT;
// }
return strT;
} // public String getContent
/**
*
* \brief dumpAscii - Dateiinhalt in ascii (Text) auf PrintStream kopieren
*
* \details
* \return void
*
* @param out
*/
public void dumpAscii(final PrintStream out) {
FileInputStream fin = null;
try {
fin = new FileInputStream(strFileName);
ExecuteCopy(fin, out);
}
catch (final IOException e) {
logger.error("dumpAscii(PrintStream) - " + e, e); //$NON-NLS-1$
}
finally {
try {
if (fin != null) {
fin.close();
}
}
catch (final IOException e) {
}
}
}
/**
*
* \brief dumpAscii - Dateiinhalt in ascii (Text) auf FileOutputStream kopieren
*
* \details
* \return void
*
* @param out
*/
public void dumpAscii(final FileOutputStream out) {
FileInputStream fin = null;
try {
fin = new FileInputStream(strFileName);
ExecuteCopy(fin, out);
}
catch (final IOException e) {
logger.error("dumpAscii(FileOutputStream) - " + e, e); //$NON-NLS-1$
}
finally {
try {
if (fin != null) {
fin.close();
}
}
catch (final IOException e) {
}
}
}
private final char[] charArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
/**
*
* \brief byte2String - bytes in String umsetzen
*
* \details
* \return String
*
* @param content
* @return
*/
public String byte2String(final byte[] content) {
final StringBuilder buffer = new StringBuilder(content.length * 2);
for (final byte element : content) {
buffer.append(charArray[(0xF0 & element) >> 4]);
buffer.append(charArray[(0xF & element)]);
}
return buffer.toString();
}
/**
*
* \brief dumpDecimal
*
* \details
* \return void
*
* @param filename
*/
public void dumpDecimal(final String filename) {
FileInputStream fin = null;
final byte[] buffer = new byte[16];
boolean end = false;
int bytesRead;
try {
fin = new FileInputStream(filename);
while (!end) {
bytesRead = 0;
while (bytesRead < buffer.length) {
final int r = fin.read(buffer, bytesRead, buffer.length - bytesRead);
if (r == -1) {
end = true;
break;
}
bytesRead += r;
}
for (int i = 0; i < bytesRead; i++) {
int dec = buffer[i];
if (dec < 0) {
dec = 256 + dec;
}
if (dec < 10) {
logger.debug("dumpDecimal(String) - 00" + dec + " "); //$NON-NLS-1$ //$NON-NLS-2$
}
else
if (dec < 100) {
logger.debug("dumpDecimal(String) - 0" + dec + " "); //$NON-NLS-1$ //$NON-NLS-2$
}
else {
logger.debug("dumpDecimal(String) - " + dec + " "); //$NON-NLS-1$ //$NON-NLS-2$
}
}
logger.debug("dumpDecimal(String)"); //$NON-NLS-1$
}
}
catch (final IOException e) {
logger.error("dumpDecimal(String) - " + e, e); //$NON-NLS-1$
}
finally {
try {
if (fin != null) {
fin.close();
}
}
catch (final IOException e) {
}
}
}
/**
*
* \brief dumpHex - Dateiinhalt in hexadezial auf PrintStream ausgeben
*
* \details
* \return void
*
* @param out
*/
public void dumpHex(final PrintStream out) {
FileInputStream fin = null;
final byte[] buffer = new byte[24];
boolean end = false;
int bytesRead;
try {
fin = new FileInputStream(strFileName);
while (!end) {
bytesRead = 0;
while (bytesRead < buffer.length) {
final int r = fin.read(buffer, bytesRead, buffer.length - bytesRead);
if (r == -1) {
end = true;
break;
}
bytesRead += r;
}
for (int i = 0; i < bytesRead; i++) {
int hex = buffer[i];
if (hex < 0) {
hex = 256 + hex;
}
if (hex >= 16) {
out.print(Integer.toHexString(hex) + " ");
}
else {
out.print("0" + Integer.toHexString(hex) + " ");
}
}
out.println();
}
}
catch (final IOException e) {
logger.error("dumpHex(PrintStream) - " + e, e); //$NON-NLS-1$
}
finally {
try {
if (fin != null) {
fin.close();
}
}
catch (final IOException e) {
}
}
}
/**
*
* \brief message
*
* \details
*
* \return
*
* @param pstrMsg
*/
public void message(final String pstrMsg) {
if (JSListener != null) {
JSListener.message(pstrMsg);
}
else {
logger.debug("message(String) - " + pstrMsg); //$NON-NLS-1$
}
}
private JSListener JSListener;
/**
*
* \brief registerMessageListener
*
* \details
*
* \return void
*
* @param l
*/
public void registerMessageListener(final JSListener l) {
JSListener = l;
}
/**
*
* \brief SignalAbort
*
* \details
*
* \return void
*
* @param strS
* @throws Exception
*/
public void SignalAbort(final String strS) throws Exception {
String strT = " ###ProgramAbort### ";
strT = strT + strS + strS;
message(strT);
throw new Exception(strT);
}
/**
*
* \brief SignalInfo
*
* \details
*
* \return void
*
* @param strS
* @throws Exception
*/
public void SignalInfo(final String strS) throws Exception {
message(strS);
}
/**
*
* \brief SignalError
*
* \details
*
* \return void
*
* @param strS
* @throws Exception
*/
public void SignalError(final String strS) throws Exception {
String strT = " ### Error ### ";
strT = strT + strS + strS;
message(strT);
throw new Exception(strT);
}
private JSArchiver objArchiver = null;
/**
*
* \brief getArchiver - liefert eine aktuelle Instanz der Archiver-Klasse
*
* \details
* liefert eine aktuelle Instanz der Archiver-Klasse.
* Falls keine existiert wird eine gestartet.
*
* \return
*
* @throws Exception
*/
public JSArchiver getArchiver() throws Exception {
if (objArchiver == null) {
objArchiver = new JSArchiver();
objArchiver.registerMessageListener(this);
objArchiver.Options().FileName(super.getAbsoluteFile().toString());
}
return objArchiver;
}
/**
*
* \brief getArchiver - liefert eine aktuelle Instanz der Archiver-Klasse
*
* \details
* liefert eine aktuelle Instanz der Archiver-Klasse.
* Falls keine existiert wird eine gestartet.
*
* \return
*
* @throws Exception
*/
public JSArchiver getArchiver(final JSArchiverOptions pobjArchiverOptions) throws Exception {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::getArchiver";
if (objArchiver == null) {
objArchiver = new JSArchiver();
objArchiver.registerMessageListener(this);
pobjArchiverOptions.FileName(super.getAbsoluteFile().toString());
objArchiver.Options(pobjArchiverOptions);
// objArchiver.Options().FileName(super.getAbsoluteFile().toString());
}
return objArchiver;
} // public JSArchiver getArchiver}
/**
*
* \brief close
*
* \details
*
* \return void
*
* @throws IOException
*/
public void close() throws IOException {
final String conMethodName = conClassName + "::close";
if (bufWriter != null) {
bufWriter.flush();
bufWriter.close();
bufWriter = null;
final NumberFormat fmt = NumberFormat.getInstance();
fmt.setGroupingUsed(true);
final String strT = String.format("%3$s - File '%1$s' created, Size is : %2$s", fleFile.getAbsoluteFile(), fmt.format(fleFile.length()),
conMethodName);
message(strT);
message(String.format("%3$s - file '%1$s' closed. '%2$d' lines written.", strFileName, lngNoOfLinesWritten, conMethodName));
}
else {
if (bufReader != null) {
bufReader.close();
bufReader = null;
}
message(String.format("%3$s - file '%1$s' closed. '%2$d' lines read.", strFileName, lngNoOfLinesRead, conMethodName));
}
this.doUnlock();
this.doReleaseExclusive();
}
/**
*
* \brief AppendFile - H�ngt den Inhalt einer anzugebenden Datei an die aktuelle Datei
*
* \return long
*
* @param pstrFileName - Name der Datei, deren Inhalt angeh�ngt werden soll
*
* @throws Exception
*/
public long AppendFile(final String pstrFileName) throws Exception {
final String conMethodName = conClassName + "::AppendFile";
long lngBytesWritten = 0;
FileInputStream in = null;
FileOutputStream out = null;
final String strFileN = getAbsolutePath();
final File objFile2Append = new File(strFileN);
if (!objFile2Append.getAbsoluteFile().exists()) {
SignalError(String.format("%1$s: File '%2$s' not exist. Append not possible", conMethodName, strFileN));
return -1;
}
File tempFile = new File(strFileN + "~"); // Ausgabe
try {
out = new FileOutputStream(tempFile);
try {
final File AFile = new File(pstrFileName); // the content of this file has to be appended
if (!AFile.getAbsoluteFile().exists()) {
SignalError(String.format("%1$s: File '%2$s' not exist. Append not possible", conMethodName, pstrFileName));
tempFile.delete();
return -1;
}
in = new FileInputStream(objFile2Append); //
lngBytesWritten += ExecuteCopyWOClose(in, out);
in.close();
in = new FileInputStream(AFile);
lngBytesWritten += ExecuteCopyWOClose(in, out);
in.close();
out.close();
message(String.format("%1$s: File '%2$s' appended to file '%3$s'", conMethodName, pstrFileName, strFileN));
objFile2Append.delete(); // otherwise the rename leads into an error
tempFile.renameTo(objFile2Append);
tempFile = null;
return lngBytesWritten;
}
catch (final FileNotFoundException e) {
SignalError(String.format("%1$s: File '%2$s' not exist. can not append to '%3$s'", conMethodName, pstrFileName, strFileN));
}
catch (final Exception e) {
if (in != null) {
in.close();
}
// if (out != null)
out.close();
throw e;
}
}
catch (final Exception e) {
logger.error("AppendFile(String)", e); //$NON-NLS-1$
SignalError(String.format("%1$s: append not succesfull for file '%2$s' with '%3$s'", conMethodName, getName(), pstrFileName));
}
finally {
if (tempFile != null) {
tempFile.delete();
tempFile = null;
}
//
}
return lngBytesWritten;
// try {
// String strFileN = this.getAbsolutePath();
// File tempFile = new File(strFileN + "~");
// writer = new BufferedWriter(new FileWriter(tempFile));
//
// File objFile2Append = new File(strFileN);
// reader = new BufferedReader(new FileReader(objFile2Append));
//
// while ((line = reader.readLine()) != null) {
// writer.write (line);
// writer.newLine();
// }
// reader.close();
//
// File AFile = new File(pstrFileName); // the content of this file has to be appended
// reader = new BufferedReader(new FileReader(AFile));
//
// while ((line = reader.readLine()) != null) {
// writer.write(line);
// writer.newLine();
// }
//
// reader.close();
//
// writer.close();
//
// objFile2Append.delete(); // otherwise the rename leads into an error
// tempFile.renameTo(objFile2Append);
// }
// catch (Exception e) {
// throw e;
// //
// }
// finally {
// if (writer != null) {
// writer.close();
// }
// if (reader != null) {
// reader.close();
// }
// }
//
// return lngBytesWritten;
}
/**
*
* \brief Send2FtpServer
*
* \details
*
* \return void
*
* @param settings
* @throws Exception
*/
public JSFile Send2FtpServer(final HashMap<String, String> settings) throws Exception {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::Send2FtpServer";
// final JSFtp objFtpClient = new JSFtp();
// final JSFtpOptions objFtpOptions = objFtpClient.Options(settings);
// objFtpOptions.setAllOptions(settings);
//
// objFtpOptions.FileMask("^" + strFileName + "$");
// objFtpClient.EstablishConnectionToServer();
// objFtpClient.putFiles();
return this;
} // public void Send2FtpServer
/**
*
* \brief Send2FtpServer
*
* \details
*
* \return JSFile
*
* @param pobjFtpOptions
* @return
* @throws Exception
*/
// public JSFile Send2FtpServer(final JSFtpOptions pobjFtpOptions) throws Exception {
//
// @SuppressWarnings("unused")
// final String conMethodName = conClassName + "::Send2FtpServer";
//
// // final JSFtp objFtpClient = new JSFtp();
// // objFtpClient.Options(pobjFtpOptions);
// //
// // pobjFtpOptions.FileMask("^" + strFileName + "$");
// // objFtpClient.EstablishConnectionToServer();
// // objFtpClient.putFiles();
//
// return this;
// } // public this Send2FtpServer}
/**
*
* \brief match
*
* \details
* Vergleicht den Inhalt der Datei mit der im Parameter angegebenen Datei.
* Beide Dateien werden Zeichen f�r Zeichen verglichen
*
* \return boolean
*
* @param fleTest
* @return
* @throws Exception
*/
public boolean compare(final JSFile pfleFile) throws Exception {
final BufferedReader objReader1 = Reader();
final BufferedReader objReader2 = pfleFile.Reader();
int char1, char2;
if (pfleFile.length() != length()) {
return false;
}
while (true) {
char1 = objReader1.read();
char2 = objReader2.read();
if (char1 != char2) {
return false;
}
if (char1 == -1 && char2 == -1) {
return true;
}
if (char1 == -1 || char2 == -1) {
return false;
}
}
}
/**
*
* \brief compare
*
* \details
*
* \return boolean
*
* @param pstrFile2Compare
* @return
* @throws IOException
*/
public boolean compare(final String pstrFile2Compare) throws IOException, Exception {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::compare";
return this.compare(new JSFile(pstrFile2Compare));
} // public boolean compare
public void Write(final StringBuffer pstrLine) throws Exception {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::Write";
this.Write(pstrLine.toString());
} // public void Write
/**
*
* \brief doLock - lock file on java-level against concurrent access
*
* \details
* This Methods locks the file on java-level against concurrent access.
*
* \return boolean - true, if the lock was sucessfull
*
* \see doUnlock
*
* \param strAccessMode
* The mode argument specifies the access mode in which the file is to be opened.
* The permitted values and their meanings are:
*
* @throws Exception
*/
public boolean doLock(final String pstrAccessMode) throws Exception {
final String conMethodName = conClassName + "::doLock";
// randomFile = new RandomAccessFile(this.strFileName, pstrAccessMode);
randomFile = new RandomAccessFile(this, pstrAccessMode);
FileChannel channel = randomFile.getChannel();
FileLock fleLock = null;
try {
fleLock = channel.tryLock();
}
catch (OverlappingFileLockException e) {
flgFileIsLocked = true;
}
catch (Exception e) {
logger.error("doLock(String)", e); //$NON-NLS-1$
throw e;
}
if (fleLock == null) { // we couldnt acquire lock as it is already locked by another program instance)
flgFileIsLocked = false;
randomFile = null;
}
else {
flgFileIsLocked = true;
}
if (flgFileIsLocked == true) {
message(String.format("%1$s - File locked: %2$s", conMethodName, strFileName));
}
return flgFileIsLocked;
} // private void doLock
/**
*
* \brief doLock
*
* \details
*
* \return boolean
*
* @return
* @throws Exception
*/
public boolean doLock() throws Exception {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::doLock";
return this.doLock("rw");
} // private boolean doLock
public boolean doUnlock() throws IOException {
final String conMethodName = conClassName + "::doUnlock";
if (randomFile != null) {
try {
if (fleLock != null) {
fleLock.release();
fleLock = null;
}
randomFile.getChannel().close();
}
catch (Exception e) {
}
randomFile = null;
flgFileIsLocked = false;
message(String.format("%1$s - File unlocked: %2$s", conMethodName, strFileName));
}
return true;
} // private boolean doUnlock
/**
*
* \brief isLocked
*
* \details
*
* \return boolean
*
* @return
*/
public boolean isLocked() {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::isLocked";
boolean flgIsLocked = false;
if (randomFile != null) {
flgIsLocked = flgFileIsLocked;
}
return flgIsLocked;
} // private boolean isLocked
public boolean setExclusive(final boolean pflgIsExclusive) throws IOException {
final String conMethodName = conClassName + "::setExclusive";
if (flgIsExclusive == true && pflgIsExclusive == false) {
//
this.doReleaseExclusive();
return flgIsExclusive;
}
flgIsExclusive = pflgIsExclusive;
if (flgIsExclusive = true) {
if (this.checkExclusiveDeny() == false) {
// String localHost = InetAddress.getLocalHost().getHostName();
InetAddress ia = InetAddress.getLocalHost();
String strUserName = System.getProperty("user.name");
JSDataElementTimeStampISO tstIso = new JSDataElementTimeStampISO(new JSDataElementDate(new Date()));
String strValues = this.strFileName + ";" + strUserName + ";" + tstIso.FormattedValue() + ";" + ia.getHostAddress();
fleExclusiveFile.WriteLine(strValues);
message(String.format("%1$s - create exclusive-file-marker with : %2$s", conMethodName, strValues));
fleExclusiveFile.close();
}
}
return flgIsExclusive;
} // private boolean setExclusive
/**
*
* \brief checkExclusiveDeny
*
* \details
*
* \return boolean
*
* @return
* @throws IOException
*/
private boolean checkExclusiveDeny() throws IOException {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::checkExclusiveDeny";
boolean flgExclusiveDeny = false;
fleExclusiveFile = new JSFile(this.strFileName + "~");
if (fleExclusiveFile.exists()) {
/**
* exclusive-file exists. check, who is the owner.
* If the current user is not the owner, we must deny the request.
*
*/
strExclusiveFootPrint = fleExclusiveFile.File2String();
if (strExclusiveFootPrint.length() > 0) {
message(String.format("%1$s - Footprint is %2$s", conMethodName, strExclusiveFootPrint));
String[] strP = strExclusiveFootPrint.split(";");
if (strP[1].equalsIgnoreCase(System.getProperty("user.name")) == false) {
fleExclusiveFile.close();
fleExclusiveFile = null;
flgExclusiveDeny = true;
}
}
}
return flgExclusiveDeny;
} // private boolean checkExclusiveDeny
private void doReleaseExclusive() {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::doReleaseExclusive";
flgIsExclusive = false;
if (fleExclusiveFile != null) {
fleExclusiveFile.delete();
fleExclusiveFile = null;
}
} // private void doReleaseExclusive
public String toXml() {
@SuppressWarnings("unused")
final String conMethodName = conClassName + "::toXml";
String strXml = String.format("<file name='%1$s' size='%2$d' modificationdate='%3$s' />", this.getAbsolutePath(), fleFile.length(), new Date(
fleFile.lastModified()));
return strXml;
} // private String toXml
}