Create svg DataFlavor in java with dataflavor image/svg+xml - java

So I want to create a DataFlavor that contains a string and has the mimetype image/svg+xml using java. I am not quite sure I get how the DataFlavor and mimetype are connected. I did not quite understand the Java tutorials 1.
What I want is to be able to move my string that I generated as an svg object to other programs using the system clipboard.
The code i am using now is:
import java.awt.Toolkit;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
public class SvgClip implements Transferable, ClipboardOwner
{
private String string;
public SvgClip(String str)
{
string = str;
}
public DataFlavor[] getTransferDataFlavors()
{
DataFlavor flavor = new DataFlavor();
try{
//flavor = new DataFlavor("image/svg+xml");S
flavor = new DataFlavor("image/svg+xml;class=java.lang.String");
}catch (Exception ex) {
ex.printStackTrace();
}
return new DataFlavor[]{flavor};
}
public boolean isDataFlavorSupported(DataFlavor flavor)
{
return DataFlavor.imageFlavor.equals(flavor);
}
public Object getTransferData(DataFlavor flavor) throws
UnsupportedFlavorException
{
if (!isDataFlavorSupported(flavor))
throw new UnsupportedFlavorException(flavor);
return string;
}
public void lostOwnership(java.awt.datatransfer.Clipboard clip,
java.awt.datatransfer.Transferable tr)
{
return;
}
}
however, this is not working , i get java.io.IOException: image/svg+xml
when trying to create it with:
SvgClip strSel = new SvgClip(newfileString);
clipboard.setContents(strSel, null);
Anyone have any idea?

