Getting filename that was used on setGraphic() - javafx-8

I am currently working on a puzzle type of app on javaFX. I created a 2d array of buttons that I used setGraphic to insert the pictures. I am wondering if there is a way to retrieve the filename that I used on setGraphic so I can compare to pictures together. I know there is a getGraphic method but that returns random numbers.

setGraphic takes a Node, not a Image object; I assume you use ImageViews as graphics.
There is no way to retrieve the file name from an Image object since you need not pass a url to the Image constructor but are also allowed to pass a InputStream. InputStream does not provide any information about it's source and Image also doesn't.
To get the file path from a image you need to store the information yourself, e.g.:
private final Map<Image, String> imageFileNames = new IdentityHashMap<>();
public Image loadImage(String filename) throws MalformedURLException {
File file = new File(filename);
Image image = new Image(file.toURI().toURL().toExternalForm());
imageFileNames.put(image, filename);
return image;
}
public String getImageFileName(Image image) {
return imageFileNames.get(image);
}
With a node containing a ImageView as a graphic, you could do something like this:
ImageView view = (ImageView) node.getGraphic();
Image img = view.getImage();
String fileName = getImageFieldName(img);
Possibly adding null checks, if the graphic and/or the image can be null.
You could also the data in the node's userData or properties if you like:
Storing
File file = new File(filename);
ImageView imageView = new ImageView(file.toURI().toURL().toExternalForm());
imageView.setUserData(filename);
Retrieving
String filename = (String) node.getGraphic().getUserData();

Related

I am trying to add more content to an existing excel file, can anyone tell me is there any method can be used from gembox.speadsheet?

I already have the path of the Excel file, but whenever I call save method, the program writes new content to UTC.xlsx file.
string pathString = "C:\Users\ADMIN-PC\Documents\SUMMER 2018\PRN192\CreateFile\SubFolder\UTC.xlsx";
ef.Save(pathString);
var path = #"C:\Users\ADMIN-PC\Documents\SUMMER 2018\PRN192\CreateFile\SubFolder\UTC.xlsx";
// Load the workbook:
var workbook = ExcelFile.Load(path);
// Manipulate the workbook …
// … and save it over the original
workbook.Save(path);

GWT getting image from database using RPC and display it in the UI

