I would like to build an application which converts PDF Screenplays in HTML. Screenplays are very simple texts with no image nor other kind of objects, but formatting is very important.
Fortunately there aren't much formatting conventions either.
That said, I found in the internet the PDFbox java library and I would like to use it, but I can't find examples on how retreiving information about formatting (or about coordinates of the text).
What I need is to know the margin box coordinates and the ones of the text so I can compare them to check whether the text is indented or not.
I hope I've been clear enough.
Thank you in advance!
https://pdfbox.apache.org/2.0/commandline.html#extracttext
"-html boolean false Output in HTML format instead of raw text."
This looks like what you need.
Please have a look at this link. I think it will help you. Anyway I am copying the code from there in case if the link is broken...
package printtextlocations;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.pdfbox.exceptions.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.util.PDFTextStripper;
import org.apache.pdfbox.util.TextPosition;
public class PrintTextLocations extends PDFTextStripper {
public static StringBuilder tWord = new StringBuilder();
public static String seek;
public static String[] seekA;
public static List wordList = new ArrayList();
public static boolean is1stChar = true;
public static boolean lineMatch;
public static int pageNo = 1;
public static double lastYVal;
public PrintTextLocations()
throws IOException {
super.setSortByPosition(true);
}
public static void main(String[] args)
throws Exception {
PDDocument document = null;
seekA = args[1].split(",");
seek = args[1];
try {
File input = new File(args[0]);
document = PDDocument.load(input);
if (document.isEncrypted()) {
try {
document.decrypt("");
} catch (InvalidPasswordException e) {
System.err.println("Error: Document is encrypted with a password.");
System.exit(1);
}
}
PrintTextLocations printer = new PrintTextLocations();
List allPages = document.getDocumentCatalog().getAllPages();
for (int i = 0; i < allPages.size(); i++) {
PDPage page = (PDPage) allPages.get(i);
PDStream contents = page.getContents();
if (contents != null) {
printer.processStream(page, page.findResources(), page.getContents().getStream());
}
pageNo += 1;
}
} finally {
if (document != null) {
System.out.println(wordList);
document.close();
}
}
}
#Override
protected void processTextPosition(TextPosition text) {
String tChar = text.getCharacter();
System.out.println("String[" + text.getXDirAdj() + ","
+ text.getYDirAdj() + " fs=" + text.getFontSize() + " xscale="
+ text.getXScale() + " height=" + text.getHeightDir() + " space="
+ text.getWidthOfSpace() + " width="
+ text.getWidthDirAdj() + "]" + text.getCharacter());
String REGEX = "[,.\\[\\](:;!?)/]";
char c = tChar.charAt(0);
lineMatch = matchCharLine(text);
if ((!tChar.matches(REGEX)) && (!Character.isWhitespace(c))) {
if ((!is1stChar) && (lineMatch == true)) {
appendChar(tChar);
} else if (is1stChar == true) {
setWordCoord(text, tChar);
}
} else {
endWord();
}
}
protected void appendChar(String tChar) {
tWord.append(tChar);
is1stChar = false;
}
protected void setWordCoord(TextPosition text, String tChar) {
tWord.append("(").append(pageNo).append(")[").append(roundVal(Float.valueOf(text.getXDirAdj()))).append(" : ").append(roundVal(Float.valueOf(text.getYDirAdj()))).append("] ").append(tChar);
is1stChar = false;
}
protected void endWord() {
String newWord = tWord.toString().replaceAll("[^\\x00-\\x7F]", "");
String sWord = newWord.substring(newWord.lastIndexOf(' ') + 1);
if (!"".equals(sWord)) {
if (Arrays.asList(seekA).contains(sWord)) {
wordList.add(newWord);
} else if ("SHOWMETHEMONEY".equals(seek)) {
wordList.add(newWord);
}
}
tWord.delete(0, tWord.length());
is1stChar = true;
}
protected boolean matchCharLine(TextPosition text) {
Double yVal = roundVal(Float.valueOf(text.getYDirAdj()));
if (yVal.doubleValue() == lastYVal) {
return true;
}
lastYVal = yVal.doubleValue();
endWord();
return false;
}
protected Double roundVal(Float yVal) {
DecimalFormat rounded = new DecimalFormat("0.0'0'");
Double yValDub = new Double(rounded.format(yVal));
return yValDub;
}
}
Related
This is what my recursion detector looks like (with an error of "The method contains(String) is undefined for Method Declaration" in if (md.contains(methodName))). I am not sure how I should change this to make it work. I hope to have some advice on what I could do to iterate through each individual method and check for its methodName in it. Thank you!
RecursionDetector.java
package detectors;
import java.awt.*;
import java.util.*;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
public class RecursionDetector extends VoidVisitorAdapter <Breakpoints> {
#Override
public void visit(MethodDeclaration md, Breakpoints collector) {
String className = getClass().getName();
String methodName = md.getName().asString();
int startline = md.getRange().get().begin.line;
int endline = md.getRange().get().end.line;
final StackTraceElement[] trace = Thread.currentThread().getStackTrace();
if (md.contains(methodName)) {
}
for (int i=0; i < trace.length-1; i++) {
if( trace[i].equals(trace[trace.length-1]) ) {
super.visit(md, collector);
collector.addEmpty(className, methodName, startline, endline);
}
}
}
}
I also have a Breakpoints.java that looks like this:
package detectors;
import java.util.ArrayList;
public class Breakpoints {
private ArrayList<String> collector = new ArrayList<String>();
public Breakpoints() { }
public void addClass(String currentClass) { }
public void addMethod(String currentMethod) { }
public ArrayList<String> returnCollector() {
return new ArrayList<String>(this.collector);
}
public void addEmpty(String currentClass, String currentMethod, int startLine, int endLine) {
String n = ("className: " + currentClass + ", methodName: " + currentMethod + ", startline : " + startLine
+ ", endline : " + endLine + "\n");
if (collector.contains(n)) {
return;
}
collector.add(n);
}
}
And a Driver.java that looks like this:
package detectors;
import java.io.*;
import java.util.Scanner;
import com.github.javaparser.*;
import com.github.javaparser.ast.CompilationUnit;
public class Driver {
public static String data;
public static String data2 = "";
public static void main(String[] args) {
try {
File myFile = new File("/Users/weihanng/Desktop/Calculator.java");
Scanner myReader = new Scanner(myFile);
while (myReader.hasNextLine()) {
data = myReader.nextLine();
data2 = data2.concat(data);
}
myReader.close();
CompilationUnit cu = JavaParser.parse(myFile);
Breakpoints collector = new Breakpoints();
cu.accept(new RecursionDetector(), collector);
System.out.println("Recursions: ");
System.out.println(collector.returnCollector());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I made a simple java program that lets you create a stocks scanner/screener. There aren't many features yet, but there is a problem with existing features. I have a class that has a method that creates an array of all stock tickers and returns it. Here it is:
package classes;
import Utility.ArrayModification;
import variables.Ticker;
import java.io.*;
import java.util.Scanner;
public class Market {
public static Ticker[] getAllTickers() throws FileNotFoundException {
Ticker[] allTickers = {};
File currentDirectory = new File(new File("").getAbsolutePath());
String allTickersDirectory = currentDirectory + "\\src\\AllTickers.txt";
Scanner scanner = new Scanner(new File(allTickersDirectory));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(!(line.contains("^"))) {
allTickers = ArrayModification.appendTicker(allTickers, new Ticker(line));
}
}
return allTickers;
}
}
AllTickers.txt is a text file with the names of all tickers in it. I also have another class that stores a datatype, Ticker. Here it is:
package variables;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Ticker {
private String savedSymbol;
public Ticker(String symbol) {
savedSymbol = symbol;
}
public String getTicker() {
return savedSymbol;
}
public Ticker setTicker(String symbol) {
savedSymbol = symbol;
return this;
}
public double getPrice() throws IOException {
try {
String stringURL = "https://markets.businessinsider.com/stocks/" + savedSymbol + "-stock";
URL url = new URL(stringURL);
URLConnection urlConn = url.openConnection();
InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
BufferedReader buff = new BufferedReader(inStream);
String stringPrice = "-1";
String line = buff.readLine();
while (line != null) {
if (line.contains("price: ")) {
int target = line.indexOf("price: ");
int deci = line.indexOf(".", target);
int start = deci;
int stop = deci;
while (line.charAt(start) != ' ') {
start--;
}
while (line.charAt(stop) != ',') {
stop++;
}
stringPrice = line.substring(start + 1, stop);
break;
}
line = buff.readLine();
}
double price = Double.parseDouble(stringPrice);
return price;
}
catch(Exception e) {
return -1;
}
}
public double getMarketCap() throws IOException {
try {
String stringURL = "https://finviz.com/quote.ashx?t=" + savedSymbol;
URL url = new URL(stringURL);
URLConnection urlConn = url.openConnection();
InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
BufferedReader buff = new BufferedReader(inStream);
String stringMarketCap = "-1";
double finalMarketCap = -1;
String line = buff.readLine();
while (line != null) {
if (line.contains(">Market Cap<")) {
int deci = line.indexOf(".");
int start = deci;
int stop = deci;
while (line.charAt(start) != '>') {
start--;
}
while (line.charAt(stop) != '<') {
stop++;
}
stringMarketCap = line.substring(start + 1, stop - 1);
double marketCap = Double.parseDouble(stringMarketCap);
if (line.charAt(stop - 1) == 'B') {
finalMarketCap = marketCap * 1000000000;
} else if (line.charAt(stop - 1) == 'M') {
finalMarketCap = marketCap * 1000000;
}
break;
}
line = buff.readLine();
}
return finalMarketCap;
}
catch(Exception e) {
return -1;
}
}
}
Using all of these, you can create a simple scanner that scans for stocks with a price of, for example, 0 - 15. You can do this by doing this:
import classes.Market;
import variables.Ticker;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Ticker[] allTickers = Market.getAllTickers();
for(int i = 0; i< allTickers.length; i++){
Ticker ticker = allTickers[i];
if(ticker.getPrice() > 0 && ticker.getPrice() < 15) {
System.out.println(ticker.getTicker());
}
}
}
}
It prints out all of the qualifying stocks. However, it is EXTREMELY slow. So slow that it's basically unusable. It is this way because the ticker.getPrice() method has to connect to markets.businessinsider.com, extract the HTML code, find the correct index, and get the price for every single stock out of the 6000 in AllTIckers.txt. Would there be a way to do this faster?
I created a software based on two sources (stated in the code below) which detect HTML copied to the clipboard and change local images to base 64 ones.
This code works perfectly when I run it in Eclipse, but not using a JAR.
Initially, I was not using the method getHtmlDataFlavor, but I added it when I tried the software as a JAR. Then, I had to ensure in HtmlSelection.getTransferData to have if (flavor.getRepresentationClass() == java.io.Reader.class) otherwise it would crash. But using the JAR, I'm only getting the plain text version! Though, it stills works when ran in Eclipse.
Does someone have an idea ?
I am running on Windows 10.
Executing in command line using : java -jar ClipboardImageToBase64-1.0.0-jar-with-dependencies.jar
GitHub project :
https://github.com/djon2003/ClipboardImageToBase64
/**
* Library from HTML parsing : https://jsoup.org
*
* Code based on :
* - http://stackoverflow.com/a/14226456/214898
* - http://elliotth.blogspot.ca/2005/01/copying-html-to-clipboard-from-java.html
*/
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class ClipBoardListener extends Thread implements ClipboardOwner {
Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
private static DataFlavor HTML_FLAVOR = new DataFlavor("text/html;class=java.io.Reader", "HTML");
private int nbImagesConverted = 0;
private Transferable currentTransferable;
#Override
public void run() {
Transferable trans = sysClip.getContents(this);
TakeOwnership(trans);
}
#Override
public void lostOwnership(Clipboard c, Transferable t) {
System.out.println("Copy to clipboard detected");
try {
ClipBoardListener.sleep(250); // waiting e.g for loading huge
// elements like word's etc.
} catch (Exception e) {
System.out.println("Exception: " + e);
}
Transferable contents = sysClip.getContents(this);
try {
process_clipboard(contents, c);
} catch (Exception ex) {
Logger.getLogger(ClipBoardListener.class.getName()).log(Level.SEVERE, null, ex);
}
TakeOwnership(currentTransferable);
}
void TakeOwnership(Transferable t) {
sysClip.setContents(t, this);
}
private void getHtmlDataFlavor(Transferable t) {
DataFlavor df = null;
for (DataFlavor tDf : t.getTransferDataFlavors()) {
if (tDf.getMimeType().contains("text/html")) {
if (tDf.getRepresentationClass() == java.io.Reader.class) {
df = tDf;
break;
}
}
}
HTML_FLAVOR = df;
}
public void process_clipboard(Transferable t, Clipboard c) {
String tempText = "";
Transferable trans = t;
currentTransferable = t;
getHtmlDataFlavor(t);
if (HTML_FLAVOR == null) {
System.out.println("No HTML flavor detected");
return;
}
nbImagesConverted = 0;
try {
if (trans != null ? trans.isDataFlavorSupported(HTML_FLAVOR) : false) {
if (trans.isDataFlavorSupported(DataFlavor.stringFlavor)) {
tempText = (String) trans.getTransferData(DataFlavor.stringFlavor);
}
java.io.Reader r = (java.io.Reader) trans.getTransferData(HTML_FLAVOR);
StringBuilder content = getReaderContent(r);
String newHtml = changeImages(content);
currentTransferable = new HtmlSelection(newHtml, tempText);
System.out.println("Converted " + nbImagesConverted + " images");
} else {
System.out.println("Not converted:" + trans.isDataFlavorSupported(HTML_FLAVOR));
System.out.println(trans.getTransferData(HTML_FLAVOR));
/*
for (DataFlavor tt : trans.getTransferDataFlavors()) {
if (tt.getMimeType().contains("text/html")) {
System.out.println("-------");
System.out.println(tt.toString());
}
}
*/
}
} catch (Exception e) {
currentTransferable = t;
System.out.println("Conversion error");
e.printStackTrace();
}
}
private String changeImages(StringBuilder content) throws RuntimeException, IOException {
Document doc = Jsoup.parse(content.toString());
Elements imgs = doc.select("img");
for (Element img : imgs) {
String filePath = img.attr("src");
filePath = filePath.replace("file:///", "");
filePath = filePath.replace("file://", "");
File file = new File(filePath);
if (file.exists()) {
String encoded = Base64.encodeBase64String(FileUtils.readFileToByteArray(file));
String extension = file.getName();
extension = extension.substring(extension.lastIndexOf(".") + 1);
String dataURL = "data:image/" + extension + ";base64," + encoded;
img.attr("src", dataURL); // or whatever
nbImagesConverted++;
}
}
String html = doc.outerHtml();
html = html.replaceAll("(?s)<!--.*?-->", ""); //Remove html comments
return html; // returns the modified HTML
}
private StringBuilder getReaderContent(java.io.Reader r) throws IOException {
char[] arr = new char[8 * 1024];
StringBuilder buffer = new StringBuilder();
int numCharsRead;
while ((numCharsRead = r.read(arr, 0, arr.length)) != -1) {
buffer.append(arr, 0, numCharsRead);
}
r.close();
return buffer;
}
private static class HtmlSelection implements Transferable {
private String html;
private String plainText;
public HtmlSelection(String html, String plainText) {
this.html = html;
this.plainText = plainText;
}
public DataFlavor[] getTransferDataFlavors() {
DataFlavor[] dfs = {HTML_FLAVOR, DataFlavor.stringFlavor};
return dfs;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.getMimeType().contains("text/html") || flavor.getMimeType().contains("text/plain");
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (flavor.getMimeType().contains("text/html")) {
if (flavor.getRepresentationClass() == java.io.Reader.class) {
return new StringReader(html);
} else {
return html;
}
} else {
return plainText;
}
//throw new UnsupportedFlavorException(flavor);
}
}
}
I finally fixed all my problems. I created a GitHub project for those who are interested.
https://github.com/djon2003/ClipboardImageToBase64
I have two project, a Java+Spring server and a unity project written in C#.
The unity project will be export into WebGl(it is not a game).
Now here is my problem:
I must load textures from the Java server.
How can i solve this problem?
My current solution, greatly simplified (not work in browser):
Server:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
-
#RestController
public class MyController {
#Autowired
private Loader2 loader2;
#RequestMapping("/skull2")
public ByteObj skull2(#RequestParam(value = "name", defaultValue = "World") String name) {
return loader2.getImages("Skull");
}
}
-
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Controller;
#Controller
public class Loader2 {
String mainPath = "Path to images folder"; // in the future i will load many textures;
public List<String> getFileNameInPath(String foldername) {
List<String> result = new ArrayList<String>();
File folder = new File(mainPath + foldername);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("file " + listOfFiles[i].getName());
result.add(listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
return result;
}
public ByteObj getImages(String folder) {
List<String> images = getFileNameInPath(folder);
for (String string : images) {
try {
File file = new File(mainPath + folder + "//" + string);
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
String imageDataString = encodeImage(imageData);
imageInFile.close();
return new ByteObj(imageDataString);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public String encodeImage(byte[] imageByteArray) {
return Base64.encodeBase64String(imageByteArray);
}
}
-
import java.io.Serializable;
public class ByteObj implements Serializable {
public String obj;
public ByteObj(String obj) {
this.obj = obj;
}
public ByteObj() {
}
}
Client(load from server and decode)
The Unity stage contains a 3D cube and a camera(with script)
// C#
public class ByteObj {
public string obj;
public ByteObj(string obj) {
this.obj = obj;
}
public ByteObj() {
}
}
-
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
using System.Text;
public class MyTestClass: MonoBehaviour {
public GameObject cube;
public float speed = 10f;
IEnumerator Start() {
yield return StartCoroutine( UploadImages() );
}
void Update () {
cube.transform.Rotate(Vector3.up, speed * Time.deltaTime);
}
IEnumerator UploadImages()
{
string aux = "";
WWW www = new WWW("http://localhost:8080/skull2");
yield return www;
aux = www.text;
if (www.text == null)
{
Debug.Log("Images not found");
}
else {
ByteObj list = JsonUtility.FromJson<ByteObj>(aux);
var myObject = list.obj;
//instruction.text = list.obj;
string s = myObject.Trim().Replace(" ", "+");
if (s.Length % 4 > 0)
s = s.PadRight(s.Length + 4 - s.Length % 4, '=');
byte[] b64_bytes = System.Convert.FromBase64String(myObject);
var decodedBytes = Convert.FromBase64String(myObject);
var tex = new Texture2D(2, 2);
tex.LoadImage(decodedBytes);
cube.GetComponent<Renderer>().material.mainTexture = tex;
}
}
}
It works as a Desktop app, but after export to WebGl I see only the cube(without textures)
Thank you for your help
PS. Sorry for my english
I want to develop logging system in OSGI bundle which can write application errors into file on the HDD.
This is the Activator:
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;
public class LoggingSystemApp implements BundleActivator {
LoggingSystemImpl log = null;
#Override
public void start(final BundleContext bc) throws Exception {
debug("Activator started");
ServiceRegistration registerService = bc.registerService(LoggingSystemImpl.class.getName(), new LoggingSystemImpl(), new Properties());
/* Start Logger System */
log = LoggingSystemImpl.getInstance();
log.start();
}
public void stop(BundleContext bc) throws Exception {
boolean ungetService = bc.ungetService(bc.getServiceReference(LoggingSystem.class.getName()));
st.close();
log.stop();
}
private void debug(String msg) {
System.out.println("JDBCBundleActivator: " + msg);
}
}
This is the implementation of the Logging system:
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.sql.Connection;
import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Locale;
import org.DX_57.osgi.LS_27.api.LoggingSystem;
public class LoggingSystemImpl implements LoggingSystem {
public LoggingSystemImpl() {
}
public DataSource ds;
#Override
public void setDataSource(DataSource ds){
this.ds = ds;
}
private final static Calendar calendar = Calendar.getInstance();
private final static String user = System.getenv("USERNAME").toLowerCase();
private final static String sMonth = calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH);
private final static int y = calendar.get(Calendar.YEAR);
// the name of the log file
//private final String logName = sysDrive + "\\fttb_web - " + sMonth.toLowerCase() + ", " + y + ".log";
private final String logName = "logger - " + sMonth.toLowerCase() + ", " + y + ".log";
private static boolean closed;
private static LoggingSystemImpl log = null;
private static BufferedWriter bw = null;
private static FileOutputStream fos = null;
private static OutputStreamWriter osw = null;
/* Utilialize Buffer and wait for data to write */
public void start() throws IOException{
log = LoggingSystemImpl.getInstance();
}
public void stop(){
log.close();
}
public void WriteLog(String WriteString){
log.writeln(WriteString);
}
public void LoggingSystemImpl() throws IOException
{
fos = new FileOutputStream(logName, true);
// set encoding to cyrillic (if available)
if (Charset.isSupported("windows-1251"))
{
osw = new OutputStreamWriter(fos, Charset.forName("windows-1251"));
}
else { osw = new OutputStreamWriter(fos); }
bw = new BufferedWriter(osw, 2048); // 2Mb buffer
}
// intro header for log session
public static synchronized LoggingSystemImpl getInstance() throws IOException
{
boolean exc = false;
try
{
if (log == null || closed)
{
log = new LoggingSystemImpl();
closed = false;
log.writeln("logged in.");
log.nl();
}
}
// catch(IOException x) { exc = true; throw x; }
catch(Exception x) { exc = true; x.printStackTrace(); }
finally
{
if (exc)
{
try
{
if (fos != null) { fos.close(); fos = null; }
if (osw != null) { osw.close(); fos = null; }
if (bw != null) { bw.close(); bw = null; }
}
catch(Exception x) { x.printStackTrace(); }
}
}
return log;
}
public synchronized void nl()
{
try { bw.newLine(); }
catch(IOException x) {x.printStackTrace();}
}
public synchronized void nl(int count)
{
try
{
for (int i = 0; i < count; i++) bw.newLine();
}
catch(IOException x) {x.printStackTrace();}
}
public synchronized void writeln(String s)
{
try { bw.write(getTime() + ": " + s); bw.newLine(); }
catch(IOException x) {x.printStackTrace();}
}
public synchronized void write(String s)
{
try { bw.write(s); }
catch (IOException x) {x.printStackTrace();}
}
public synchronized void close()
{
try
{
if (bw != null)
{
writeln("logged out.");
nl();
bw.flush();
bw.close();
closed = true;
fos = null;
osw = null;
bw = null;
}
}
catch(IOException x) { x.printStackTrace(); }
}
public synchronized boolean isClosed() { return closed; }
public synchronized void writeException(Exception x)
{
writeln("");
write("\t" + x.toString()); nl();
StackTraceElement[] ste = x.getStackTrace();
int j = 0;
for (int i = 0; i < ste.length; i++)
{
if (i < 15) { write("\t\tat " + ste[i].toString()); nl(); }
else { j++; }
}
if (j > 0) { write("\t\t... " + j + " more"); nl(); }
nl(2);
}
private String getTime()
{
Calendar c = Calendar.getInstance();
int month = c.get(Calendar.MONTH) + 1;
int d = c.get(Calendar.DAY_OF_MONTH);
int h = c.get(Calendar.HOUR_OF_DAY);
int m = c.get(Calendar.MINUTE);
int s = c.get(Calendar.SECOND);
int y = c.get(Calendar.YEAR);
String dd = d < 10 ? "0"+d : ""+d;
String hh = h < 10 ? "0"+h : ""+h;
String mm = m < 10 ? "0"+m : ""+m;
String ss = s < 10 ? "0"+s : ""+s;
String sm = month < 10 ? "0"+month : ""+month;
return user + " [" + y + "." + sm + "." + dd + " " + hh + ":" + mm + ":" + ss + "]";
}
}
When I try to compile the code in Netbeans I get this error:
COMPILATION ERROR :
-------------------------------------------------------------
org/DX_57/osgi/LS_27/impl/LoggingSystemImpl.java:[34,7] error: LoggingSystemImpl is not abstract and does not override abstract method SessionRegister(String,String,String) in LoggingSystem
1 error
How I can fix this problem?
Best wishes
P.S
this is the code of the interface
public interface LoggingSystem {
public void setDataSource(DataSource ds);
}
EDIT
Can you tell me do you see any other errors in the code especially the Activator class?
You have to implement the mentioned method in your class. The message says that your class is not abstract bus has not concretely implemented all abstract methods from its parents.
Well, the error message is pretty clear. You can either declare LoggingSystemImpl as abstract or implement the missing method - SessionRegister(String,String,String).
The reason for this is that the interface LoggingSystem has the method SessionRegister(String,String,String) declared. Because it has no implementation, it needs to be implemented in all non-abstract children, including your class.
A quick fix would be:
public class LoggingSystemImpl implements LoggingSystem {
void SessionRegister(String,String,String)
{ //dummy implementation
}
//other methods
}
Looks like there is a method SessionRegister(String,String,String) declared in the interface that you have not implemented... You should probably implement it...
My guess is that if you declared LoggingSystem as you show in your code, then the import in the implementation class is the problem:
import org.DX_57.osgi.LS_27.api.LoggingSystem;
Are you sure that's the interface you're trying to implement?