Best way to handle awt.Image buffering in JavaFX - image

I have a class that takes a String parameter and performs a google search, then it gets the ten images and puts them in an array, that is then handled by another method in the same class. Using Javafx.scene.image would probably allow me to implement the buffering progress easily, but there is a bug with JavaFX Image, that misinterprets the color encoding of normal Images, and saves a weird looking image to the hard drive, so I just decided to use awt.Image.
This is the image search class:
public class GoogleCustomSearch {
static String key = //custom google id;
static String cx = // also a custom google id;
static String searchType = "image";
static java.awt.Image[] publicImageArray;
public static java.awt.Image[] Search(String searchParameter,int start) throws IOException, URISyntaxException{
String formatedText = URLEncoder.encode(searchParameter,"UTF-8");
URL url = new URL("https://www.googleapis.com/customsearch/v1?" + "key=" +key + "&cx=" +cx + "&q=" +formatedText + "&searchType=" +searchType +"&imgSize=medium" + "&start=" + start + "&num=10");
System.out.println(url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader( ( conn.getInputStream() ) ) );
GResults results = new Gson().fromJson(br, GResults.class);
java.awt.Image [] imageArray = new java.awt.Image[10];
//JProgressBar prb = new JProgressBar();
//MediaTracker loadTracker = new MediaTracker(prb);
for(int i = 0; i<10; i++){
try {
imageArray[i] = ImageIO.read(new URL(results.getLink(i)));
}catch (java.io.IOException e){
imageArray[i] = ImageIO.read(new File("C:\\Users\\FILIP.D\\IdeaProjects\\Manual_Artwork\\src\\MAT - NoImage.jpg"));
}
}
conn.disconnect();
return imageArray;
}
public static BufferedImage getImage(String searchPar, int index, boolean newSearch) throws IOException, URISyntaxException {
int adaptedIndex;
int start;
BufferedImage bimage;
if(index<10){
adaptedIndex = index;
start = 1;
}else if (index<20){
start = 11;
adaptedIndex = index % 10;
if(index == 10){
publicImageArray = new java.awt.Image[10];
publicImageArray = Search(searchPar,start);
}
}else if(index < 30){
start = 21;
adaptedIndex = index % 10;
if (index == 20) {
publicImageArray = new java.awt.Image[10];
publicImageArray = Search(searchPar,start);
}
}else{
adaptedIndex = index % 10;
start = 21; //ovo ce posle 30 da ga vrti u loop prvih 10
}
if(newSearch){
publicImageArray = new java.awt.Image[10];
publicImageArray = Search(searchPar,start);
return bimage = (BufferedImage) publicImageArray[adaptedIndex];
}else{
return bimage = (BufferedImage) publicImageArray[adaptedIndex];
}
}
public static RenderedImage getLiveImage (int index){
return (RenderedImage) publicImageArray[index % 10];
}
}
And this is the snippet of the main GUI class that just handles opening the new image in the array
private void nextImageResult() throws IOException, URISyntaxException {
if(imgNr == -1){
imgNr++;
changeImage(SwingFXUtils.toFXImage(GoogleCustomSearch.getImage(oppenedTrack.getArtistName() + "+" + oppenedTrack.getTrackName(),imgNr,true),null));
}else{
imgNr++;
changeImage(SwingFXUtils.toFXImage(GoogleCustomSearch.getImage(oppenedTrack.getArtistName() + "+" + oppenedTrack.getTrackName(),imgNr,false),null));
}
}
To summarise, I need a proper way to show a progress bar in the place of the image before it loads, and it needs not to hang the UI, for which I can use Task. I can optimise the loading of the array with MediaTracker, so it can prioritize loading the first few images first.

Related

dynamically change an image via c# script in Xamarin forms

