Premier commit - Inclusion dans le projet git

This commit is contained in:
Mysaa 2021-05-23 23:08:30 +02:00
commit e1e3fb2abc
4 changed files with 495 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.classpath
.project
bin/
doc.zip
doc/

View File

@ -0,0 +1,47 @@
import java.io.File;
import java.io.PrintStream;
import com.bernard.logMachine.*;
public class BernardLogMachineMain {
public static void main(String[] args) {
Logger logger = new Logger();
LogChan chan1 = logger.newChan(new File("/home/mysaa/chan1.log.bernard"));
LogChan chan2 = logger.newChan(new File("/home/mysaa/chan2.log.bernard"));
LogChan chan3 = logger.newChan(new File("/home/mysaa/chan3.log.bernard"));
LogChan chan4 = logger.newChan(new File("/home/mysaa/chan4.log.bernard"));
LogChan chan5 = logger.newChan(new File("/home/mysaa/chan5.log.bernard"));
LogChan chan6 = logger.newChan(new File("/home/mysaa/chan6.log.bernard"));
System.out.println("bonjour");
PrintStream oldOut = System.out;
PrintStream oldErr = System.err;
System.out.println("ccava");
//System.setErr(chan1);
System.setOut(chan2);
System.out.println("Bien ?");
chan1.println("Wow");
chan2.println("Wow,bis");
chan3.println("Wow,tri");
chan4.println("Wow,carotte");
chan5.println("Wow, magie");
chan6.println("Waw");
chan1.println("Wiw");
chan6.println("Www");
chan4.println("bernard.com");
chan5.println("Concombre=courgette");
chan5.println("Lister");
System.out.println("Tuturu");
System.out.println("Carotte");
System.err.println("Akeproblem");
oldErr.println("vrai ?");
oldOut.println("vout");
logger.closeChan(chan4);
logger.closeChan(chan2);
logger.closeEverybody();
}
}

View File

@ -0,0 +1,328 @@
package com.bernard.logMachine;
import java.io.*;
import java.util.Calendar;
import java.util.Formatter;
import java.util.Locale;
public class LogChan extends PrintStream{
protected String tempMsg = "";
private void ensureOpen() {}//Est censé renvoyer une exception
/**
* Est censé actualiser/envoyer le buffer
* Vu qu'il n'y a pas de buffer, ca ne fait rien
*/
public void flush() {
//Naturally flushed
}
/**
* La fonction close A NE PAS UTILISER (pour la compatibilité)
*/
public void close() {
System.err.println("Veuillez passer par le le LogChan pour fermer un channel");
}
/**
* Si jamais y a une erreur dans le stream
*/
private boolean trouble;
/**
* Y a-t-il une erreur
*/
public boolean checkError() {return trouble;}
/**
* Oui, il y a eu une erreur
*/
protected void setError() {
trouble = true;
}
/**
* Non, il n'y a pâs d'erreur
*/
protected void clearError() {
trouble = false;
}
/**
* Écrit l'entrée
* @param b le truc a écrire
*/
public void write(int b) {
tempMsg += b;
}
public void write(byte buf[], int off, int len) {
byte[] newData = new byte[len];
System.arraycopy(buf, off, newData, 0, len);
tempMsg += newData;
}
private void write(char buf[]) {
tempMsg += buf;
}
private void write(String s) {
tempMsg += s;
}
private void newLine() {
log();
}
public void print(boolean b) {
write(b ? "true" : "false");
}
public void print(char c) {
write(String.valueOf(c));
}
public void print(int i) {
write(String.valueOf(i));
}
public void print(long l) {
write(String.valueOf(l));
}
public void print(float f) {
write(String.valueOf(f));
}
public void print(double d) {
write(String.valueOf(d));
}
public void print(char s[]) {
write(s);
}
public void print(String s) {
write((s==null)?"null":s);
}
public void print(Object obj) {
write(String.valueOf(obj));
}
public void println() {
newLine();
}
public void println(boolean x) {
synchronized (this) {
print(x);
newLine();
}
}
public void println(char x) {
synchronized (this) {
print(x);
newLine();
}
}
public void println(int x) {
synchronized (this) {
print(x);
newLine();
}
}
public void println(long x) {
synchronized (this) {
print(x);
newLine();
}
}
public void println(float x) {
synchronized (this) {
print(x);
newLine();
}
}
public void println(double x) {
synchronized (this) {
print(x);
newLine();
}
}
public void println(char x[]) {
synchronized (this) {
print(x);
newLine();
}
}
public void println(String x) {
print(x);
newLine();
}
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
public PrintStream printf(String format, Object ... args) {
return format(format, args);
}
public PrintStream printf(Locale l, String format, Object ... args) {
return format(l, format, args);
}
public PrintStream format(String format, Object ... args) {
synchronized (this) {
ensureOpen();
new Formatter(this).format(Locale.getDefault(), format, args);
}
return this;
}
public PrintStream format(Locale l, String format, Object ... args) {
synchronized (this) {
ensureOpen();
new Formatter(this).format(l, format, args);
}
return this;
}
public PrintStream append(CharSequence csq) {
if (csq == null)
print("null");
else
print(csq.toString());
return this;
}
public PrintStream append(CharSequence csq, int start, int end) {
CharSequence cs = (csq == null ? "null" : csq);
write(cs.subSequence(start, end).toString());
return this;
}
public PrintStream append(char c) {
print(c);
return this;
}
/////////////////Internal////////////////////
/**
* Le sacré-saint stream de sortie
*/
private OutputStream os;
/**
* Le charset de sortie
*/
public String charset = "UTF-8";
/**
* Le préfixe des lignes de sortie
*/
public String formatString = "\\£µdateµ£\\§(§\\£µthreadµ£\\§)]";
/**
* Crée le LogChan
* @param os le canal de sortie
*/
public LogChan(OutputStream os) {
super(os);//Totally useless because every function is overwritten
this.os = os;
}
/**
* Log un "toString" de cet objet
* @see java.lang.Object#toString
* @param data L'objet à dump
* @param <O> le type (en générique) de l'objet d'entrée
* @return Ce même objet (pour faire des chaines)
*/
public<O> O log(O data) {
logs(data.toString());
return data;
}
/**
* Log tout simplement la chaine du caractère
* @param data La chaine a écrire
* @return Cette même chaine (pour faire des chaînes)
*/
public String logs(String data) {
tempMsg += data;
log();
return data;
}
/**
* Dump TOUS les objets donnée
* @param data Les objets a donner
* @return Le String aui a été affiché
*/
public String log(Object... data) {
String concat = "";
for (Object object : data)
concat += object.toString();
return logs(concat);
}
/**
* Écrit le buffer avec le préfix et un retour a la ligne
* @return La chaine écrite, null si il y a eu un problème
*/
public String log() {
try {
os.write(head().replace("\n", "\\n").getBytes());
os.write(tempMsg.replace("\n", "\\n").getBytes(charset));
os.write('\n');
} catch (UnsupportedEncodingException e) {
System.err.println("Le charset "+charset+"n'est pas reconnu par Java :");
e.printStackTrace();
return null;
} catch (IOException e) {
System.err.println("Impossible de logger votre texte, une erreur de fichiers est apparue");
e.printStackTrace();
return null;
}
String out = tempMsg;
tempMsg = "";
return out;
}
/**
* Génère un préfix à inserer devant les lignes
* @return ce préfix
*/
public String head() {
return formatString
.replace("§\\£µnanotimeµ£\\§", Long.toString(System.nanoTime(),10))
.replace("§\\£µtimestampµ£\\§", Long.toString(System.currentTimeMillis(),10))
.replace("§\\£µdateµ£\\§", Calendar.getInstance().getTime().toString())
.replace("§\\£µthreadµ£\\§", Thread.currentThread().getName());
}
/**
* Récupérer le canal de sortie
* @return Le canal de sortie
*/
OutputStream os() {
return os;
}
}