I am trying to make an image uploading widget and store the image in the GWT database so it can be read from it later. Here's the code:
Servlet (HttpServletRequest request)
/* */
iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
InputStream stream = item.openStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
Blob content = new Blob(out.toByteArray());
/* */
Entity
public class ImageEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Enumerated
private Blob image;
/* */
RCP implementation
/* */
public String getImageData(Long id){
EntityManager em = EMF.get();
jtwitter.shared.Image image = em.find(jtwitter.shared.Image.class, id);
Blob blobData = image.getImage();
System.out.println(blobData.getBytes().length);;
byte[] imageData = image.getImage().getBytes();
System.out.println(imageData.length);
String base64 = Base64Utils.toBase64(imageData);
base64 = "data:image/png;base64,"+ base64;
return base64;
}
public String getImageData(Long id){
EntityManager em = EMF.get();
jtwitter.shared.Image image = em.find(jtwitter.shared.Image.class, id);
Blob blobData = image.getImage();
System.out.println(blobData.getBytes().length);;
byte[] imageData = image.getImage().getBytes();
System.out.println(imageData.length);
String base64 = Base64Utils.toBase64(imageData);
base64 = "data:image/png;base64,"+ base64;
return base64;
}
/* */
On the client side I'm calling com.google.gwt.user.client.ui.Image img = new Image(getImageData's result). All I get is a broken image icon, right clicking on it gives image code in bytes. I've tried comparing sizes and original image size is same as the one read inside the getImageData's method.
Thanks for reading,
P.
Have you tried something like:
HTML html = new HTML("<img src=\""+getImageData's result+"\" alt=\"Foo\">");
Or have you tried with other B64 util class?
Other option is generate a url from your DB and pass it to your image instead of all the B64 data (we are doing this and it works well).
Thanks,
Adolfo.
I'm wondering why you want to create your own upload widget and not use a library like gwtupload which gives you many things out-of-the-box.
Anyway, and related with your question about how to get the saved image in the ddbb, I would never use RPC to get the image and show it in the UI, but a servlet to return the binary image, which has been the normal way for ages.
Using RPC has many caveats:
You have to convert images to base-64 strings, which increases a lot the size
RPC mechanism has to deal with large strings in both client and server sides, penalizing the performance (serialization/deserialization, escaping, memory issues, etc).
RCP is not cacheable, so the client is going to download always the image
I think this is not in your query, but if you wanted the image in b64 in client you can do it in any browser supporting canvas.
In summary, I would follow the DRY principle with gwtupload: Using SingleUploader or MultipleUploader in client, extending UploadAction in server, and overriding executeAction() to save uploaded files to the DDBB and getUploadedFile() to get the file back.
Your problem is that you are using bad implementation of a B64. For some reason beyond me the actualy B64 supplied by com.google.appengine.api doesn't work with the apache uploader. Instead you should use this http://iharder.net/base64

Upload Servlet with custom file keys

I have built a Server that you can upload files to and download, using Eclipse, servlet and jsp, it's all very new to me. (more info).
Currently the upload system works with the file's name. I want to programmatically assign each file a random key. And with that key the user can download the file. That means saving the data in a config file or something like : test.txt(file) fdjrke432(filekey). And when the user inputs the filekey the servlet will pass the file for download.
I have tried using a random string generator and renameTo(), for this. But it doesn't work the first time, only when I upload the same file again does it work. And this system is flawed, the user will receive the file "fdjrke432" instead of test.txt, their content is the same but you can see the problem.
Any thoughts, suggestions or solutions for my problem?
Well Sebek, I'm glad you asked!! This is quite an interesting one, there is no MAGIC way to do this. The answer is indeed to rename the file you uploaded. But I suggest adding the random string before the name of the file; like : fdjrke432test.txt.
Try this:
filekey= RenameRandom();
File renamedUploadFile = new File(uploadFolder + File.separator+ filekey+ fileName);
item.write(renamedUploadFile);
//remember to give the user the filekey
with
public String RenameRandom()
{
final int LENGTH = 8;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random()*26)+97));
}
System.out.println(sb.toString());
return sb.toString();
}
To delete or download the file from the server you will need to locate it, the user will input the key, you just need to search the upload folder for a file that begins with that key:
filekey= request.getParameter("filekey");
File f = new File(getServletContext().getRealPath("") + File.separator+"data");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(filekey);
}
});
String newfilename = matchingFiles[0].getName();
// now delete or download newfilename

Getting line locations with iText