I have a cross platform app which I need to show a set of images when the user clic in a button, so, I put these image files named as "img000.png" to "img029.png" in a folder in the PCL solution and make al these images as "EmbeddedResource", after,I fill a List with all these images and its work fine at now, i.e. the image is shown like I want, but when I click in the button to show the next image in the list the image don't go to the next.
I have this:
//...
public class ImageSetPage : BasePage
// BasePage encapsule a ContentPage...
{
private string directory = "MyApp.Assets.";
private int idx = 0;
protected StackLayout _mainLayout;
protected StackLayout _buttonStack;
protected Image _btnPrevI;
protected Label _displayName;
protected Image _btnNestI;
protected Image _image;
protected List<Image> _Images;
public ImageSetPage()
{
this._Images = getImages();
var prevI_Tap = new TapGestureRecognizer();
prevI_Tap.Tapped += (s, e) =>
{
onClick("pvi");
};
var nextI_Tap = new TapGestureRecognizer();
nextI_Tap.Tapped += (s, e) =>
{
onClick("nti");
};
/// begin layout
base.Title = "set of Images";
this._mainLayout = new StackLayout()
{
Orientation = StackOrientation.Vertical,
BackgroundColor = Color.Black,
Padding = new Thickness(0, 10, 0, 0)
};
this._btnPrevI = new Image()
{
Aspect = Aspect.AspectFill,
Source = ImageSource.FromResource(directory+"prevbtn.png")
};
_btnPrevI.GestureRecognizers.Add(prevI_Tap);
this._displayName = new Label()
{
Style = Device.Styles.SubtitleStyle,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand,
TextColor = Color.White,
};
this._btnNextI = new Image()
{
Aspect = Aspect.AspectFill,
Source = ImageSource.FromResource(directory + "nextbtn.png")
};
_btnNextI.GestureRecognizers.Add(nextI_Tap);
this._buttonStack.Children.Add(_btnPrevI);
this._buttonStack.Children.Add(_displayName);
this._buttonStack.Children.Add(_btnNextI);
this._mainLayout.Children.Add(_buttonStack);
FillImage(idx);
this._mainLayout.Children.Add(this._image);
this.Content = this._mainLayout;
}
private void FillImage(int i)
{
this._displayName.Text = "Image n# " + FillWithZeroes(i);
// [EDIT 1] cemented these lines ...
// this._image = null;
// mi = _images[i];
// this._image = mi;
// [EDIT 2] the new try
string f = directory + "imgs.img0" + FillWithZeroes(i) + ".png";
this._image = new Image() {
VerticalOptions = LayoutOptions.Center,
Soruce = ImageSource.FromResource(f)
};
// In this way the image show and don't change when click
// this Fking* code is a big S_OF_THE_B*
// The Xamarin and the C# is brothers of this FKing* code
}
private void onClick(string v)
{
string vw = v;
if (vw.Equals("pvi")) idx--;
if (vw.Equals("nti")) idx++;
if (idx <= 0) idx = 29;
if (idx >= 29) idx = 0;
FillImage(idx);
vw = "";
}
private string FillWithZeroes(int v)
{
string s = v.ToString();
string r = "";
if (s.Length == 1) { r = "0" + s; } else { r = s; }
return r;
}
// to fill a list of Images with files in a PCL folder
private List<Image> getImages()
{
string directory = "MyApp.Assets.";
List<Image> imgCards = new List<Image>();
int c = 0;
for (c = 0; c < 30;c++) {
string f = directory + "imgs.img0" + FillWithZeroes(c) + ".png";
Image img = new Image();
img.Source = ImageSource.FromResource(f);
imgCards.Add(img);
}
return imgCards;
}
// ...
}
but the image don't change, i.e. change, like I see in debug, but don't show in the Layout when I click in the buttons.
Maybe I'm doing it wrong.
Can someone here help me?
thanks in advance

Spring Boot example how to download file from server