View File

@ -0,0 +1,115 @@
package com.bernard.logMachine;
import java.awt.geom.IllegalPathStateException;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
/**
* Un objet qui rescence les <code>LogChan</code> pour permettre de les gérer correctement.
* Une instance devrait être créée pour chaque fonction pouvant créer plusieurs 'sous-chans'
* @see LogChan
* @author mysaa
*
*/
public class Logger{
/**
* Liste les chans gérés par ce Logger
*/
Map<String,LogChan> chans = new HashMap<>();
/**
* Liste des canaux de sortie associés aux LogChan
* @see chans
*/
Map<String,OutputStream> outputStreams = new HashMap<>();
/**
* Le message de fin, affiché lorsque un chan est fermé
*/
public static String endMessage = "##########FIN DU LOG##########";
public Logger() {
chans = new HashMap<>();
}
/**
* Cree un nouveau canal, au nom aléatoire (UUID)
* @param f le fichier de sortie du canal
* @return le le LogChan ainsi créé
* @throws IllegalPathStateException Si le fichier ne peut pas être écrit
*/
public LogChan newChan(File f) {
String logchanName = UUID.randomUUID().toString();
try {
if((f.exists())?!f.canWrite():!f.createNewFile());
OutputStream os = new FileOutputStream(f);
LogChan logChan = new LogChan(os);
chans.put(logchanName, logChan);
outputStreams.put(logchanName, os);
return logChan;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
throw new IllegalPathStateException("Ye suis désolé ye ne peut pas yécrire sur cé fichié ('"+f+"') ... disolé");
}
return null;
}
/**
* Ferme le LogChan ainsi nommé (et y envoie le message de fin)
* @param name Le nom du canal a fermer
*/
public void closeChan(String name) {
try {
chans.get(name).println(endMessage);
outputStreams.get(name).close();
outputStreams.remove(name);
chans.remove(name);
}catch(NullPointerException|IOException e){
System.err.println("Impossible de fermer le canal "+name);
e.printStackTrace();
}
}
/**
* Ferme le LogChan donné (et y envoie le message de fin)
* @param chan Le canal a fermer
*/
public void closeChan(LogChan chan) {
try {
Iterator<Entry<String, LogChan>> entries = chans.entrySet().iterator();
while (entries.hasNext()) {
Entry<String, LogChan> l = entries.next();
if(l.getValue().equals(chan)){
chans.get(l.getKey()).println(endMessage);
outputStreams.get(l.getKey()).close();;
outputStreams.remove(l.getKey());
entries.remove();
return;
}
}
throw new NullPointerException("Le canal n'est pas associé à ce Logger et je ne peut donc pas le fermer !");
}catch(NullPointerException|IOException e){
System.err.println("Impossible de fermer le canal "+chan);
e.printStackTrace();
}
}
/**
* Ferme tous les canaux associés a ce Logger
* (Bonne idée pour la fin du programme)
*/
public void closeEverybody(){
ArrayList<String> names = new ArrayList<>();
names.addAll(chans.keySet());
for (String name : names)
closeChan(name);
}
}