Java IO not displaying file data - java-io

Okay, I guess I'm stuck here. Can't get the values from the file to show in JOptionPane's message dialog box where it's enclosed within a while loop.
Right now I don't know which method of Input/Output stream to use to display all the data on this file which I believed to be serialized as UTF8??
Please tell me what to do and what things I missed since I'm new to java.io classes.
Also, the file StudentData.feu was just given to me. It's not that I don't want to research on my own because I already did, I'm just stuck. I read the Javadoc but I'm clueless right now.
import java.io.*;
import javax.swing.JOptionPane;
public class MyProj {
public void showMenu() {
String choice = JOptionPane.showInputDialog
(null, "Please enter a number: " + "\n[1] All Students" + "\n[2] BSCS Students" + "\n[3] BSIT Students"
+ "\n[4] BSA Students" + "\n[5] First Year Students" + "\n[6] Second Year Students" + "\n[7] Third Year Students"
+ "\n[8] Passed Students" + "\n[9] Failed Students" + "\n[0] Exit");
int choiceConvertedString = Integer.parseInt(choice);
switch(choiceConvertedString){
case 0:
JOptionPane.showMessageDialog(null, "Program closed!");
System.exit(1);
break;
}
}
DataInputStream myInputStream;
OutputStream myOutputStream;
int endOfFile = -1;
double grades;
int studentNo;
int counter;
String studentName;
String studentCourse;
public void readFile()
{
try
{
myInputStream = new DataInputStream
(new FileInputStream("C:\\Users\\Jordan's Pc\\Documents\\NetBeansProjects\\MyProj\\StudentData.feu"));
try{
while((counter=myInputStream.read()) != endOfFile)
{
studentName = myInputStream.readUTF();
studentCourse = myInputStream.readUTF();
grades = myInputStream.readDouble();
JOptionPane.showMessageDialog
(null, "StdNo: " + studentNo + "\n"
+ "Student Name: " + studentName + "\n"
+ "Student Course: " + studentCourse + "\n"
+ "Grades: " + grades);
}
}
catch(FileNotFoundException fnf){
JOptionPane.showMessageDialog(null, "File Not Found");
}
}/* end of try */
catch(EOFException ex)
{
JOptionPane.showMessageDialog(null, "Processing Complete");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "An error occured");
}
}
}

while((counter=myInputStream.read()) != endOfFile)
The problem is probably here. You're reading a byte and then throwing it away. It isn't likely that the file contains extra bytes like this that are intended to be thrown away. The correct loop would go like this:
try
{
for (;;)
{
// .... readUTF() etc
}
}
catch (EOFException exc)
{
// You've read to end of file.
}
// catch IOException etc.

Related

Convert logic to Streams (Java) (nested for loops with counter)

Dears,
I'm new to Streams and want to convert some logic to using them:
this is the logic:
for (String headerKey : map.keySet()) {
int counter = 1;
for (String value : map.get(headerKey)) {
if (map.get(headerKey).size() != 1) {
System.out.println("Response header: " + headerKey + "[" + counter++ + "]: " + value);
} else {
System.out.println("Response header: " + headerKey + ": " + value);
}
}
}
the problem is the "counter"...
I got as far as:
private static long after(Map<String, List<String>> map) {
return map.keySet().stream().map(key -> output(key, map)).count(); // use print() here instead of output()
}
private static String output(String key, Map<String, List<String>> map) {
counter = 1;
long longString = map.get(key).stream().map(value -> print(value, key, map.get(key))).count();
return "" + longString;
}
private static String print(String value, String key, List<String> strings) {
if (strings.size() != 1) {
System.out.println("Response header: " + key + "[" + counter++ + "]: " + value);
} else {
System.out.println("Response header: " + key + ": " + value);
}
return "";
}
And I suppose I can put the print() method at the indicated spot,
but I don't know how to get the counter to behave as in the original code...
All comment/ideas are welcome :)
Thanks beforehand!
Create a helper method like
static Stream<String> values(List<?> list) {
return list.size() == 1? Stream.of(": " + list.get(0)):
IntStream.range(0, list.size()).mapToObj(ix -> "[" + ix + "]: " + list.get(ix));
}
Instead of re-evaluating the list.size() == 1 condition in each iteration, it selects the right shape of the operation upfront. When the size is not one, rather than trying to maintain a counter, stream over the index range in the first place.
This method now can be used when streaming over the map, like
map.entrySet().stream()
.flatMap(e -> values(e.getValue()).map(("Response header: " + e.getKey())::concat))
.forEach(System.out::println);