I have a Spring Boot web application and I need an example of how to download a file from the server.
Thanks,
R.
I have this running project of SpringBoot. Below is a part of code which outputs xlsx file.
WebController.java
#RequestMapping(value = {"/excel"}, method = RequestMethod.GET)
public void excel(HttpServletResponse response, #RequestParam("email") String email) {
try {
Query query = new Query();
query.addCriteria(Criteria.where("email").is(email));
if(email.equals(""))
query=new Query();
List<MQTT_Server_Detail> list = mongoTemplate.find(query, MQTT_Server_Detail.class, "owner");
response.addHeader("Content-disposition", "attachment; filename=Door.xlsx");
response.setContentType("application/vnd.ms-excel");
Workbook workbook = new XSSFWorkbook();
workbook.createSheet("owner");
workbook.setSheetName(0, "Owner");
Sheet sheet = workbook.getSheetAt(0);
sheet.createRow(0);
sheet.getRow(0).createCell(0).setCellValue("Owner Email");
sheet.getRow(0).createCell(1).setCellValue("Topic");
sheet.getRow(0).createCell(2).setCellValue("Device Name");
sheet.getRow(0).createCell(3).setCellValue("Device ID");
Row row;
int num = 1;
for (MQTT_Server_Detail a : list) {
Devices devices = getDevice(a.getEmail());
for (int i = 0; i < devices.getDevicesID().size(); i++) {
row = sheet.createRow(num++);
row.createCell(0).setCellValue(a.getEmail());
row.createCell(1).setCellValue(a.getTopic());
row.createCell(2).setCellValue((String) devices.getDevicesName().get(i));
row.createCell(3).setCellValue((String) devices.getDevicesID().get(i));
}
}
sheet = workbook.createSheet("Users");
row = sheet.createRow(0);
row.createCell(0).setCellValue("Name");
row.createCell(1).setCellValue("Device");
row.createCell(2).setCellValue("CardID");
row.createCell(3).setCellValue("Email");
row.createCell(4).setCellValue("Mobile");
row.createCell(5).setCellValue("Blocked");
row.createCell(6).setCellValue("Last in Date");
row.createCell(7).setCellValue("Last in Time");
row.createCell(8).setCellValue("Last out Date");
row.createCell(9).setCellValue("Last out Time");
row.createCell(10).setCellValue("Owner");
Criteria criteria[] = new Criteria[list.size()];
for (int i = 0; i < list.size(); i++) {
criteria[i] = Criteria.where("owner").is(list.get(i).getEmail());
}
List<Users_POJO> users_pojoList;
if (list.size() == 0)
users_pojoList = new ArrayList<>();
else
users_pojoList = mongoTemplate.find(new Query().addCriteria(new Criteria().orOperator(criteria)),
Users_POJO.class, "users");
for (int i = 0; i < users_pojoList.size(); i++) {
row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(users_pojoList.get(i).getName());
row.createCell(1).setCellValue(users_pojoList.get(i).getDevice());
row.createCell(2).setCellValue(users_pojoList.get(i).getCard_id());
row.createCell(3).setCellValue(users_pojoList.get(i).getEmail());
row.createCell(4).setCellValue(users_pojoList.get(i).getMobile());
row.createCell(5).setCellValue(users_pojoList.get(i).getBlocked());
row.createCell(6).setCellValue(users_pojoList.get(i).getLast_in_date());
row.createCell(7).setCellValue(users_pojoList.get(i).getLast_in_time());
row.createCell(8).setCellValue(users_pojoList.get(i).getLast_out_date());
row.createCell(9).setCellValue(users_pojoList.get(i).getLast_out_time());
row.createCell(10).setCellValue(users_pojoList.get(i).getOwner());
}
sheet = workbook.createSheet("Logs");
row = sheet.createRow(0);
row.createCell(0).setCellValue("CardID");
row.createCell(1).setCellValue("Device");
row.createCell(2).setCellValue("Date");
row.createCell(3).setCellValue("Time");
row.createCell(4).setCellValue("Count");
criteria = new Criteria[users_pojoList.size()];
for (int i = 0; i < users_pojoList.size(); i++) {
criteria[i] = Criteria.where("card_id").is(users_pojoList.get(i).getCard_id());
}
query = new Query();
query.addCriteria(new Criteria().orOperator(criteria));
List<Log_POJO> log_pojoList;
if (users_pojoList.size() == 0)
log_pojoList = new ArrayList<>();
else
log_pojoList = mongoTemplate.find(query, Log_POJO.class, "logs");
for (int i = 0; i < log_pojoList.size(); i++) {
row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(log_pojoList.get(i).getCard_id());
row.createCell(1).setCellValue(log_pojoList.get(i).getDevice());
String date = log_pojoList.get(i).getDay() + "-" + log_pojoList.get(i).getMonth() + "-" + log_pojoList.get(i).getYear();
row.createCell(2).setCellValue(date);
String time = log_pojoList.get(i).getHour() + "-" + log_pojoList.get(i).getMin() + "-" + log_pojoList.get(i).getSec();
row.createCell(3).setCellValue(time);
row.createCell(4).setCellValue(log_pojoList.get(i).getSerial_no());
}
workbook.write(response.getOutputStream());
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
}
}
In short, you have to do this:
response.addHeader("Content-disposition", "attachment; filename=Door.xlsx");
response.setContentType("application/vnd.ms-excel");
//get the outputstream of response and write data to it
Spring Boot download file from server
#Controller
#RequestMapping(value = "/")
public class HomeController {
#RequestMapping(value = "/download", method = RequestMethod.GET)
public StreamingResponseBody getSteamingFile(HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"webpage.html\"");
InputStream inputStream = new FileInputStream(new File("C:\\MyWebPage\\webpage.html"));
return outputStream -> {
int nRead;
byte[] data = new byte[1024];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
outputStream.write(data, 0, nRead);
}
inputStream.close();
};
}
}