How can one find where are lines located in a document with iText?
Suppose say I have a table in a PDF document, and want to read its contents; I would like to find where exactly the cells are located. In order to do that I thought I might find the intersections of lines.
I think your only option using iText will be to parse the PDF tokens manually. Before doing that I would have a copy of the PDF spec handy.
(I'm a .Net guy so I use iTextSharp but other than some capitalization differences and property declarations they're almost 100% the same.)
You can get the individual tokens using the PRTokeniser object which you feed bytes into from calling getPageContent(pageNum) on your PdfReader.
//Get bytes for page 1
byte[] pageBytes = reader.getPageContent(1);
//Get the tokens for page 1
PRTokeniser tokeniser = new PRTokeniser(pageBytes);
Then just loop through the PRTokeniser:
PRTokeniser.TokType tokenType;
string tokenValue;
while (tokeniser.nextToken()) {
tokenType = tokeniser.tokenType;
tokenValue = tokeniser.stringValue;
//...check tokenValue, do something with it
}
As far a tokenValue, you'd want to probably look for re and l values for rectangle and line. If you see an re then you want to look at the previous 4 values and if you see an l then previous 2 values. This also means that you need to store each tokenValue in an array so you can look back later.
Depending on what you used to create the PDF with you might get some interesting results. For instance, I created a 4 cell table with Microsoft Word and saved as a PDF. For some reason there are two sets of 10 rectangles with many duplicates, but the general idea still works.
Below is C# code targeting iTextSharp 5.1.1.0. You should be able to convert it to Java and iText very easily, I noted the one line that has .Net-specific code that needs to be adjusted from a Generic List (List<string>) to a Java equivalent, probably an ArrayList. You'll also need to adjust some casing, .Net uses Object.Method() whereas Java uses Object.method(). Lastly, .Net accesses properties without gets and sets, so Object.Property is both the getter and setter compared to Java's Object.getProperty and Object.setProperty.
Hopefully this gets you started at least!
//Source file to read from
string sourceFile = "c:\\Hello.pdf";
//Bind a reader to our PDF
PdfReader reader = new PdfReader(sourceFile);
//Create our buffer for previous token values. For Java users, List<string> is a generic list, probably most similar to an ArrayList
List<string> buf = new List<string>();
//Get the raw bytes for the page
byte[] pageBytes = reader.GetPageContent(1);
//Get the raw tokens from the bytes
PRTokeniser tokeniser = new PRTokeniser(pageBytes);
//Create some variables to set later
PRTokeniser.TokType tokenType;
string tokenValue;
//Loop through each token
while (tokeniser.NextToken()) {
//Get the types and value
tokenType = tokeniser.TokenType;
tokenValue = tokeniser.StringValue;
//If the type is a numeric type
if (tokenType == PRTokeniser.TokType.NUMBER) {
//Store it in our buffer for later user
buf.Add(tokenValue);
//Otherwise we only care about raw commands which are categorized as "OTHER"
} else if (tokenType == PRTokeniser.TokType.OTHER) {
//Look for a rectangle token
if (tokenValue == "re") {
//Sanity check, make sure we have enough items in the buffer
if (buf.Count < 4) throw new Exception("Not enough elements in buffer for a rectangle");
//Read and convert the values
float x = float.Parse(buf[buf.Count - 4]);
float y = float.Parse(buf[buf.Count - 3]);
float w = float.Parse(buf[buf.Count - 2]);
float h = float.Parse(buf[buf.Count - 1]);
//..do something with them here
}
}
}

EncodedImage.getEncodedImageResource fail to load image with the same name different subfolder in Eclipse (Blackberry plugin)

I'm using the Blackberry JDE Plugin v1.3 for Eclipse and I'm trying this code to create a BitmapField and I've always done it this way:
this.bitmap = EncodedImage.getEncodedImageResource("ico_01.png");
this.bitmap = this.bitmap.scaleImage32(
this.conf.getWidthScale(), this.conf.getHeightScale());
this.imagenLoad = new BitmapField(this.bitmap.getBitmap(), this.style);
It works fine with no errors, but now I have this set of images with the same name but in different subfolders like this:
I made it smaller than it actually is for explanatory reasons. I wouldn't want to rename the files so they're all different. I would like to know how to access the different subfolders. "res/img/on/ico_01.jpg", "img/on/ico_01.jpg", "on/ico_01.jpg" are some examples that I tried and failed.
It appears that EncodedImage.getEncodedImageResource(filename) will retrieve the first instance of filename regardless of where it is in your resource directory tree.
This is not very helpful if you have the images with the same filename in different directories (as you have).
The solution I have used is to create my own method which can return an image based on a path and filename.
public static Bitmap getBitmapFromResource(String resourceFilename){
Bitmap imageBitmap = null;
//get the image as a byte stream
InputStream imageStream = getInstance().getClass().getResourceAsStream(resourceFilename);
//load it into memory
byte imageBytes[];
try {
imageBytes = IOUtilities.streamToBytes(imageStream);
//create the bitmap
imageBitmap = Bitmap.createBitmapFromBytes(imageBytes, 0, imageBytes.length, 1);
} catch (IOException e) {
Logger.log("Error loading: "+resourceFilename+". "+e.getMessage());
}
return imageBitmap;
}