java.lang.NoSuchMethodError: No direct method <init>(Ljava/lang/Object;) - java

I have an application in which I connected with a device which is connected by USB when I start to ping this device my application is crashed. This device is a RFID scanner which is connected to the phone by USB. A phone and my application see the connected phone with this scanner.
This is a code :
#Override
public synchronized void run() {
if (context == null || usbDevice == null) {
onStatusChanged(Status.NoContextOrUsbDeviceSpecified);
return;
}
//l("Device -> " + usbDevice);
UsbInterface usbInterface = null;
UsbEndpoint usbEndpointIn = null;
UsbEndpoint usbEndpointOut = null;
for (int i = 0; i < usbDevice.getInterfaceCount(); i++) {
usbInterface = usbDevice.getInterface(i);
//l("Interface[" + i + "] -> " + usbInterface);
if (usbInterface != null) {
for (int j = 0; j < usbInterface.getEndpointCount(); j++) {
UsbEndpoint usbEndpoint = usbInterface.getEndpoint(j);
//l("Endpoint[" + j + "] -> " + usbEndpoint);
if (usbEndpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (usbEndpoint.getDirection() == UsbConstants.USB_DIR_IN) {
l("Found input!");
usbEndpointIn = usbEndpoint;
}
else {
l("Found output!");
usbEndpointOut = usbEndpoint;
}
if (usbEndpointIn != null && usbEndpointOut != null) {
break;
}
}
}
if (usbEndpointIn != null && usbEndpointOut != null) {
break;
}
}
else {
//l("Interface was null");
}
}
if (usbEndpointIn == null || usbEndpointOut == null) {
onStatusChanged(Status.NoEndpointsFoundOnUsbDevice);
return;
}
UsbManager usbManager = (UsbManager)context.getSystemService(Context.USB_SERVICE);
UsbDeviceConnection usbDeviceConnection = usbManager.openDevice(usbDevice);
if (usbDeviceConnection == null) {
onStatusChanged(Status.CouldntOpenUsbDeviceConnection);
return;
}
if (!usbDeviceConnection.claimInterface(usbInterface, true)) {
onStatusChanged(Status.CouldntClaimUsbDeviceInterface);
return;
}
onStatusChanged(Status.ScanningInitializing);
currentUsbDeviceConnection = usbDeviceConnection;
currentUsbInterface = usbInterface;
currentUsbEndpointIn = usbEndpointIn;
currentUsbEndpointOut = usbEndpointOut;
// Toast.makeText(context,send(PING) + " wysłane" , Toast.LENGTH_LONG).show();
final String[] a = new String[1];
pingingThread = new Thread(() -> {
onStatusChanged(Status.PingStarted);
String s = "";
for (byte aPING : PING) {
s = s + aPING;
}
Log.e("Ping " , s);
String aa ="";
for (byte aACK : ACK) {
aa = aa + aACK;
}
Log.e("ACK " , aa);
while (shouldPing && !Thread.interrupted()) {
if (send(PING) >= 0) {
onStatusChanged(Status.PingSuccessful);
} else {
onStatusChanged(Status.PingFailed);
}
SystemClock.sleep(PING_RECEIVE_TIMEOUT / 3);
}
onStatusChanged(Status.PingStopped);
scheduleStopReceiving();
});
byte[] bytes = new byte[36];
int result = currentUsbDeviceConnection.bulkTransfer(currentUsbEndpointIn, bytes, bytes.length, RECEIVE_TIMEOUT);
// Toast.makeText(context, "result " + result , Toast.LENGTH_LONG ).show();
receivingThread = new Thread(() -> {
onStatusChanged(Status.ReceivingStarted);
long lastTagTimestamp = 0;
boolean wasInterrupted = false;
while (shouldReceive) {
byte[] received = receive(36);
if (received != null) {
if (received[0] != (byte) 0xab ||
received[1] != (byte) 0xba ||
received[2] != (byte) 0xcd ||
received[3] != (byte) 0xdc) {
onStatusChanged(Status.ReceivedUnknown);
} else if (received[4] == 0x00) {
if (send(ACK) < 0) {
continue;
}
onStatusChanged(Status.ReceivedTag);
lastTagTimestamp = System.currentTimeMillis();
byte[] tag = new byte[8];
int index = 0;
while (index < tag.length) {
tag[index++] = received[8 + index];
}
long longValue = ByteBuffer.wrap(tag).getLong();
String hexValue = Long.toHexString(longValue).toUpperCase();
onScanCompleted(hexValue);
} else if (received[4] == 0x02) {
onStatusChanged(Status.ReceivedPing);
}
}
if (Thread.interrupted()) {
wasInterrupted = true;
}
if (wasInterrupted) {
if (lastTagTimestamp == 0) {
lastTagTimestamp = System.currentTimeMillis();
}
if (lastTagTimestamp + PING_RECEIVE_TIMEOUT < System.currentTimeMillis()) {
break;
}
}
}
onStatusChanged(Status.ReceivingStopped);
close();
});
shouldPing = true;
shouldReceive = true;
pingingThread.start();
receivingThread.start();
}
In this line I have
java.lang.NoSuchMethodError: No direct method
(Ljava/lang/Object;)V in class
Lrest/hello/org/usbdevice/rfid2/-$Lambda$2; or its super classes
(declaration of 'rest.hello.org.usbdevice.rfid2.-$Lambda$2' appears in
/data/app/rest.hello.org.usbdevice-2/base.apk)
pingingThread = new Thread(() -> {
onStatusChanged(Status.PingStarted);
String s = "";
for (byte aPING : PING) {
s = s + aPING;
}
Log.e("Ping " , s);
String aa ="";
for (byte aACK : ACK) {
aa = aa + aACK;
}
Log.e("ACK " , aa);

Related

EOFException DataInputStream.readFully

Basically I'm helping a friend of mine out,
There's a disconnection error with his game (runescape private server) and there's an error that keeps being thrown, which is
DataInputStream.readFully(Unknown Source)
at Client.streamLoaderForName(Client.java:7343)
I read some things up on using while(in.available() > 0), but I don't know where it'd be placed.
This is the method where the error occurs
private CacheArchive streamLoaderForName(int i, String s, String s1, int j, int k)
{
byte abyte0[] = null;
int l = 5;
try
{
if(cacheIndices[0] != null)
abyte0 = cacheIndices[0].get(i);
}
catch(Exception _ex) { }
if(abyte0 != null)
{
CacheArchive streamLoader = new CacheArchive(abyte0);
return streamLoader;
}
int j1 = 0;
while(abyte0 == null)
{
String s2 = "Unknown error";
setLoadingText(k, "Requesting " + s);
Object obj = null;
try
{
int k1 = 0;
DataInputStream datainputstream = jaggrabRequest(s1 + j);
byte[] abyte1 = new byte[6];
datainputstream.readFully(abyte1, 0, 6);
Stream stream = new Stream(abyte1);
stream.currentOffset = 3;
int i2 = stream.read3Bytes() + 6;
int j2 = 6;
abyte0 = new byte[i2];
System.arraycopy(abyte1, 0, abyte0, 0, 6);
while(j2 < i2)
{
int l2 = i2 - j2;
if(l2 > 1000)
l2 = 1000;
int j3 = datainputstream.read(abyte0, j2, l2);
if(j3 < 0)
{
s2 = "Length error: " + j2 + "/" + i2;
throw new IOException("EOF");
}
j2 += j3;
int k3 = (j2 * 100) / i2;
k1 = k3;
}
datainputstream.close();
try
{
if(cacheIndices[0] != null)
cacheIndices[0].put(abyte0.length, abyte0, i);
}
catch(Exception _ex)
{
cacheIndices[0] = null;
}
}
catch(IOException ioexception)
{
ioexception.printStackTrace();
if(s2.equals("Unknown error"))
s2 = "Connection error";
abyte0 = null;
}
catch(NullPointerException _ex)
{
s2 = "Null error";
abyte0 = null;
}
catch(ArrayIndexOutOfBoundsException _ex)
{
s2 = "Bounds error";
abyte0 = null;
}
catch(Exception _ex)
{
s2 = "Unexpected error";
abyte0 = null;
}
if(abyte0 == null)
{
for(int l1 = l; l1 > 0; l1--)
{
if(j1 >= 3)
{
setLoadingText(k, "Game updated - please reload page");
l1 = 10;
} else
{
setLoadingText(k, s2 + " - Retrying in " + l1);
}
try
{
Thread.sleep(1000L);
}
catch(Exception _ex) { }
}
l *= 2;
if(l > 60)
l = 60;
}
}
CacheArchive streamLoader_1 = new CacheArchive(abyte0);
return streamLoader_1;
}
I can't seem to find out where to do any placements or how to fix this error. By the way, the line that's 7343, is
datainputstream.readFully(abyte1, 0, 6);
Also sorry for the poor thread, I don't know how to write it up properly on this.

Submit Hadoop Map Reduce Job With Secondary Data File?

I'm trying to do a Map-Reduce job on big text file which contains my data. To process this data I actually need another array to do lookup's with the data I'm processing.
So ideally the reducers would load this file and populate the array, then start reducing.
I'm trying to use Google Cloud platform because I get £250 free computation, Without going into massive detail about the project, I'm new to map-reduce, only having done a small university course on extreme computing and need a little direction for the best way to achieve this. There are a few things I haven't fixed yet like the output types etc but what I'm struggling with is the setup() function, exactly how to populate my array before the reducer starts reducing, any help would be greatly appreciated!
public static class MapForEquityCalculator extends Mapper<LongWritable, Text, Text, IntWritable> {
public int GetIndex(int R1, int R2, boolean IsSuited) {
if (IsSuited) {
return (int)(((13 - Math.ceil((double)Math.max(R1, R2) / 4)) * 13) + (13 - Math.ceil((double)Math.min(R1, R2) / 4)));
} else {
return (int)(((13 - Math.ceil((double)Math.min(R1, R2) / 4)) * 13) + (13 - Math.ceil((double)Math.max(R1, R2) / 4)));
}
}
public void map(LongWritable key, Text value, Context con) throws IOException, InterruptedException {
String line = value.toString();
String[] cards=line.split(",");
int ind_1 = GetIndex(Integer.parseInt(cards[0]),Integer.parseInt(cards[1]),Integer.parseInt(cards[0])%4 == Integer.parseInt(cards[1])%4);
int ind_2 = GetIndex(Integer.parseInt(cards[2]),Integer.parseInt(cards[3]),Integer.parseInt(cards[2])%4 == Integer.parseInt(cards[3])%4);
int ind_3 = GetIndex(Integer.parseInt(cards[4]),Integer.parseInt(cards[5]),Integer.parseInt(cards[4])%4 == Integer.parseInt(cards[4])%4);
Text outputKey = new Text(Integer.toString(ind_1) +"," + Integer.toString(ind_2) +"," + Integer.toString(ind_3));
Text outputValue = new Text(line);
con.write(outputKey, outputValue);
}
}
public static class ReduceForEquityCalculator extends Reducer<Text, IntWritable, Text, IntWritable> {
public static final int HandRankSize = 32487834;
public static int HR[] = new int[HandRankSize];
protected static final int littleEndianByteArrayToInt(byte[] b, int offset) {
return (b[offset + 3] << 24) + ((b[offset + 2] & 0xFF) << 16)
+ ((b[offset + 1] & 0xFF) << 8) + (b[offset] & 0xFF);
}
public void setup(Context context) throws IOException{
Path pt=new Path("gs://mybucket/HandRanks.dat");
Configuration conf = new Configuration();
FileSystem fs = pt.getFileSystem(conf);
int tableSize = HandRankSize*4;
byte[] b = new byte[tableSize];
try {
FileInputStream fr = new FileInputStream(fs.open(pt));
int bytesRead = fr.read(b, 0, tableSize);
if (bytesRead != tableSize) {
}
fr.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
for (int i = 0; i < HandRankSize; i++) {
HR[i] = littleEndianByteArrayToInt(b, i * 4);
}
}
public void reduce(Text word, Text value, Context con) throws IOException, InterruptedException {
String line = value.toString();
String[] cards_string=line.split(",");
Integer[] cards = new Integer[cards_string.length];
int i=0;
for(String str:cards_string){
cards[i]=Integer.parseInt(str);//Exception in this line
i++;
}
int c0, c1, c2, c3, c4, c5, c6;
int u0, u1, u2, u3, u4, u5;
int su0, su1, su2, su3, su4, su5;
int tu0, tu1, tu2, tu3, tu4, tu5;
u0 = HR[53+cards[0]];
u1 = HR[u0+cards[1]];
su0 = HR[53+cards[2]];
su1 = HR[su0+cards[3]];
tu0 = HR[53+cards[4]];
tu1 = HR[su0+cards[5]];
int A_B_C = 0;
int A_C_B = 0;
int A_BC = 0;
int AB_C = 0;
int AC_B = 0;
int ABC = 0;
int B_A_C = 0;
int B_C_A = 0;
int B_AC = 0;
int BC_A = 0;
int C_A_B = 0;
int C_B_A = 0;
int C_AB = 0;
for (int com1 = 1; com1 < 49; com1++) {
if (com1 != cards[0] && com1 != cards[1] && com1 != cards[2] && com1 != cards[3] && com1 != cards[4] && com1 != cards[5]) {
u2 = HR[u1+com1];
su2 = HR[su1+com1];
tu2 = HR[tu1+com1];
for (int com2 = com1 + 1; com2 < 50; com2++) {
if (com2 != cards[0] && com2 != cards[1] && com2 != cards[2] && com2 != cards[3] && com2 != cards[4] && com2 != cards[5]) {
u3 = HR[u2+com2];
su3 = HR[su2+com2];
tu3 = HR[tu2+com2];
for (int com3 = com2 + 1; com3 < 51; com3++) {
if (com3 != cards[0] && com3 != cards[1] && com3 != cards[2] && com3 != cards[3] && com3 != cards[4] && com3 != cards[5]) {
u4 = HR[u3+com3];
su4 = HR[su3+com3];
tu4 = HR[tu3+com3];
for (int com4 = com3 + 1; com4 < 52; com4++) {
if (com4 != cards[0] && com4 != cards[1] && com4 != cards[2] && com4 != cards[3] && com4 != cards[4] && com4 != cards[5]) {
u5 = HR[u4+com4];
su5 = HR[su4+com4];
tu5 = HR[tu4+com4];
for (int com5 = com4 + 1; com5 < 53; com5++) {
if (com5 != cards[0] && com5 != cards[1] && com5 != cards[2] && com5 != cards[3] && com5 != cards[4] && com5 != cards[5]) {
int rank_a = HR[u5 + com5];
int rank_b = HR[su5 + com5];
int rank_c = HR[tu5 + com5];
if (rank_a > rank_b && rank_b > rank_c) {
A_B_C++;
} else if (rank_a > rank_c && rank_c > rank_b) {
A_C_B++;
} else if (rank_a > rank_b && rank_b == rank_c) {
A_BC++;
} else if (rank_a == rank_b && rank_b > rank_c) {
AB_C++;
} else if (rank_a == rank_c && rank_c > rank_b) {
AC_B++;
} else if (rank_a == rank_c && rank_a == rank_b) {
ABC++;
} else if (rank_b > rank_a && rank_a > rank_c) {
B_A_C++;
} else if (rank_b > rank_c && rank_c > rank_a) {
B_C_A++;
} else if (rank_b > rank_a && rank_a == rank_c) {
B_AC++;
} else if (rank_b == rank_c && rank_c > rank_a) {
BC_A++;
} else if (rank_c > rank_a && rank_a > rank_b) {
C_A_B++;
} else if (rank_c > rank_b && rank_b > rank_a) {
C_B_A++;
} else {
C_AB++;
}
}
}
}
}
}
}
}
}
}
}
Text outputValue = new Text(Integer.toString(A_B_C) +"," + Integer.toString(A_C_B) + "," + Integer.toString(A_BC)+"," + Integer.toString(A_BC) +","+ Integer.toString(AB_C)+","+ Integer.toString(AC_B) +","+ Integer.toString(ABC)+"," +Integer.toString(B_A_C) +","+Integer.toString(B_C_A)+","+Integer.toString(B_AC) +","+Integer.toString(BC_A)+","+Integer.toString(C_A_B) +","+Integer.toString(C_B_A)+","+Integer.toString(C_AB) + "\n");
con.write(word, outputValue);
}
}
}

Error: A JNI error has occurred (javax.mail.jar)

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]

Unable To Cycle Backwards Through Android Notifications

I have a series of notifications which appear two at a time to display a series of a total of 6-10 instructions (depending on the results of a web service call.) This portion of the code is working fine. The problem is when clicking BACKWARDS through the notifications cycle (if you click any of the two displayed notifications it will display the previous two notifications) it gets hungup at step 5 and does not display the 5th notifications and I'm having a bit of trouble determining why.
SCREENSHOT:
http://datasettings.site90.net/Screenshot_2013-10-03-11-37-20.png
SPECIFIC SOURCE:
private void setNotificationStrings(Bundle extras) {
TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
// The code below sets the values of the current (field and value),
// previous, and beforePrevious
// Those hold the strings to display in the 2 notifications and the
// strings to go back to
// if the user decides to back track
if (i == count) {
done = true;
}
if (extras != null) {
if (((tm.getSimOperator()).equals(getString(R.string.numeric_tmo)))) {
Log.w(TAG, "Extras not null");
previousValue = extras.getString(getString(R.string.config_name_label));
value = extras.getString(getString(R.string.apn_label));
if (previousValue != null && value == null) {
previousField = getString(R.string.config_name_label);
previousValue = valuez.getAsString("name");
Log.w("previousValue", previousValue);
beforePreviousField = "step1";
beforePreviousValue = "> New APN";
//
field = getString(R.string.apn_label);
value = valuez.getAsString("apn");
extras.clear();
currentStep = 2;
if (i == 1) {
j++;
}
Log.d("currentStep = ", " 2");
} else {
previousValue = extras.getString(getString(R.string.apn_label));
if (proxyArr.size() > 0)// if proxy and port are not null
value = extras.getString(getString(R.string.proxy_label));
else {
value = extras.getString(getString(R.string.mmsc_label));
}
if (previousValue != null && value == null) {
previousField = getString(R.string.apn_label);
beforePreviousField = getString(R.string.config_name_label);
beforePreviousValue = valuez.getAsString("name");
if (proxyArr.size() > 0) {
field = getString(R.string.proxy_label);
value = valuez.getAsString("proxy");
} else {
field = getString(R.string.mmsc_label);
value = valuez.getAsString("mmsc");
}
extras.clear();
currentStep = 3;
Log.d("currentStep = ", " 3");
} else {
if (proxyArr.size() > 0) {// if proxy and port are not
// null
previousValue = extras.getString(getString(R.string.apn_label));
value = extras.getString(getString(R.string.port_label));
if (previousValue != null && value == null) {
previousField = getString(R.string.apn_label);
beforePreviousField = getString(R.string.config_name_label);
beforePreviousValue = valuez.getAsString("name");
field = getString(R.string.port_label);
value = valuez.getAsString("port");
extras.clear();
currentStep = 4;
Log.d("currentStep = ", " 4");
} else {
previousValue = extras.getString(getString(R.string.port_label));
value = extras.getString(getString(R.string.mmsc_label));
if (previousValue != null && value == null) {
previousField = getString(R.string.port_label);
beforePreviousField = getString(R.string.proxy_label);
beforePreviousValue = valuez.getAsString("proxy");
field = getString(R.string.mmsc_label);
value = valuez.getAsString("mmsc");
extras.clear();
currentStep = 5;
Log.d("currentStep = ", " 5");
} else {
previousValue = extras.getString(getString(R.string.port_label));
if (mmsproxyArr.size() > 0) {// if mmsproxy
// and
// mmsport
// are not
// null
value = extras.getString(getString(R.string.mms_proxy_label));
} else {
value = extras.getString(getString(R.string.type_label));
}
if (previousValue != null && value == null) {
previousField = getString(R.string.mmsc_label);
beforePreviousField = getString(R.string.port_label);
beforePreviousValue = valuez.getAsString("port");
if (mmsproxyArr.size() > 0) {
field = getString(R.string.mms_proxy_label);
value = valuez.getAsString("mmsproxy");
} else {
field = getString(R.string.type_label);
value = getString(R.string.type);
}
extras.clear();
currentStep = 6;
if (i < nameArr.size() - 1 && currentStep == 6) {
i++;
Log.d("currentStep = ", " 6");
} else {
if (mmsproxyArr.size() > 0) {// if
// mmsproxy
// and
// mmsport
// are
// not
// null
previousValue = extras.getString(getString(R.string.mms_proxy_label));
value = extras.getString(getString(R.string.mms_port_label));
if (previousValue != null && value == null) {
previousField = getString(R.string.mms_proxy_label);
beforePreviousField = getString(R.string.mmsc_label);
beforePreviousValue = valuez.getAsString("mmsc");
field = getString(R.string.mms_port_label);
value = valuez.getAsString("mmsport");
extras.clear();
currentStep = 7;
Log.d("currentStep = ", " 7");
} else {
previousValue = extras.getString(getString(R.string.mms_port_label));
value = extras.getString(getString(R.string.type_label));
if (previousValue != null && value == null) {
previousField = getString(R.string.mms_port_label);
beforePreviousField = getString(R.string.mms_proxy_label);
beforePreviousValue = valuez.getAsString("mmsproxy");
field = getString(R.string.type_label);
value = getString(R.string.type);
extras.clear();
currentStep = 8;
Log.d("currentStep = "," 8");
FULL SOURCE:
https://docs.google.com/document/d/1EjAo4bpnEjj6jExt7RY28EiA-fZIa1ExMBOfxzdGc3I/edit?usp=sharing

Byte Array operations in objective-c like java?

I want to implement one functionality as my ANDROID colleague did. Below is code snippet and I am having trouble converting that code to objective-c. So please guide me in right direction--- Thanks
Here is the code snippet
public String createControlParams() {
controlParams_ = "";
String expiry = "";
String delayedDelivery = "";
String restricted = "";
String priorityIndicator = "";
String acknowledgement = "";
//Note - PMessage.PRIORITY_INDICATOR_WHITE is defined as Int like 1,2,3
if (priorityIndicator_ == PMessage.PRIORITY_INDICATOR_WHITE) {
expiryTimeText_ = "";
restrictBackup = false;
restrictForward_ = false;
readAcknowledgement_ = false;
}
if (expiryTimeText_ != null && expiryTimeText_.length() > 0) {
int exptime = Integer.parseInt(expiryTimeText_);
byte h = (byte) (exptime / 60);
byte m = (byte) (exptime % 60);
expiry = new String(new byte[]{'E', 0, h, m});//??? how to get this thing in objective-c
}
if (delayDelivery) {
long timeDifference;
long deliveryTime;
// Fix
// if (midlet_.getPlatform().equalsIgnoreCase("rim")) {
//// timeDifference = Calendar.getInstance().getTimeZone().getRawOffset();
//// deliveryTime = (dateField_.getTime() - (dateField_.getTime() % (24 * 60 * 60 * 1000))) + (24 * 60 * 60 * 1000) + deliverySetTime_ - timeDifference;//+timeDifference;//(((Integer) timeSpinner.getValue()).longValue() * 1000);
// deliveryTime = (dateField_.getTime() + deliverySetTime_);// - timeDifference;
// } else {
deliveryTime = dateField_.getTime() + deliverySetTime_;// - timeDifference;
// }
if (deliveryTime > (new Date().getTime() + 2000)) { // Added to_ make message as instant delivery as opposed to_ delayed delivery if the delivery time is set in past (Added 2 seconds for message processing time)
delayedDelivery = "D" + deliveryTime;
}
}
if (restrictBackup && restrictForward_) {
restricted = new String(new byte[]{'R', (byte) 3});
} else if (restrictForward_) {
restricted = new String(new byte[]{'R', (byte) 1});
} else if (restrictBackup) {
restricted = new String(new byte[]{'R', (byte) 2});
}
if (priorityIndicator_ == PMessage.PRIORITY_INDICATOR_RED) {
priorityIndicator = new String(new byte[]{'P', (byte) PMessage.PRIORITY_INDICATOR_RED});
} else if (priorityIndicator_ == PMessage.PRIORITY_INDICATOR_YELLOW) {
priorityIndicator = new String(new byte[]{'P', (byte) PMessage.PRIORITY_INDICATOR_YELLOW});
} else if (priorityIndicator_ == PMessage.PRIORITY_INDICATOR_GREEN) {
priorityIndicator = new String(new byte[]{'P', (byte) PMessage.PRIORITY_INDICATOR_GREEN});
} else if (priorityIndicator_ == PMessage.PRIORITY_INDICATOR_GRAY) {
priorityIndicator = new String(new byte[]{'P', (byte) PMessage.PRIORITY_INDICATOR_GRAY});
} else if (priorityIndicator_ == PMessage.PRIORITY_INDICATOR_WHITE) {
priorityIndicator = new String(new byte[]{'P', (byte) PMessage.PRIORITY_INDICATOR_WHITE});
}
if (readAcknowledgement_) {
acknowledgement = new String(new byte[]{'A', PMessage.ACK_READ});
}
controlParams_ = priorityIndicator;
if (!expiry.equals("") && expiry != null) {
controlParams_ += (byte) (-128) + expiry;
}
if (!delayedDelivery.equalsIgnoreCase("") && delayedDelivery != null) {
controlParams_ += (byte) (-128) + delayedDelivery;
}
if (!restricted.equalsIgnoreCase("") && restricted != null) {
controlParams_ += (byte) (-128) + restricted;
}
if (!acknowledgement.equalsIgnoreCase("") && acknowledgement != null) {
controlParams_ += (byte) (-128) + acknowledgement;
}
return controlParams_;
// System.out.println(controlParams_);
}
private void getDraftControlParms(String controlParams_) {
if (!controlParams_.equals("") && controlParams_ != null) {
String[] sysParams = Helpers.splitUsingStringDelim(controlParams_, String.valueOf((byte) (-128)));
try {
for (int i = 0; i < sysParams.length; i++) {
if (!sysParams[i].equals("") && sysParams[i] != null) {
if (sysParams[i].substring(0, 1).equalsIgnoreCase("P")) {
priorityIndicator_ = (int) sysParams[i].getBytes()[1];
}
if (sysParams[i].substring(0, 1).equalsIgnoreCase("E")) {
int expiryFirstByte_ = sysParams[i].getBytes()[2];
int expirySecondByte_ =sysParams[i].getBytes()[3];
int expiryTime=(expiryFirstByte_ * 60) + (expirySecondByte_);
expiryMinutesField_.setText(expiryTime+"");
expiryTimeText_ = expiryMinutesField_.getText();
}
if (sysParams[i].substring(0, 1).equalsIgnoreCase("R")) {
int restrictedByte_ = (byte) sysParams[i].getBytes()[1];
if(restrictedByte_==1){
restrictForward_ = true;
restrictBackup = false;
}else if(restrictedByte_==2){
restrictForward_ = false;
restrictBackup = true;
}else{
restrictForward_ = true;
restrictBackup = true;
}
}
if (sysParams[i].substring(0, 1).equalsIgnoreCase("A")) {
readAcknowledgement_ = true;
}
}
switch (priorityIndicator_) {
case PMessage.PRIORITY_INDICATOR_RED: {
counter.getStyle().setBgColor(0xfe0002);
counter.getStyle().setBgTransparency(255);
break;
}
case PMessage.PRIORITY_INDICATOR_YELLOW: {
counter.getStyle().setBgColor(0xffff00);
counter.getStyle().setBgTransparency(255);
break;
}
case PMessage.PRIORITY_INDICATOR_GREEN: {
counter.getStyle().setBgColor(0x80ff00);
counter.getStyle().setBgTransparency(255);
break;
}
case PMessage.PRIORITY_INDICATOR_GRAY: {
counter.getStyle().setBgColor(0x919594);
counter.getStyle().setBgTransparency(255);
break;
}
case PMessage.PRIORITY_INDICATOR_WHITE: {
counter.getStyle().setBgColor(0xffffff);
counter.getStyle().setBgTransparency(255);
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I'm not an Objective C guy, but have you tried using char? In C/C++ a char is one byte and should do what you need it to.
You don't need to use bytes. You can use an NSArray of NSStrings.
Bytes, or unsigned char's in C, are more useful when you are concerned about the memory size of some data in a constrained environment.

Categories