I am now using this class to implement an SVG object that can be put in the clipboard, please give thanks if this is useful!:
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.SystemFlavorMap;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class SvgClip implements Transferable
{
final private String svgstring;
//https://bugs.openjdk.java.net/browse/JDK-8140526
//http://bugs.java.com/bugdatabase/view_bug.do;jsessionid=67bf0d656b66cc60360819906ba?bug_id=4493178
static final private DataFlavor svgFlavor = new DataFlavor("image/svg+xml; class=java.io.InputStream","Scalable Vector Graphic");
static final private DataFlavor inkscapeFlavor = new DataFlavor("image/x-inkscape-svg; class=java.io.InputStream","Scalable Vector Graphic");
//static private DataFlavor svgFlavor = new DataFlavor(String.class,"image/svg+xml");
private DataFlavor [] supportedFlavors;
private FileTransferable file;
public SvgClip(String str)
{
/*
try {
this.svgFlavor = new DataFlavor("image/svg+xml");
} catch (ClassNotFoundException ex) {
Logger.getLogger(SvgClip.class.getName()).log(Level.SEVERE, null, ex);
}
*/
this.supportedFlavors = new DataFlavor[] {
svgFlavor,
DataFlavor.javaFileListFlavor,
inkscapeFlavor
};
this.svgstring = str;
SystemFlavorMap systemFlavorMap = (SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap();
DataFlavor dataFlavor = svgFlavor;
//systemFlavorMap.addFlavorForUnencodedNative("image/svg+xml", dataFlavor);
systemFlavorMap.addUnencodedNativeForFlavor(dataFlavor, "image/svg+xml");
systemFlavorMap.addUnencodedNativeForFlavor(inkscapeFlavor, "image/x-inkscape-svg");
try{
this.file = FileTransferable.createFileInTempDirectory("temp.svg");
List<File> files = file.getFiles();
if(files.isEmpty())
{
System.out.println("No file!");
}
else
{
//write the svgstring to a file in temp.
PrintWriter writer = new PrintWriter(files.get(0));
writer.println(svgstring);
writer.close();
}
}
catch(Exception Ex)
{
Ex.printStackTrace();
}
}
#Override public DataFlavor[] getTransferDataFlavors()
{
return this.supportedFlavors;
}
static DataFlavor getSVGFlavor()
{
return SvgClip.svgFlavor;
}
#Override public boolean isDataFlavorSupported(DataFlavor flavor)
{
for( DataFlavor supported : this.supportedFlavors)
{
if( flavor.equals(supported)){
System.out.println("flavor is supported " +
flavor.getMimeType()
+ " " + flavor.toString()
);
return true;
}
else{
System.out.println("flavor is NOT supported " + flavor.getMimeType());
}
}
return false;
}
#Override public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException
{
if (isDataFlavorSupported(flavor))
{
if(flavor.equals(inkscapeFlavor) || flavor.equals(svgFlavor))
{
InputStream stream = new ByteArrayInputStream(svgstring.getBytes(StandardCharsets.UTF_8));
return stream;
}
if(flavor.equals(DataFlavor.javaFileListFlavor))
{
System.out.println("Returning file");
return this.file.getTransferData(flavor);
}
}
throw new UnsupportedFlavorException (flavor);
}
public void lostOwnership(java.awt.datatransfer.Clipboard clip,
java.awt.datatransfer.Transferable tr)
{
return;
}
}

Related

Minecraft plugin hanging on "Enabling plugin" and producing out of memory errors

Why would this code be having memory issues? It runs fine once, and then when I try to run it again it hangs on "Enabling plugin". It'll then give me an OutOfMemoryException such as
"Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "Worker-Main-10""
The code I am using is as follows from the Spigot API
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Bat;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.UUID;
public class COVID19 extends JavaPlugin {
private static ArrayList<CovidInfection> infections;
#Override
public void onEnable() {
infections = new ArrayList<CovidInfection>();
System.out.println("1");
try {
readInfections();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
System.out.println("2");
this.getCommand("getInfected").setExecutor(new CommandGetInfected());
BukkitScheduler scheduler = getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
#Override
public void run() {
batCovid();
}
}, 0, 10);
System.out.println(4);
}
#Override
public void onDisable() {
try {
writeInfections();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void batCovid() {
System.out.println(3);
for(Player player : Bukkit.getOnlinePlayers()) {
for(Entity nearby : player.getNearbyEntities(6, 6, 6)) {
if (nearby instanceof Bat) {
String name = player.getName();
UUID uuid = player.getUniqueId();
infections.add(new CovidInfection(uuid, name, 14));
}
}
}
}
public void readInfections() throws FileNotFoundException {
File file = new File("infected.txt");
if(file.length() == 0) {
return;
}
Scanner input = new Scanner(file);
String line = input.nextLine();
while (!(line.equals(""))) {
infections.add(parseInfectionLine(line));
}
input.close();
}
public void writeInfections() throws IOException {
//File will be written as UUID,Name,DaysRemaining
FileWriter writer = new FileWriter("infected.txt", false);
for(CovidInfection infection : infections) {
writer.write(infection.toString());
}
writer.close();
}
private CovidInfection parseInfectionLine(String line) {
String[] words = line.replace("\n","").split(",");
return new CovidInfection(UUID.fromString(words[0]), words[1], Integer.parseInt(words[2]));
}
public static String getInfected() {
String compiled = "";
for (CovidInfection infection : infections) {
compiled += infection.toString() + "\n";
}
return compiled;
}
}
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandGetInfected implements CommandExecutor {
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
String message = COVID19.getInfected();
if(!(message.equals(""))) {
sender.sendMessage(message);
} else {
sender.sendMessage("There are no infected!");
}
return(true);
}
}
import java.util.UUID;
public class CovidInfection {
private UUID uuid;
private String name;
private int days;
public CovidInfection(UUID uuid, String name, int days) {
this.uuid = uuid;
this.name = name;
this.days = days;
}
public int getDays() {
return days;
}
public String getName() {
return name;
}
public UUID getUuid() {
return uuid;
}
public void newDay() {
days--;
}
public String toString() {
return uuid.toString() + "," + name + "," + days + "\n";
}
}
Any help would be greatly appreciated, thank you!
Firstly, you are make I/O request on main thread.
To fix this issue, use multithreading such as explained here or here
Then, this :
Scanner input = new Scanner(file);
String line = input.nextLine();
Can't be used in a server.
An input like that already exist, it's the console sender.
To do that, I suggest you to use ServerCommandEvent and use spigot's console.

Java DecriptionInfo on Word DocX

I'm pulling my hair out as I cannot get the samples to work - hopefully someone can help..
I would like to DETECT if a docx and a doc file is password protected/encrypted. I have seen this posted in a few places but I cannot get it work - it doesnt throw an exception. Can someone see what I am doing wrong. Note I only need to detect the password..i dont want to open the document.
String fileLocation = "C:/myfile.docx";
File file = new File(fileLocation);
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
POIFSFileSystem pfis = new POIFSFileSystem(fis);
try{
EncryptionInfo info = new EncryptionInfo(pfis);
EncryptionMode mode = info.getEncryptionMode();
Decryptor d = Decryptor.getInstance(info);
//Try and open it
if(!d.verifyPassword(Decryptor.DEFAULT_PASSWORD))
{
//file is encrypted
}
}
catch(GeneralSecurityException gse)
{
//file is encrypted
}
catch(EncryptedDocumentException edc)
{
//file is encrypted
}
I haven't elaborated much to get the code smaller, but I've simply taken one of the factory classes - like SlideShowFactory - and modified it for H/XWPF. As H/XWPF hasn't got a common interface on the document level (as of now), the quick&dirty approach is to return an Object.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.DocumentFactoryHelper;
import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class EncDetect {
public static void main(String[] args) {
String dir = "/home/kiwiwings/project/poi/poi/test-data";
String[] files = {
"document/bug53475-password-is-solrcell.docx",
"document/password_tika_binaryrc4.doc",
"document/58067.docx",
"document/58804.doc"
};
for (String f : files) {
try {
DocumentFactory.create(new File(dir, f));
System.out.println(f + " not encrypted");
} catch (EncryptedDocumentException e) {
System.out.println(f + " is encrypted");
} catch (Exception e) {
System.out.println(f + " " +e.getMessage());
}
}
}
static class DocumentFactory {
public static Object create(NPOIFSFileSystem fs) throws IOException {
return create(fs, null);
}
public static Object create(final NPOIFSFileSystem fs, String password) throws IOException {
DirectoryNode root = fs.getRoot();
// Encrypted OOXML files go inside OLE2 containers, is this one?
if (root.hasEntry(Decryptor.DEFAULT_POIFS_ENTRY)) {
InputStream stream = null;
try {
stream = DocumentFactoryHelper.getDecryptedStream(fs, password);
return createXWPFDocument(stream);
} finally {
IOUtils.closeQuietly(stream);
}
}
// If we get here, it isn't an encrypted XWPF file
// So, treat it as a regular HWPF one
boolean passwordSet = false;
if (password != null) {
Biff8EncryptionKey.setCurrentUserPassword(password);
passwordSet = true;
}
try {
return createHWPFDocument(fs);
} finally {
if (passwordSet) {
Biff8EncryptionKey.setCurrentUserPassword(null);
}
}
}
public static Object create(InputStream inp) throws IOException, EncryptedDocumentException {
return create(inp, null);
}
public static Object create(InputStream inp, String password) throws IOException, EncryptedDocumentException {
// If clearly doesn't do mark/reset, wrap up
if (! inp.markSupported()) {
inp = new PushbackInputStream(inp, 8);
}
// Ensure that there is at least some data there
byte[] header8 = IOUtils.peekFirst8Bytes(inp);
// Try to create
if (NPOIFSFileSystem.hasPOIFSHeader(header8)) {
NPOIFSFileSystem fs = new NPOIFSFileSystem(inp);
return create(fs, password);
}
if (DocumentFactoryHelper.hasOOXMLHeader(inp)) {
return createXWPFDocument(inp);
}
throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
}
public static Object create(File file) throws IOException, EncryptedDocumentException {
return create(file, null);
}
public static Object create(File file, String password) throws IOException, EncryptedDocumentException {
return create(file, password, false);
}
public static Object create(File file, String password, boolean readOnly) throws IOException, EncryptedDocumentException {
if (!file.exists()) {
throw new FileNotFoundException(file.toString());
}
NPOIFSFileSystem fs = null;
try {
fs = new NPOIFSFileSystem(file, readOnly);
return create(fs, password);
} catch(OfficeXmlFileException e) {
IOUtils.closeQuietly(fs);
return createXWPFDocument(file, readOnly);
} catch(RuntimeException e) {
IOUtils.closeQuietly(fs);
throw e;
}
}
protected static Object createHWPFDocument(NPOIFSFileSystem fs) throws IOException, EncryptedDocumentException {
return new HWPFDocument(fs.getRoot());
}
protected static Object createXWPFDocument(InputStream stream) throws IOException, EncryptedDocumentException {
return new XWPFDocument(stream);
}
protected static Object createXWPFDocument(File file, boolean readOnly) throws IOException, EncryptedDocumentException {
try {
OPCPackage pkg = OPCPackage.open(file, readOnly ? PackageAccess.READ : PackageAccess.READ_WRITE);
return new XWPFDocument(pkg);
} catch (InvalidFormatException e) {
throw new IOException(e);
}
}
}
}

dynamic header CSVParser

Below code parses the CSV records if the header is always known in advance and we can declare the array values for FILE_HEADER_MAPPING.
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING);
FileReader fileReader = new FileReader("file");
CSVParser csvFileParser = new CSVParser(fileReader, csvFileFormat);
Iterable<CSVRecord> records = csvFileParser.getRecords();
but how to create the CSVParser for the CSV files in which the headers differs for each csv file.
I will not know the header of the csv file to create with the format
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING);
I want to have a csv parser for each possible csv headers.
Please help me to solve this scenario.
package dfi.fin.dcm.syn.loantrading.engine.source.impl;
import static dfi.fin.dcm.syn.loantrading.engine.task.impl.BackOfficeCSVHelper.AMOUNT;
import static dfi.fin.dcm.syn.loantrading.engine.task.impl.BackOfficeCSVHelper.FCN;
import static dfi.fin.dcm.syn.loantrading.engine.task.impl.BackOfficeCSVHelper.FEE_TYPE;
import static dfi.fin.dcm.syn.loantrading.engine.task.impl.BackOfficeCSVHelper.LINE_TYPE;
import static dfi.fin.dcm.syn.loantrading.engine.task.impl.BackOfficeCSVHelper.LINE_TYPE_VALUE_CARRY_EVT;
import static dfi.fin.dcm.syn.loantrading.engine.task.impl.BackOfficeCSVHelper.MARKIT_ID;
import static dfi.fin.dcm.syn.loantrading.engine.task.impl.BackOfficeCSVHelper.VALUE_DATE;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import com.csvreader.CsvReader.CatastrophicException;
import com.csvreader.CsvReader.FinalizedException;
import dfi.fin.dcm.syn.loantrading.engine.source.SourceException;
import dfi.fin.dcm.syn.loantrading.model.portfolio.Portfolio;
#Deprecated
public class CarryEventStreamSource extends AbstractInputStreamSource<CarryEventData> {
private static String [] headers = {LINE_TYPE,VALUE_DATE,MARKIT_ID,FEE_TYPE,AMOUNT};
private SimpleDateFormat dateFormat = null;
public CarryEventStreamSource(InputStream stream) {
super(stream);
dateFormat = new SimpleDateFormat("dd/MM/yy");
}
public CarryEventData readNextElementInternal() throws SourceException, IOException, CatastrophicException, FinalizedException {
//skipping all events which are not Carry
boolean loop = true;
while (loop) {
// skipping all events which are not Carry
if(getReader().readRecord() && !getReader().get(LINE_TYPE).trim().equals(LINE_TYPE_VALUE_CARRY_EVT)) {
loop = true;
} else {
loop = false;
}
}
//EOF?
if (getReader().get(LINE_TYPE).trim().equals(LINE_TYPE_VALUE_CARRY_EVT)) {
CarryEventData toReturn = new CarryEventData();
toReturn.setComputationDate(Calendar.getInstance().getTime());
try {
toReturn.setValueDate(getDateFormat().parse(getReader().get(VALUE_DATE).trim()));
} catch (ParseException e) {
throw new SourceException(e);
}
if (!getPortfolio().getMtmSourceType().equals(Portfolio.MTM_SOURCE_TYPE_NONE)) {
if (getReader().get(MARKIT_ID).trim() == null) {
throw new SourceException("Back Office file invalid data format: the markit id is missing on line "+getReader().getCurrentRecord());
}
toReturn.setTrancheMarkitId(getReader().get(MARKIT_ID).trim());
} else {
if (getReader().get(FCN)==null || "".equals(getReader().get(FCN).trim())) {
throw new SourceException("Back Office file invalid data format: missing loan tranche id on line "+getReader().getCurrentRecord());
}
toReturn.setTrancheMarkitId(getReader().get(FCN).trim());
}
if (getReader().get(FEE_TYPE).equals("")) {
toReturn.setFeeType(null);
} else {
toReturn.setFeeType(getReader().get(FEE_TYPE).trim());
}
if (getReader().get(AMOUNT)==null) {
throw new SourceException("Back Office file invalid data format: missing amount on line "+getReader().getCurrentRecord());
}
try {
toReturn.setAmount(new BigDecimal(getReader().get(AMOUNT)));
} catch (NumberFormatException ex) {
throw new SourceException(ex,"Back Office file invalid data format: invalid amount on line "+getReader().getCurrentRecord());
}
return toReturn;
}
// no carry found, null is returned
return null;
}
public SimpleDateFormat getDateFormat() {
return dateFormat;
}
public void setDateFormat(SimpleDateFormat dateFormat) {
this.dateFormat = dateFormat;
}
#Override
public char getDelimiter() {
return ',';
}
#Override
public List<String> getHeaderSet() {
return Arrays.asList(headers);
}
#Override
public String getName() {
return "File import";
package dfi.fin.dcm.syn.loantrading.engine.source.impl;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import com.csvreader.CsvReader.CatastrophicException;
import com.csvreader.CsvReader.FinalizedException;
import dfi.fin.dcm.syn.loantrading.engine.source.SourceException;
import dfi.fin.dcm.syn.loantrading.model.common.LTCurrency;
import dfi.fin.dcm.syn.loantrading.model.engine.event.CurrencyEvent;
public class SpotForexRateStreamSource extends AbstractInputStreamSource<CurrencyEvent> {
private SimpleDateFormat dateFormat;
private static String [] headers = {"CURRENCY","DATE","MID"};
public SpotForexRateStreamSource(InputStream stream) {
super(stream);
dateFormat = new SimpleDateFormat("dd/MM/yy");
}
#Override
public CurrencyEvent readNextElementInternal() throws SourceException, IOException, FinalizedException, CatastrophicException {
//skipping all events which are not Trade
if (getReader().readRecord()) {
CurrencyEvent event = new CurrencyEvent();
//retrieving the currency
LTCurrency currency = getCurrencyDAO().getLTCurrencyByISOCode(getReader().get("CURRENCY"));
event.setCurrency(currency);
try {
event.setDate(getDateFormat().parse(getReader().get("DATE")));
} catch (ParseException e) {
throw new SourceException(e, "Parse error while reading currency event date");
}
event.setExchangeRate(new BigDecimal(getReader().get("MID")));
event.setComputationDate(Calendar.getInstance().getTime());
return event;
}
return null;
}
#Override
public char getDelimiter() {
return ';';
}
public SimpleDateFormat getDateFormat() {
return dateFormat;
}
public void setDateFormat(SimpleDateFormat dateFormat) {
this.dateFormat = dateFormat;
}
#Override
public List<String> getHeaderSet() {
return Arrays.asList(headers);
}
#Override
public String getName() {
return "CSV File";
}
}
}
}

