I created a chat in Java, which displays the messages sent and received on the screen. The problem is that when sending the message it is picking up the previously sent value. For example, I send the message written "Microsoft", and then I send another message written "Apple", when the display shows "Applesoft", it appears that it is not emptying DatagramPacket. What can be done?
class Recebe implements Runnable {
#Override
public void run() {
byte[] dadosReceber = new byte[255];
boolean erro = false;
DatagramSocket socket = null;
while (true) {
try {
socket = new DatagramSocket(getPorta());
} catch (SocketException ex) {
Logger.getLogger(Conexao.class.getName()).log(Level.SEVERE, null, ex);
}
erro = false;
while (!erro) {
DatagramPacket pacoteRecebido = new DatagramPacket(dadosReceber, dadosReceber.length);
try {
socket.receive(pacoteRecebido);
byte[] b = pacoteRecebido.getData();
String s = "";
for (int i = 0; i < b.length; i++) {
if (b[i] != 0) {
s += (char) b[i];
System.out.println("Valor S: " + s + " ");
}
}
// if (!s.equals(new GeraHash().MD5("envie a chave publica!!!"))) {
String nome = pacoteRecebido.getAddress().toString() + " disse:";
notifica(nome + s);
System.out.println("Dados Recebe 2: " + s + " ");
// } else {
// conexaoAtual().envia("Funcionou!");
// System.out.println("Dados Recebe 1: " + s + " ");
// }
} catch (Exception e) {
System.out.println("erro");
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Conexao.class.getName()).log(Level.SEVERE, null, ex);
}
erro = true;
continue;
}
}
}
}
}
socket.receive(pacoteRecebido);
byte[] b = pacoteRecebido.getData();
String s = "";
for (int i = 0; i < b.length; i++) {
if (b[i] != 0) {
s += (char) b[i];
System.out.println("Valor S: " + s + " ");
}
Usual problem. You're ignoring the actual length of the received datagram, given by DatagramPacket.getLength(). You can reduce all that to:
socket.receive(pacoteRecebido);
System.out.println(new String(pacoteRecebido.getData(), 0, pacoteRecebido.getLength());
Related
I have implemented this java app communicating with a remote 8 modem server and when I request for an image from a security camera (error free or not) the outcome is a 1 byte image (basically a small white square). Can you help me find the error?
Here is my code:
import java.io.*;
import java.util.Scanner;
import ithakimodem.Modem;
public class g {
private static Scanner scanner = new Scanner(System.in);
private static String EchoCode = "E3369";
private static String noImageErrorscode = "M2269";
private static String imageErrorsCode = "G6637";
private static String GPS_Code = "P7302";
private static String ACK_Code = "Q2591";
private static String NACK_Code = "R4510";
public static void main(String[] args) throws IOException, InterruptedException {
int timeout = 2000;
int speed = 80000;
Modem modem = new Modem(speed);
modem.setTimeout(timeout);
modem.write("ATD2310ITHAKI\r".getBytes());
getConsole(modem);
modem.write(("test\r").getBytes());
getConsole(modem);
while (true) {
System.out.println("\nChoose one of the options below :");
System.out.print("Option 0: Exit\n" + "Option 1: Echo packages\n" + "Option 2: Image with no errors\n" + "Option 3: Image with errors\n" + "Option 4: Tracks of GPS\n"
+ "Option 5: ARQ\n" );
System.out.print("Insert option : ");
int option = scanner.nextInt();
System.out.println("");
switch (option) {
case 0: {
// Exit
System.out.println("\nExiting...Goodbye stranger");
modem.close();
scanner.close();
return;
}
case 1: {
// Echo
getEcho(modem, EchoCode);
break;
}
case 2: {
// Image with no errors
getImage(modem, noImageErrorscode, "no_error_image.jpg");
break;
}
case 3: {
// Image with errors
getImage(modem, imageErrorsCode, "image_with_errors.jpg");
}
case 4: {
// GPS
getGPS(modem, GPS_Code);
break;
}
case 5: {
// ARQ
getARQ(modem, ACK_Code, NACK_Code);
break;
}
default:
System.out.println("Try again please\n");
}
}
}
public static String getConsole(Modem modem) {
int l;
StringBuilder stringBuilder= new StringBuilder();
String string = null;
while (true) {
try {
l = modem.read();
if (l == -1) {
break;
}
System.out.print((char) l);
stringBuilder.append((char) l);
string = stringBuilder.toString();
} catch (Exception exc) {
break;
}
}
System.out.println("");
return string;
}
private static void getImage(Modem modem, String password, String fileName) throws IOException {
int l;
boolean flag;
FileOutputStream writer = new FileOutputStream(fileName, false);
flag = modem.write((password + "\r").getBytes());
System.out.println("\nReceiving " + fileName + "...");
if (!flag) {
System.out.println("Code error or end of connection");
writer.close();
return;
}
while (true) {
try {
l = modem.read();
writer.write((char) l);
writer.flush();
if (l == -1) {
System.out.println("END");
break;
}
}
catch (Exception exc) {
break;
}
}
writer.close();
}
private static void getGPS(Modem modem, String password) throws IOException {
int rows = 99;
String Rcode = "";
Rcode = password + "R=10200" + rows;
System.out.println("Executing R parameter = " + Rcode + " (XPPPPLL)");
modem.write((Rcode + "\r").getBytes());
String stringConsole = getConsole(modem);
if (stringConsole == null) {
System.out.println("Code error or end of connection");
return;
}
String[] stringRows = stringConsole.split("\r\n");
if (stringRows[0].equals("n.a")) {
System.out.println("Error : Packages not received");
return;
}
System.out.println("**TRACES**\n");
float l1 = 0, l2 = 0;
int difference = 8;
difference *= 100 / 60;
int traceNumber = 7;
String[] traces = new String[traceNumber + 1];
int tracesCounter = 0, flag = 0;
for (int i = 0; i < rows; i++) {
if (stringRows[i].startsWith("$GPGGA")) {
if (flag == 0) {
String str = stringRows[i].split(",")[1];
l1 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
flag = 1;
}
String str = stringRows[i].split(",")[1];
l2 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
if (Math.abs(l2 - l1) >= difference) {
traces[tracesCounter] = stringRows[i];
if (tracesCounter == traceNumber)
break;
tracesCounter++;
l1 = l2;
}
}
}
for (int i = 0; i < traceNumber; i++) {
System.out.println(traces[i]);
}
String w = "", T_cd_fnl = password + "T=";
int p = 1;
System.out.println();
for (int i = 0; i < traceNumber; i++) {
String[] strSplit = traces[i].split(",");
System.out.print("T parameter = ");
String str1 = strSplit[4].substring(1, 3);
String str2 = strSplit[4].substring(3, 5);
String str3= String.valueOf(Integer.parseInt(strSplit[4].substring(6, 10)) * 60 / 100).substring(0, 2);
String str4= strSplit[2].substring(0, 2);
String str5= strSplit[2].substring(2, 4);
String str6= String.valueOf(Integer.parseInt(strSplit[2].substring(5, 9)) * 60 / 100).substring(0, 2);
w = str1 + str2 + str3 + str4 + str5 + str6 + "T";
p = p + 5;
System.out.println(w);
T_cd_fnl = T_cd_fnl + w + "=";
}
T_cd_fnl = T_cd_fnl.substring(0, T_cd_fnl.length() - 2);
System.out.println("\nSending code: " + T_cd_fnl);
getImage(modem, T_cd_fnl, "traces GPS.jpg");
}
private static void getEcho(Modem modem, String strl) throws InterruptedException, IOException {
FileOutputStream echo_time_writer = new FileOutputStream("echoTimes.txt", false);
FileOutputStream echo_counter_writer = new FileOutputStream("echoCounter.txt", false);
int h;
int runtime = 5, packetCounter = 0;
String str = "";
System.out.println("\nRuntime (mins) = " + runtime + "\n");
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receiveTime = 0;
String time = "", ClockTime = "";
echo_time_writer.write("Clock Time\tSystem Time\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
packetCounter++;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
while (true) {
try {
h = modem.read();
System.out.print((char) h);
str += (char) h;
if ( h== -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (str.endsWith("PSTOP")) {
receiveTime = System.currentTimeMillis();
ClockTime = str.substring(18, 26) + "\t";
time = String.valueOf((receiveTime - send_time) + "\r\n");
echo_time_writer.write(ClockTime.getBytes());
echo_time_writer.write(time.getBytes());
echo_time_writer.flush();
str = "";
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
}
echo_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
echo_counter_writer.write(("\r\nPackets Received: " + String.valueOf(packetCounter)).getBytes());
echo_counter_writer.close();
echo_time_writer.close();
}
private static void getARQ(Modem modem, String strl, String nack_code) throws IOException, InterruptedException {
FileOutputStream arq_time_writer = new FileOutputStream("ARQtimes.txt", false);
FileOutputStream arq_counter_writer = new FileOutputStream("ARQcounter.txt", false);
int runtime = 5;
int xor = 1;
int f = 1;
int m;
int packageNumber = 0;
int iterationNumber = 0;
int[] nack_times_counter = new int[15];
int nack_to_package = 0;
String time = "", clock_time = "", s = "";
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receive_time = 0;
System.out.printf("Runtime (mins) = " + runtime + "\n");
arq_time_writer.write("Clock Time\tSystem Time\tPacket Resends\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
if (xor == f) {
packageNumber++;
nack_times_counter[nack_to_package]++;
nack_to_package = 0;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
} else {
iterationNumber++;
nack_to_package++;
modem.write((nack_code + "\r").getBytes());
}
while (true) {
try {
m = modem.read();
System.out.print((char) m);
s += (char) m;
if (m == -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (s.endsWith("PSTOP")) {
receive_time = System.currentTimeMillis();
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
String[] string = s.split("<");
string = string[1].split(">");
f = Integer.parseInt(string[1].substring(1, 4));
xor = string[0].charAt(0) ^ string[0].charAt(1);
for (int i = 2; i < 16; i++) {
xor = xor ^ string[0].charAt(i);
}
if (xor == f) {
System.out.println("Packet ok");
receive_time = System.currentTimeMillis();
time = String.valueOf((receive_time - send_time) + "\t");
clock_time = s.substring(18, 26) + "\t";
arq_time_writer.write(clock_time.getBytes());
arq_time_writer.write(time.getBytes());
arq_time_writer.write((String.valueOf(nack_to_package) + "\r\n").getBytes());
arq_time_writer.flush();
} else {
xor = 0;
}
s = "";
}
arq_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
arq_counter_writer.write("\r\nPackets Received (ACK): ".getBytes());
arq_counter_writer.write(String.valueOf(packageNumber).getBytes());
arq_counter_writer.write("\r\nPackets Resent (NACK): ".getBytes());
arq_counter_writer.write(String.valueOf(iterationNumber).getBytes());
arq_counter_writer.write("\r\nNACK Time Details".getBytes());
for (int i = 0; i < nack_times_counter.length; i++) {
arq_counter_writer.write(("\r\n" + i + ":\t" + nack_times_counter[i]).getBytes());
}
arq_counter_writer.close();
arq_counter_writer.close();
System.out.println("Packets Received: " + packageNumber);
System.out.println("Packets Resent: " + iterationNumber);
System.out.println("\n\nFile arqTimes.txt is created.");
System.out.println("File arqCounter.txt is created.");
}
}
I know the problem is most probably in the getImage() function but I haven't figured it out yet.
I'm making the bot for Google Dictionary using this API https://dictionaryapi.dev/. It's supposed to show word definitions in different languages. And the bot works just fine for English and Spanish. But there's an IOException every time I put in Russian words. What can be the cause of it?
Here's my Bot class.
Bot.java:
public void onUpdateReceived(Update update) {
//Model model = new Model();
WordModel wordModel = new WordModel();
Message message = update.getMessage();
if (message != null && message.hasText())
{
switch (message.getText()) {
case "/english":
DictionaryEntry.setLanguage("en");
sendMsg(message, DictionaryEntry.getLanguage());
break;
case "/russian":
DictionaryEntry.setLanguage("ru");
sendMsg(message, DictionaryEntry.getLanguage());
break;
case "/spanish":
DictionaryEntry.setLanguage("es");
sendMsg(message, DictionaryEntry.getLanguage());
break;
default:
if (!message.getText().contains("/")) {
try {
sendMsgs(message, DictionaryEntry.getWords(message.getText(), wordModel));
} catch (IOException e) {
sendMsg(message, "Не найдено");
sendMsg(message, DictionaryEntry.getUrl().toString());
}
}
break;
}
}
}
public void sendMsg(Message message, String text) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(message.getChatId());
sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setText(text);
try {
//setButtons(sendMessage);
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
public void sendMsgs(Message message, List<String> words) {
for (int i = 0; i < words.size(); i++) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(message.getChatId());
sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setText(words.get(i));
try {
//setButtons(sendMessage);
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
And here's my DictionaryEntry class where I process JSON string that I get from URL.
DictionaryEntry.java:
private static String language = "ru";
public static String getLanguage() {
return language;
}
public static void setLanguage(String language) {
DictionaryEntry.language = language;
}
public static URL getUrl() {
return url;
}
private static URL url;
public static List<String> getWords(String message, WordModel wordModel) throws IOException {
url = new URL("https://api.dictionaryapi.dev/api/v2/entries/"
+ DictionaryEntry.getLanguage() + "/" + message);
Scanner in = new Scanner((InputStream) url.getContent());
String result = "";
while (in.hasNext())
{
result += in.nextLine();
}
String result2 = result.replaceAll("\"", "\\\"");
List<WordModel> models = new ArrayList<>();
List<String> results = new ArrayList<>();
int count = 0;
try {
JSONArray mainArray = new JSONArray(result2);
for (int i = 0; i < mainArray.length(); i++) {
JSONObject wordEntry = mainArray.getJSONObject(i);
String wordName = wordEntry.getString("word");
wordModel.setWord(wordName);
JSONArray meaningsArray = wordEntry.getJSONArray("meanings");
for (int j = 0; j < meaningsArray.length(); j++) {
JSONObject meaningEntry = meaningsArray.getJSONObject(j);
JSONArray definitionsArray = meaningEntry.getJSONArray("definitions");
for (int k = 0; k < definitionsArray.length(); k++) {
//count++;
JSONObject definitionEntry = definitionsArray.getJSONObject(k);
String definition = definitionEntry.getString("definition");
wordModel.setDefinition(definition);
if (definitionEntry.has("example")) {
count++;
String example = definitionEntry.getString("example");
wordModel.setExample(example);
}
else {
wordModel.setExample("No examples found");
}
models.add(wordModel);
results.add("Word: " + wordModel.getWord() + "\n\n" +
"Definition: " + wordModel.getDefinition() + "\n\n" +
"Example: " + wordModel.getExample());
}
}
}
/*result = "Word: " + wordModel.getWord() + "\n\n" +
"Definition: " + wordModel.getDefinition() + "\n\n" +
"Example: " + wordModel.getExample();*/
} catch (JSONException e) {
count = 50;
}
results.add(url.toString());
return results;
}
Here's the stack trace:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.dictionaryapi.dev/api/v2/entries/ru/мышь
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1932)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1528)
at java.base/java.net.URLConnection.getContent(URLConnection.java:749)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getContent(HttpsURLConnectionImpl.java:404)
at java.base/java.net.URL.getContent(URL.java:1181)
at DictionaryEntry.getWords(DictionaryEntry.java:73)
at Bot.onUpdateReceived(Bot.java:91)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.telegram.telegrambots.meta.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:321)
+ URLEncoder.encode(message, "UTF-8")
You are sending a HTTP request. The URL should be appropriate for the used encoding.
There are more aspects of using the right charset/encoding, but this might already be sufficient. The site probably uses UTF-8, as that can handle the full Unicode range.
400 is BAD REQUEST.
url = new URL("https://api.dictionaryapi.dev/api/v2/entries/"
+ DictionaryEntry.getLanguage() + "/"
+ URLEncoder.encode(message, "UTF-8"));
And
Scanner in = new Scanner((InputStream) url.getContent(),
StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
while (in.hasNextLine())
{
sb.append(in.nextLine()).append('\n');
}
String result = sb.toString();
Check in your environment that the file was in utf-8u format Because Cyrillic may not be supported
I'm trying to read gmail messages using showmsg.java in the javamail sample package, and I keep getting this error when I run it. The program compiles fine though.
Here's the error message:
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/internet/ParseException
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: javax.mail.internet.ParseException
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
Here's the code:
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.event.*;
import javax.mail.internet.*;
/*
* Demo app that exercises the Message interfaces.
* Show information about and contents of messages.
*
* #author John Mani
* #author Bill Shannon
*/
public class msgshow {
static String protocol;
static String host = null;
static String user = null;
static String password = null;
static String mbox = null;
static String url = null;
static int port = -1;
static boolean verbose = false;
static boolean debug = false;
static boolean showStructure = false;
static boolean showMessage = false;
static boolean showAlert = false;
static boolean saveAttachments = false;
static int attnum = 1;
public static void main(String argv[]) {
int optind;
InputStream msgStream = System.in;
for (optind = 0; optind < argv.length; optind++) {
if (argv[optind].equals("-T")) {
protocol = argv[++optind];
} else if (argv[optind].equals("-H")) {
host = argv[++optind];
} else if (argv[optind].equals("-U")) {
user = argv[++optind];
} else if (argv[optind].equals("-P")) {
password = argv[++optind];
} else if (argv[optind].equals("-v")) {
verbose = true;
} else if (argv[optind].equals("-D")) {
debug = true;
} else if (argv[optind].equals("-f")) {
mbox = argv[++optind];
} else if (argv[optind].equals("-L")) {
url = argv[++optind];
} else if (argv[optind].equals("-p")) {
port = Integer.parseInt(argv[++optind]);
} else if (argv[optind].equals("-s")) {
showStructure = true;
} else if (argv[optind].equals("-S")) {
saveAttachments = true;
} else if (argv[optind].equals("-m")) {
showMessage = true;
} else if (argv[optind].equals("-a")) {
showAlert = true;
} else if (argv[optind].equals("--")) {
optind++;
break;
} else if (argv[optind].startsWith("-")) {
System.out.println(
"Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
System.out.println(
"\t[-P password] [-f mailbox] [msgnum ...] [-v] [-D] [-s] [-S] [-a]");
System.out.println(
"or msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
System.exit(1);
} else {
break;
}
}
try {
// Get a Properties object
Properties props = System.getProperties();
// Get a Session object
Session session = Session.getInstance(props, null);
session.setDebug(debug);
if (showMessage) {
MimeMessage msg;
if (mbox != null)
msg = new MimeMessage(session,
new BufferedInputStream(new FileInputStream(mbox)));
else
msg = new MimeMessage(session, msgStream);
dumpPart(msg);
System.exit(0);
}
// Get a Store object
Store store = null;
if (url != null) {
URLName urln = new URLName(url);
store = session.getStore(urln);
if (showAlert) {
store.addStoreListener(new StoreListener() {
public void notification(StoreEvent e) {
String s;
if (e.getMessageType() == StoreEvent.ALERT)
s = "ALERT: ";
else
s = "NOTICE: ";
System.out.println(s + e.getMessage());
}
});
}
store.connect();
} else {
if (protocol != null)
store = session.getStore(protocol);
else
store = session.getStore();
// Connect
if (host != null || user != null || password != null)
store.connect(host, port, user, password);
else
store.connect();
}
// Open the Folder
Folder folder = store.getDefaultFolder();
if (folder == null) {
System.out.println("No default folder");
System.exit(1);
}
if (mbox == null)
mbox = "INBOX";
folder = folder.getFolder(mbox);
if (folder == null) {
System.out.println("Invalid folder");
System.exit(1);
}
// try to open read/write and if that fails try read-only
try {
folder.open(Folder.READ_WRITE);
} catch (MessagingException ex) {
folder.open(Folder.READ_ONLY);
}
int totalMessages = folder.getMessageCount();
if (totalMessages == 0) {
System.out.println("Empty folder");
folder.close(false);
store.close();
System.exit(1);
}
if (verbose) {
int newMessages = folder.getNewMessageCount();
System.out.println("Total messages = " + totalMessages);
System.out.println("New messages = " + newMessages);
System.out.println("-------------------------------");
}
if (optind >= argv.length) {
// Attributes & Flags for all messages ..
Message[] msgs = folder.getMessages();
// Use a suitable FetchProfile
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.FLAGS);
fp.add("X-Mailer");
folder.fetch(msgs, fp);
for (int i = 0; i < msgs.length; i++) {
System.out.println("--------------------------");
System.out.println("MESSAGE #" + (i + 1) + ":");
dumpEnvelope(msgs[i]);
// dumpPart(msgs[i]);
}
} else {
while (optind < argv.length) {
int msgnum = Integer.parseInt(argv[optind++]);
System.out.println("Getting message number: " + msgnum);
Message m = null;
try {
m = folder.getMessage(msgnum);
dumpPart(m);
} catch (IndexOutOfBoundsException iex) {
System.out.println("Message number out of range");
}
}
}
folder.close(false);
store.close();
} catch (Exception ex) {
System.out.println("Oops, got exception! " + ex.getMessage());
ex.printStackTrace();
System.exit(1);
}
System.exit(0);
}
public static void dumpPart(Part p) throws Exception {
if (p instanceof Message)
dumpEnvelope((Message)p);
/** Dump input stream ..
InputStream is = p.getInputStream();
// If "is" is not already buffered, wrap a BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream))
is = new BufferedInputStream(is);
int c;
while ((c = is.read()) != -1)
System.out.write(c);
**/
String ct = p.getContentType();
try {
pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
} catch (ParseException pex) {
pr("BAD CONTENT-TYPE: " + ct);
}
String filename = p.getFileName();
if (filename != null)
pr("FILENAME: " + filename);
/*
* Using isMimeType to determine the content type avoids
* fetching the actual content data until we need it.
*/
if (p.isMimeType("text/plain")) {
pr("This is plain text");
pr("---------------------------");
if (!showStructure && !saveAttachments)
System.out.println((String)p.getContent());
} else if (p.isMimeType("multipart/*")) {
pr("This is a Multipart");
pr("---------------------------");
Multipart mp = (Multipart)p.getContent();
level++;
int count = mp.getCount();
for (int i = 0; i < count; i++)
dumpPart(mp.getBodyPart(i));
level--;
} else if (p.isMimeType("message/rfc822")) {
pr("This is a Nested Message");
pr("---------------------------");
level++;
dumpPart((Part)p.getContent());
level--;
} else {
if (!showStructure && !saveAttachments) {
/*
* If we actually want to see the data, and it's not a
* MIME type we know, fetch it and check its Java type.
*/
Object o = p.getContent();
if (o instanceof String) {
pr("This is a string");
pr("---------------------------");
System.out.println((String)o);
} else if (o instanceof InputStream) {
pr("This is just an input stream");
pr("---------------------------");
InputStream is = (InputStream)o;
int c;
while ((c = is.read()) != -1)
System.out.write(c);
} else {
pr("This is an unknown type");
pr("---------------------------");
pr(o.toString());
}
} else {
// just a separator
pr("---------------------------");
}
}
/*
* If we're saving attachments, write out anything that
* looks like an attachment into an appropriately named
* file. Don't overwrite existing files to prevent
* mistakes.
*/
if (saveAttachments && level != 0 && p instanceof MimeBodyPart &&
!p.isMimeType("multipart/*")) {
String disp = p.getDisposition();
// many mailers don't include a Content-Disposition
if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
if (filename == null)
filename = "Attachment" + attnum++;
pr("Saving attachment to file " + filename);
try {
File f = new File(filename);
if (f.exists())
// XXX - could try a series of names
throw new IOException("file exists");
((MimeBodyPart)p).saveFile(f);
} catch (IOException ex) {
pr("Failed to save attachment: " + ex);
}
pr("---------------------------");
}
}
}
public static void dumpEnvelope(Message m) throws Exception {
pr("This is the message envelope");
pr("---------------------------");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
pr("FROM: " + a[j].toString());
}
// REPLY TO
if ((a = m.getReplyTo()) != null) {
for (int j = 0; j < a.length; j++)
pr("REPLY TO: " + a[j].toString());
}
// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++) {
pr("TO: " + a[j].toString());
InternetAddress ia = (InternetAddress)a[j];
if (ia.isGroup()) {
InternetAddress[] aa = ia.getGroup(false);
for (int k = 0; k < aa.length; k++)
pr(" GROUP: " + aa[k].toString());
}
}
}
// SUBJECT
pr("SUBJECT: " + m.getSubject());
// DATE
Date d = m.getSentDate();
pr("SendDate: " +
(d != null ? d.toString() : "UNKNOWN"));
// FLAGS
Flags flags = m.getFlags();
StringBuffer sb = new StringBuffer();
Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags
boolean first = true;
for (int i = 0; i < sf.length; i++) {
String s;
Flags.Flag f = sf[i];
if (f == Flags.Flag.ANSWERED)
s = "\\Answered";
else if (f == Flags.Flag.DELETED)
s = "\\Deleted";
else if (f == Flags.Flag.DRAFT)
s = "\\Draft";
else if (f == Flags.Flag.FLAGGED)
s = "\\Flagged";
else if (f == Flags.Flag.RECENT)
s = "\\Recent";
else if (f == Flags.Flag.SEEN)
s = "\\Seen";
else
continue; // skip it
if (first)
first = false;
else
sb.append(' ');
sb.append(s);
}
String[] uf = flags.getUserFlags(); // get the user flag strings
for (int i = 0; i < uf.length; i++) {
if (first)
first = false;
else
sb.append(' ');
sb.append(uf[i]);
}
pr("FLAGS: " + sb.toString());
// X-MAILER
String[] hdrs = m.getHeader("X-Mailer");
if (hdrs != null)
pr("X-Mailer: " + hdrs[0]);
else
pr("X-Mailer NOT available");
}
static String indentStr = " ";
static int level = 0;
/**
* Print a, possibly indented, string.
*/
public static void pr(String s) {
if (showStructure)
System.out.print(indentStr.substring(0, level * 2));
System.out.println(s);
}
}
The command I'm using to run is java msgshow -D -T imaps -H imap.gmail.com -U [USER] -P [PASS] and the command I'm using to compile it is javac -cp ".:./:./lib:./lib/*" msgshow.java. The javax.mail.jar is contained in the lib folder
This is some alternate code that's much shorter and gets the same errors:
import java.util.*;
import java.io.*;
import javax.mail.*;
import smtp;
import imaps;
//import java.mail.*;
//import com.sun.mail.*;
public class AccessGmail {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
try
{
Properties prop = new Properties();
prop.load(new FileInputStream(new File("smtp.properties")));
Session session = Session.getDefaultInstance(prop, null);
String pass = scan.next();
Store store = session.getStore("imaps");
store.connect("smtp.gmail.com","shane.l.gvoice#gmail.com",pass);
Folder inbox = store.getFolder("inbox");
inbox.open(Folder.READ_ONLY);
int messageCount = inbox.getMessageCount();
System.out.println("Message Count: "+messageCount);
}
catch (FileNotFoundException e){}
catch (IOException e){}
catch(NoSuchProviderException e){}
catch(MessagingException e){}
}
}
You're not setting the CLASSPATH when you're running the program so it's not finding the javax.mail.jar file:
java -cp ".:lib/javax.mail.jar" msgshow -D -T imaps -H imap.gmail.com -U [USER] -P [PASS]
So, I'm trying to create a function (If not pretty) IRC client using no libraries, written in Java. I've gotten almost everything working, the only problem is that I'm currently getting user input using System.in. And if someone else in the channel sends a message while I'm in the middle of typing, it cuts off what I currently have, and I need to guess where I am in the string. I want to know if there's a way to separate user input from the output of the program, so that this doesn't happen. This is the code in question:
new Thread(() -> {
while(connected[0]) {
String output = sc.nextLine();
if(!output.startsWith("~") && !output.startsWith("/")) {
try {
writeToSocket("PRIVMSG " + focused[0] + " " + output);
} catch (IOException e) {
e.printStackTrace();
}
}
if(output.substring(1).toLowerCase().startsWith("quit")) {
String[] split = output.substring(5).split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
if(i == 0) {
sb.append(split[i]);
}
sb.append(" ").append(split[i]);
}
try {
writeToSocket("QUIT " + sb.toString());
connected[0] = false;
} catch (IOException e) {
e.printStackTrace();
}
}else if(output.substring(1).toLowerCase().startsWith("focus")) {
String get = output.substring(7);
if(!channels.contains(get)) {
print("Not connected to channel");
}else {
try {
writeToSocket("PART " + focused[0]);
writeToSocket("JOIN " + get);
} catch (IOException e) {
e.printStackTrace();
}
focused[0] = get;
}
}else if(output.substring(1).toLowerCase().startsWith("join")) {
String get = output.substring(6);
channels.add(get);
}
if(output.startsWith("/") && output.substring(1).toLowerCase().startsWith("msg")) {
String[] split = output.substring(5).split(" ");
String username = split[0];
StringBuilder msg = new StringBuilder();
for(int i = 1; i < split.length; i++) {
if(i == 1) {
msg.append(split[i]);
continue;
}
msg.append(" ").append(split[i]);
}
try {
writeToSocket("PRIVMSG " + username + " " + msg.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}