JavaFX App: creating a user-feedback, that the program is still working

I'm working on a Tool to read XML-files from a collection and write the information into a text-file. This process can take a few seconds and my program gets the "no response" in the title ...
Is there a simple way to inform the user, that the program is still working? like implementing a loading image or a 3-dot animation with a Label?
I have no experience with this topic
This is the current method to read the files and write the txt:
#FXML
public void FullFilterAndExport() throws JAXBException, IOException {
totalFilesCount = 0;
totalFilesCountPositive = 0;
PrintWriter pWriter = new PrintWriter(new BufferedWriter(new FileWriter(DB_Path.toString() + "\\export_full.txt")));
for(String file: FileList) {
if (file.endsWith(".xml") && !file.contains("databaseinfo.xml")) {
totalFilesCount = totalFilesCount +1;
ItemList.clear();
JAXBContext context = JAXBContext.newInstance(NotesDocumentMetaFile.class);
Unmarshaller um = context.createUnmarshaller();
NotesDocumentMetaFile docMetaFile = (NotesDocumentMetaFile) um.unmarshal(new FileReader(file));
for(int i = 0; i < docMetaFile.getItems().size(); i++) {
if(docMetaFile.getItems().get(i).getValueIsSpecial() == true) {
ItemList.add("Itemname:" + docMetaFile.getItems().get(i).getName());
}
}
if(!ItemList.isEmpty()) {
totalFilesCountPositive = totalFilesCountPositive + 1;
pWriter.println(file);
pWriter.println();
for(String item : ItemList) {
pWriter.println(item);
}
pWriter.println();
}
}
}
pWriter.println();
pWriter.println("------------------");
pWriter.println("Anzahl der geprüften Dateien: " + totalFilesCount);
pWriter.println("Anzahl der geprüften positiven Dateien: " + totalFilesCountPositive);
if (pWriter != null){
pWriter.flush();
pWriter.close();
}
}

Processing and Twitter4j, problems searching for tweets

I have processing 2.0 and twitter4j 3.0.3; when I try to run the program I get the error message
"The function "getTweet() does not exist".
I have tried getStatuses instead to no avail, I get the same error message that the function does not exist.
Help?
ArrayList<String> words = new ArrayList();
TwitterFactory twitterFactory;
Twitter twitter;
void setup() {
size(500, 500);
background(0);
smooth();
connectTwitter();
}
void draw() {
//draw fade rectangle
fill(0, 1);
rect(0, 0, width, height);
//draw arraylist words
int i = (frameCount % words.size());
String word = words.get(i);
fill(255, random(50, 150));
textSize(random(10, 30));
text(word, random(width), random(height));
}
// Initial connection
void connectTwitter() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("FvnrJfRMsMUCEhL0xxPegQ");
cb.setOAuthConsumerSecret("ZSnKgo6EQmq9wVd5gCMbufcMP5ztFuQhVwKpJvDhAY");
cb.setOAuthAccessToken("274686457-ZiYxpWchtcwHod7UXPjLCj18djl9CyNrk1HMqtQx");
cb.setOAuthAccessTokenSecret("kafd2QHznAu4Mu0R9x5HNyeyA4J3UwCOpETQYeDU");
twitterFactory = new TwitterFactory(cb.build());
twitter = twitterFactory.getInstance();
Query query = new Query("#BioshockInfinite");
query.setCount(100);
try {
QueryResult result = twitter.search(query);
ArrayList Status = (ArrayList) result.getTweet();
for (int i = 0; i < tweet.size(); i++) {
Status s = (Status) tweet.get(i);
User user = s.getUser;
String name = user.getName();
String msg = s.getText();
Date d = s.getCreatedAt();
println("Tweet by" + user + "at" + d + ":" + msg);
}
}
catch (TwitterException te) {
println("Couldn't connect:" + te);
}
}
I changed the line
ArrayList Status = (ArrayList) result.getTweet();
(which looks a bit odd anyway) to
List<Status> tweets = result.getTweets();
and I get Results now.
Eclipse showed an error that getTweet() wants a List to store the Tweets.