Raw ESCP Printing through Socket JAVA

I have this Raw ESC/POS command for LX-300+, and i want to print it through Print Server using Socket.
String escp = " '\x1B' + '\x40', // initialize the printer, reset printer to defaults " +
" '\x1B' + '\x78' + '\x31', // Set Print Quality NLQ " +
" '\x1B' + '\x6B' + '\x31', // Select typeface San serif " +
" '\x1B' + '\x43' + '\x00' + '\x06', // set Page Length to 6 Inch " +
" '\x1B' + '\x4D', // Select 12 cpi Spacing " +
" '\x1B' + '\x45', // SET Bold Font ";
Question is, can we parse that String of escp with Socket? i use this code,
Socket socket = null;
OutputStream output = null;
BufferedReader reader = null;
try {
socket = new Socket("10.0.5.30", 9100);
socket.setSoTimeout(5000);
output = socket.getOutputStream();
reader = new BufferedReader(new java.io.InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
// TODO: handle exception
}
if (socket != null && output != null) {
try
{
output.write(escp.getBytes());
output.flush();
socket.shutdownOutput();
output.close();
socket.close();
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
The result is, printer LX-300 is not converting the ESC/POS Command. Just print the String inside escp variable. Any solution to this? i'm using linux 18.04 FYI.

ESP32 WifiClientSecure no response

I'm working on a project using a google script to publish images from an ESP32-CAM to google drive.
I keep getting the error "no response", no matter how long I set the wait peroid to. I tried using http and https(wificlient and wificlientsecure) but it doesn't work no matter what.
What could be the issue?
WiFiClientSecure clienthttps;
Serial.println("Connect to " + String(myDomain));
if (clienthttps.connect(myDomain, 443)) {
Serial.println("Connection successful");
camera_fb_t * fb = NULL;
fb = esp_camera_fb_get();
if (!fb) {
Serial.println("Camera capture failed");
delay(1000);
ESP.restart();
return;
}
char *input = (char *)fb->buf;
char output[base64_enc_len(3)];
String imageFile = "";
for (int i = 0; i < fb->len; i++) {
base64_encode(output, (input++), 3);
if (i % 3 == 0) imageFile += urlencode(String(output));
}
String Data = myFilename + mimeType + myImage;
esp_camera_fb_return(fb);
Serial.println("Send a captured image to Google Drive.");
Serial.println("POST " + myScript + " HTTP/1.1");
Serial.println("Host: " + String(myDomain));
Serial.println("Content-Length: " + String(Data.length() + imageFile.length()));
Serial.println("Content-Type: application/x-www-form-urlencoded");
Serial.println(Data);
Serial.println();
clienthttps.println("POST " + myScript + " HTTP/1.1");
clienthttps.println("Host: " + String(myDomain));
clienthttps.println("Content-Length: " + String(Data.length() + imageFile.length()));
clienthttps.println("Content-Type: application/x-www-form-urlencoded");
clienthttps.println();
clienthttps.print(Data);
int Index;
for (Index = 0; Index < imageFile.length(); Index = Index + 1000) {
clienthttps.print(imageFile.substring(Index, Index + 1000));
}
Serial.println("Waiting for response.");
long int StartTime = millis();
while (!clienthttps.available()) {
Serial.print(".");
delay(100);
if ((StartTime + waitingTime) < millis()) {
Serial.println();
Serial.println("No response.");
//If you have no response, maybe need a greater value of waitingTime
break;
}
}
Serial.println();
while (clienthttps.available()) {
Serial.print(char(clienthttps.read()));
}
} else {
Serial.println("Connected to " + String(myDomain) + " failed.");
}
clienthttps.stop();
Note that in the latest "github.com/espressif/arduino-esp32" (as at 17Jan23) the command
"WiFiClientSecure.println();" (your "clienthttps.println()") seems to corrupt the SSL-buffer somehow, and although the command returns after a bit, the SSL-connection fails at that point (this didn't happen in earlier versions of the software).
The solution which worked for me was to ensure I at very least sent "WiFiClientSecure.println(" ");" (ie. " \r\n") as this seems to work.
(This solution appears also often necessary if sending data over a GPRS connection because in that instance a ".println()" seems to be ingored!)

How do I send email using java6?

There is some big chunk of code on old server(java 1.6.025). It builds sql query. It has too many dependencies with other classes, and I can't just take it out and test standalone.
So I decided to just run it AS-IS on server except inject some "send.Email()" code and just see what it does.
sb.append("</key>");
}
sb.append("</" + st.tableName + ">");
sb.append("</" + s + ">");
}
sb.append("</" + this.select.selectName + ">");
// XMLFunctions.addInfo("sb before os.write " + sb.toString());
this.os.write(sb.toString().getBytes("utf-8"));
//CODE HERE
}
catch (UnsupportedEncodingException e) {
XMLFunctions.addWarning((String)(String.valueOf(e.getClass().getCanonicalName()) + ": " + e.getMessage()));
}
What code would work on java6?
EDIT: my class does not have main() where I can initialize email properties..

How can we improve the Update / Write operation on BaseX datastore?

I am using BaseX (XML based datastore) for its performance benchmarking. For testing it with ,
TestBeds
I) 10,000 users, 10 friends, 10 resources
II) 100,000 users , 10 friends, 10 resources
I faced below issues:
1) Loading of data is too slow. Gets slowed with eh increase in the number of threads.
2) Plus point - Reading/retriving values from BaseX is faster (17k operation per second)
3) Updating the data in BaseX is very slow. Throughput is ~10 operations per second.
Am I correct to say BaseX is 'TOO' slow for write/update operations (20/sec) compared to read/retrieve (10k/sec)?
Please advice me to make it more efficient for the write and update :
I have a function insertEntity (update or insert function) in to the BaseX datastore as follows -
public int insertEntity(String entitySet, String entityPK,
HashMap<String, ByteIterator> values, boolean insertImage) {
String parentTag ="",childTag ="", key="", entryTag="";
StringBuffer insertData = new StringBuffer();
Set<String> keys = values.keySet();
Iterator<String> iterator = keys.iterator();
while(iterator.hasNext()) {
String entryKey = iterator.next();
if(!(entryKey.equalsIgnoreCase("pic") || entryKey.equalsIgnoreCase("tpic")))
insertData.append("element " + entryKey + " {\"" + StringEscapeUtils.escapeXml(values.get(entryKey).toString()) + "\"},");
}
if(entitySet.equalsIgnoreCase("users")&& insertImage){
byte[] profileImage = ((ObjectByteIterator)values.get("pic")).toArray();
String encodedpImage = DatatypeConverter.printBase64Binary(profileImage);
insertData.append(" element pic {\"" + encodedpImage + "\"},");
profileImage = ((ObjectByteIterator)values.get("tpic")).toArray();
encodedpImage = DatatypeConverter.printBase64Binary(profileImage);
insertData.append(" element tpic {\"" + encodedpImage + "\"},");
}
if(entitySet.equalsIgnoreCase("users"))
{
parentTag = "users";
childTag = "members";
entryTag = "member";
key = "mem_id";
insertData.append("element confirmed_friends {}, element pending_friends {}");
}
if(entitySet.equalsIgnoreCase("resources"))
{
parentTag = "resources";
childTag = "resources";
entryTag = "resource";
key = "rid";
insertData.append("element manipulations {}");
}
try {
session.execute(new XQuery(
"insert node element " + entryTag
+ "{ attribute " + key + "{"
+ entityPK + "}, "
+ insertData.toString()
+ "} "
+ "into doc('" + databaseName + "/" + parentTag +".xml')/" + childTag
));
String q1 = "insert node element " + entryTag
+ "{ attribute " + key + "{"
+ entityPK + "}, "
+ insertData.toString()
+ "} "
+ "into doc('" + databaseName + "/" + parentTag +".xml')/" + childTag;
System.out.println(q1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
And the below function is acceptFriendship (update function)
public int acceptFriend(int inviterID, int inviteeID) {
// TODO Auto-generated method stub
String acceptFriendQuery1 = "insert node <confirmed_friend id = '"
+ inviterID + "'>"
+ " </confirmed_friend>"
+ "into doc('"+databaseName+"/users.xml')/members/member[#mem_id = '"+inviteeID+"']/confirmed_friends";
String acceptFriendQuery2 = "insert node <confirmed_friend id = '"
+ inviteeID + "'>"
+ " </confirmed_friend>"
+ "into doc('"+databaseName+"/users.xml')/members/member[#mem_id = '"+inviterID+"']/confirmed_friends";
String acceptFriendQuery3 = "delete node doc('"+databaseName+"/users.xml')/members/member[#mem_id = '"
+ inviteeID + "']/pending_friends/pending_friend[#id = '"+ inviterID +"']";
try {
session.execute(new XQuery(acceptFriendQuery1));
session.execute(new XQuery(acceptFriendQuery2));
session.execute(new XQuery(acceptFriendQuery3));
System.out.println("Inviter: "+inviterID +" AND Invitee: "+inviteeID);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}

Resources