I want to create a text file with name coming from user and the write in it?

I wrote this program for my uni Assignment. The main idea is when ever the addItem is invoked it creates a text file and write order from the user on that file. But how ever it only creates the file but prints nothing on the inside.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
public class OrderedFood extends Food {
private int quantity;
private boolean isSet;
private SetDrink setDrink;
public OrderedFood(){
quantity = 0;
isSet = false;
setDrink = null;
}
public OrderedFood(String foodCode, String foodName,boolean isSet, SetDrink setDrink, int quantity){
super(foodCode, foodName);
this.isSet = isSet;
this.quantity = quantity;
this.setDrink = setDrink;
}
public int getquantity(){
return quantity;
}
public void setquantity(int quantity){
this.quantity = quantity;
}
public boolean getIsSet(){
return isSet;
}
public void setisSet(boolean isSet){
this.isSet = isSet;
}
public SetDrink getsetDrink(){
return setDrink;
}
public void setsetDrink(SetDrink setDrink){
this.setDrink = setDrink;
}
public void addItem (String foodCode, int TabNum)throws IOException{
clearScreen(); // invoking the clearScreen method
String filename = Integer.toString(TabNum);
try
{
//this blocks creates a table by the table num
File file = new File("/tmp", filename);
System.out.println("path=" + file.getAbsolutePath());
file.createNewFile();
System.out.println("File created");
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Failed to create file");
}
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "utf-8")))
{
writer.write("foodCode"); // this syntax prints the order
writer.close();
}
}
public void deleteItem(String foodCode , int TabNum)throws IOException{
clearScreen();
String Tab = Integer.toString(TabNum);
remove(Tab,foodCode);// we just invoke the remove method, which will then remove the item from the .txt file
}
public static void clearScreen() { // this method clears the screen.
System.out.print("\033[H\033[2J");
System.out.flush();
}
public void remove(String file, String lineToRemove)throws IOException {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader buff = new BufferedReader(new FileReader(file));
PrintWriter kap = new PrintWriter(new FileWriter(tempFile));
String line = null;
while ((line = buff.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
kap.println(line);
kap.flush();
}
}
kap.close();
buff.close();
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
There is a logical mistake when you are creating a file you are not telling the extension also when opening the file for writing you used filename but it contains only the tabnumber not the full path to file use the below code
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
public class OrderedFood extends Food {
private int quantity;
private boolean isSet;
private SetDrink setDrink;
public OrderedFood(){
quantity = 0;
isSet = false;
setDrink = null;
}
public OrderedFood(String foodCode, String foodName,boolean isSet, SetDrink setDrink, int quantity){
super(foodCode, foodName);
this.isSet = isSet;
this.quantity = quantity;
this.setDrink = setDrink;
}
public int getquantity(){
return quantity;
}
public void setquantity(int quantity){
this.quantity = quantity;
}
public boolean getIsSet(){
return isSet;
}
public void setisSet(boolean isSet){
this.isSet = isSet;
}
public SetDrink getsetDrink(){
return setDrink;
}
public void setsetDrink(SetDrink setDrink){
this.setDrink = setDrink;
}
public void addItem (String foodCode, int TabNum)throws IOException{
clearScreen(); // invoking the clearScreen method
String filename = Integer.toString(TabNum);
try
{
//this blocks creates a table by the table num
File file = new File("/tmp", filename);
System.out.println("path=" + file.getAbsolutePath());
file.createNewFile();
filename = file.getAbsolutePath(); //here the actual address is updated to use later
System.out.println("File created");
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Failed to create file");
}
try
{
//now here we need that address updated earlier not just the tabnumber
PrintWriter writer = new PrintWriter(filename, "UTF-8");
writer.print("food code");
riter.close();
}
}
public void deleteItem(String foodCode , int TabNum)throws IOException{
clearScreen();
String Tab = Integer.toString(TabNum);
remove(Tab,foodCode);// we just invoke the remove method, which will then remove the item from the .txt file
}
public static void clearScreen() { // this method clears the screen.
System.out.print("\033[H\033[2J");
System.out.flush();
}
public void remove(String file, String lineToRemove)throws IOException {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader buff = new BufferedReader(new FileReader(file));
PrintWriter kap = new PrintWriter(new FileWriter(tempFile));
String line = null;
while ((line = buff.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
kap.println(line);
kap.flush();
}
}
kap.close();
buff.close();
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Java - Clipboard modification : Works in Eclipse, but not as JAR

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

Categories

Resources