j2me midlet chinese character display message garbled

My J2ME midlet could retrieves message in Chinese character from a PHP server but it's garbled. The server basically returns the response string and by detecting the first 2 characters. AA = good, anything else indicates error of which the message is to be passed to the calling function for display
InputStream is = null;
StringBuffer sb = null;
String str = "";
HttpConnection http = null;
DataOutputStream dos = null;
try
{
URL = login.getURL();
URL += ctlFunction + "/" + uriStr;
URL = EncodeURL(URL);
//System.out.println(URL);
if(!ctlFunction.equals("login"))
{
msg += "&user=" + login.getUsername();
msg += "&token=" + login.getToken();
}
msg += "&lang=" + System.getProperty("microedition.locale");
// establish the connection
http = (HttpConnection) Connector.open(URL);
http.setRequestMethod(HttpConnection.POST);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setRequestProperty("Content-length", ""+EncodeURL(msg).getBytes().length);
dos = http.openDataOutputStream();
byte[] request_body = EncodeURL(msg).getBytes();
for (int i = 0; i < request_body.length; i++)
{
dos.writeByte(request_body[i]);
}
// server response
if (http.getResponseCode() == HttpConnection.HTTP_OK)
{
is = http.openDataInputStream();
int length = (int) http.getLength();
if (length != -1)
{
// Read data in one chunk
byte serverData[] = new byte[length];
is.read(serverData);
str = new String(serverData);
}
else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1)
bStrm.write(ch);
str = new String(bStrm.toByteArray());
bStrm.close();
}
}
else
{
networkError();
}
}
catch (Exception e)
{
System.err.println("Error3: " + e.toString());
networkError(e.toString());
}
finally
{
if (is != null)
is.close();
if (!str.equals(""))
post = str;
else
networkError();
if (http != null)
http.close();
}
if (post != null)
{
String fate = post.substring(0, 2);
if(fate.equals("AA"))
{
if(ctlFunction.equals("login"))
{
String rawPost = post.substring(2);
Vector v = new Vector();
int index = 0;
//find the first occurrence of the SPLITTER
int endIndex = rawPost.indexOf(SPLITTER, index);
String item = "";
//extract the items until the end of the last SPLITTER found in the rawPost string
while(endIndex != -1)
{
item = rawPost.substring(index, endIndex);
index = endIndex + 1;
endIndex = rawPost.indexOf(SPLITTER, index);
v.addElement(item);
}
//extract the rest of the rawPost (the text item)
item = rawPost.substring(index);
v.addElement(item);
String[] ret = new String[v.size()];
v.copyInto(ret);
login.setToken(ret[0]);
login.setToday(ret[1]);
login.setNextDrawDay(ret[2]);
}
midlet.returnResults(post.substring(2), getCurrentDisplay(), ctlFunction);
}
else
{
String errmessage = post.substring(2);
System.out.println(post);
midlet.showInfo(post, getCurrentDisplay());
}
}
else
{
networkError();
}
On the PHP server, I have set the header to UTF-8 encoding
<?php header("Content-Type:text/plain; charset=utf-8"); ?>
What could possibly be wrong?
I found that this user has the same problem and it's been answered
Reading UTF8 strings from a server through http using MIDP. Kudos to the answer.
I basically edited my MIDP code from
// is = http.openDataInputStream();
// int length = (int) http.getLength();
// if (length != -1)
// {
// // Read data in one chunk
// byte serverData[] = new byte[length];
// is.read(serverData);
// str = new String(serverData);
// }
// else // Length not available...
// {
// ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
// int ch;
// while ((ch = is.read()) != -1)
// bStrm.write(ch);
//
// str = new String(bStrm.toByteArray());
// bStrm.close();
// }
to
Reader r = new InputStreamReader(http.openInputStream(), "UTF-8");
int ch;
while((ch = r.read()) != -1)
str = str + (char)ch;
just wondering though why does reading bytes messes up the UTF-8 characters?

Resources