I'm using the code
byte[] mac = ni.getHardwareAddress();
for (int i = 0; i < mac.length; i++) {
System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
to output: 00-27-0E-C2-53-B7
I need this output to be stored in a variable and I need a query to save it to a MySQL database. I also want to fetch MAC addresses automatically on my login page along with user details.
That way, I can store users' MAC addresses along with their usernames and passwords in the database. The idea is that, when a user logs in, I want to be able to fetch the MAC address automatically to authenticate the user.
How can I do this?
You are asking a lot of questions.
Your mac address is already stored in variable. Array mac[] is a array variable. If you need separate variable just define it like the following:
String myMac = mac[i];
Saving data in DB. I believe that you are already using DB. If for exampel you are using plain JDBC construct insert or update SQL statement like this:
insert into UserData ('mac') VAULUES (?) where user_id=?
Obviously the concrete fields depend on your DB schema.
If you are using some ORM system ask more specific question about this ORM. But in most cases this will be even simpler. If for example you already have class User:
class User {
private String username;
private String password;
// etc
}
...just add the new field mac there:
class User {
private String username;
private String password;
private String mac;
// etc
}
If you are using JPA your DB schema will be updated automatically and the data will be saved there too.
The same is about login page. If you already have login page that shows for example user ID, add similar code for MAC
etc, etc....
The zen of Python says "simple is better than complex."
This code is from SO user Carles Barrobes:
public String obtainMacAddress() throws Exception
{
Process aProc = Runtime.getRuntime().exec("ipconfig /all");
InputStream procOut = new DataInputStream(aProc.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(procOut));
String aMacAddress = "((\\p{XDigit}\\p{XDigit}-){5}\\p{XDigit}\\p{XDigit})";
Pattern aPatternMac = Pattern.compile(aMacAddress);
String aIpAddress = ".*IP.*: (([0-9]*\\.){3}[0-9]).*$";
Pattern aPatternIp = Pattern.compile(aIpAddress);
String aNewAdaptor = "[A-Z].*$";
Pattern aPatternNewAdaptor = Pattern.compile(aNewAdaptor);
// locate first MAC address that has IP address
boolean zFoundMac = false;
boolean zFoundIp = false;
String foundMac = null;
String theGoodMac = null;
String strLine;
while (((strLine = br.readLine()) != null) && !(zFoundIp && zFoundMac)) {
Matcher aMatcherNewAdaptor = aPatternNewAdaptor.matcher(strLine);
if (aMatcherNewAdaptor.matches()) {
zFoundMac = zFoundIp = false;
}
Matcher aMatcherMac = aPatternMac.matcher(strLine);
if (aMatcherMac.find()) {
foundMac = aMatcherMac.group(0);
zFoundMac = true;
}
Matcher aMatcherIp = aPatternIp.matcher(strLine);
if (aMatcherIp.matches()) {
zFoundIp = true;
if(zFoundMac && (theGoodMac == null)) theGoodMac = foundMac;
}
}
aProc.destroy();
aProc.waitFor();
return theGoodMac;}
Note that it is necessary to have an ethernet or wifi connection to run the above.
Related
i already inputted all the necessary parameters for it to work according to the docs and the forums but it just can't seem to work on me
private void joinMeeting(Context context, String meetingNumber,String zak, String userName, String usID){
int ret = -1;
MeetingService meetingService = ZoomSDK.getInstance().getMeetingService();
JoinMeetingOptions options = new JoinMeetingOptions();
//JoinMeetingParams params = new JoinMeetingParams();
//params.displayName=userName;
//params.meetingNo =meetingNumber;
//params.password=meetingPassword;
//meetingService.joinMeetingWithParams(context,params,options);
StartMeetingParamsWithoutLogin params = new StartMeetingParamsWithoutLogin();
params.userId = usID; // Based on this id we are able to start the meeting as host
params.userType = MeetingService.USER_TYPE_API_USER;
params.displayName = userName;
params.zoomAccessToken = zak; //getting the zoom access token from start_url
params.meetingNo = meetingNumber; // meetingNo, getting this from create meeting api response
ret = meetingService.startMeetingWithParams(context,params,options);
Log.e("Start Meeting As Host", "===startMeetingWithNumber====ret=" + ret);
}
i tried all generating more meeting using my web sdk but it wont work either
I am trying to store a randomly generated string in a string variable to use for in for other things. Basically, it is a password generator that stores the password for use with commands that need it. The application seems to have problems with storing the password for later use though. Code and output vs expected below.
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
super.onGuildMessageReceived(event);
String id = "discord userid String";
long idlong = Long.parseLong(id);
String generatedString = RandomStringUtils.random(15, true, true);
StringBuilder stored = new StringBuilder(15);
//password generator
if (event.getMessage().getContentRaw().equalsIgnoreCase("!passwordgen")) {
if (stored.toString().isEmpty() == true || idlong ==
event.getMessage().getAuthor().getIdLong()) {
stored.replace(0, 14, generatedString);
User user = event.getMessage().getAuthor();
user.openPrivateChannel().complete()
.sendMessage("Your new password is: " + stored + ". You can change your password
in the future with !setpassword <currentpassword>.").queue();
}
else {
event.getChannel().sendMessage("You do not have permission to generate a new password
and/or an initial password has already been set.").queue();
}
}
//set password command
if (event.getMessage().getContentRaw().startsWith("!setpassword")) {
char[] chararr = event.getMessage().getContentRaw().toCharArray();
for (int i = 0; i < chararr.length; i++) {
if (chararr[i] == ' ') {
passwordkeyed += event.getMessage().getContentRaw().substring(13);
}
}
if (passwordkeyed.equals(stored.toString()) && !(passwordkeyed.isEmpty())) {
stored.replace(0, 14, generatedString); //replaces random password from !passwordgen
// with new random password
event.getChannel().sendMessage("Stored: " + stored).queue();
event.getChannel().sendMessage("Check your DMs!").queue();
User user1 = event.getMessage().getAuthor();
user1.openPrivateChannel().complete()
.sendMessage("Your new password is: " + stored).queue();
}
if (!(passwordkeyed.equals(stored.toString()))) {
event.getChannel().sendMessage("Incorrect password. Stored: " + stored).queue();
}
if (stored.toString().isEmpty()) {
event.getChannel().sendMessage("Please use !passwordgen to generate an initial password.").queue();
}
}
}
For some reason, in the //password generator section, stored is replaced with a random string just fine but when you enter that password using the !setpassword command, stored is empty so it is like the replace method I used in the password generator section is not being saved even though the StringBuilder has the proper scope for the method.
I've been trying to do this for a bit now. I have tried with String, StringBuilder, and StringBuffer to see if any had different results but all had the same output.
Output:
!passwordgen //discord bot command
Your new password is: h50uSKlrWa30Q40. You can change your password in the future with !setpassword
<currentpassword>. //private message to whoever ran the command
!setpassword h50uSKlrWa30Q40 //discord bot command
Incorrect password. Stored:
Please use !passwordgen to generate an initial password.
Expected Output:
!passwordgen //discord bot command
Your new password is: h50uSKlrWa30Q40. You can change your password in the future with !setpassword
<currentpassword>. //private message to whoever ran the command
!setpassword h50uSKlrWa30Q40 //discord bot command
Stored: 2Fx8buVxpIEyNYX
Check your DMs!
Your new password is: 2Fx8buVxpIEyNYX //private message to whoever ran the command
In the back of my mind I am thinking it may be how I am generating the random password and storing it but I am not sure since this seems to be a problem with the string declaration itself and its scope
Try:
StringBuilder stored = new StringBuilder(15);
to
String stored = "";
OR
try to add this above the public void onGuildMessageReceived(GuildMessageReceivedEvent event):
private String Stored = "";
Everytime you want to use it, do this.Stored
See if it works then.
Also, try to add a statement to send in dms the current stored string at random points in the code this is what i call print–debugging to simply see when the value changes to reduce our search.
I am doing a reading text file practice where I read and store the data into a string array object. One ArrayList data should have photo, title, website, and date. The text file looks like this:
photo:android_pie
title:Android Pie: Everything you need to know about Android 9
website:https://www.androidcentral.com/pie
date:20-08-2018
photo:oppo
title:OPPO Find X display
website:https://www.androidpit.com/oppo-find-x-display-review
date:25-08-2018
photo:android_pie2
title:Android 9 Pie: What Are App Actions & How To Use Them
website:https://www.androidheadlines.com/2018/08/android-9-pie-what-are-app-
actions-how-to-use-them.html
date:16-09-2018
I am trying to split and store them into a string array, which is an instance of my object class:
private List<ItemObjects> itemList;
and this is the constructor of my object class:
public ItemObjects(String photo, String name, String link, String date) {
this.photo = photo;
this.name = name;
this.link = link;
this.date = date;
}
I tried this but the ":" separator doesnt separate it like I want it to:
while ((sItems = bufferedReader.readLine()) != null) {
if (!sItems.equals("")) {
String[] tmpItemArr = sItems.split("\\:");
listViewItems.add(new ItemObjects(tmpItemArr[0], tmpItemArr[1], tmpItemArr[2], tmpItemArr[3]));
}
}
What is the best way of doing this? I have tried using for loop which stops at third line and adds the next one as new data. There are several online ways of doing it but some are very complicated and I am having trouble understanding it.
The problem is your understanding of using both the split function and the BufferReader.
By using readline function you are reading only one line so your split will split the first line only, you need to read the 4 first lines then add the item.
int count = 0;
String[] tmpItemArr = new String[4];
while ((sItems = bufferedReader.readLine()) != null) {
if (!sItems.equals("")) {
tmpItemArr[count] = sItems.split(":")[1];
count++;
if (count > 3) {
listViewItems.add(new ItemObjects(tmpItemArr[0], tmpItemArr[1], tmpItemArr[2], tmpItemArr[3]));
count = 0;
}
}
}
This maybe simple but java isn’t really my thing but I'm working with a java API.
I need to parse a csv file and use the values as strings.
CSV file:
Mac,device,level ,key number,key function ,name,number,prim
01:1A:E8:84:9D:27,0,0,1,31,line,441865945218,TRUE
01:1A:E8:84:9D:27,0,0,2,51,dss,441865985452,FALSE
each row need to be read seprately so something like.
Read first row of csv
Assign values to strings (e.g. mac = 01:1A:E8:84:9D:27 device = 0 and so on)
Run "code" using these strings
Read second row of csv
So on till end of csv.
Thanks
I have tried csvreader but I'm not able to use the strings outside of the while function and it does not read line by line.
CsvReader phones = new CsvReader("dls.csv");
phones.readHeaders();
while (phones.readRecord()){
String deviceID = phones.get("Mac");
String device = phones.get("device");
String level = phones.get("level");
String keynumber = phones.get("key number");
String keyfunction = phones.get("key Function");
String label = phones.get("name");
String e164 = phones.get("number");
String prim = phones.get("prim");
}
As you are new to Java, whatever you are doing, looks like it reads the file line by line. But as you are defining the Strings in while loop, you won't be able to access it outside.
If you want to read all lines and store in Strings, you should probably take array for all of them and define them outside the while loop, add values in the loop and then you'll be able to use it.
Or just create a Phone class:
public class Phone{
String deviceId;
String device;
......etc...
//setters and getters
}
And take an array of it outside while. Something like this:
CsvReader phones = new CsvReader("dls.csv");
phones.readHeaders();
List<Phone> phonesArr=new ArrayList<Phone>();
while (phones.readRecord())
{
Phone phone=new Phone();
phone.setDeviceId(phones.get("Mac"));
phone.setDevice(phones.get("device"));
.....
phones.add(phone);
}
// array phones will be accessible here
Hope that helps!
You have to declare the Strings outside of the loop. Otherwise the String variables would be loop scoped.
CsvReader phones = new CsvReader("dls.csv");
phones.readHeaders();
String deviceID;
String device;
String level;
String keynumber;
String keyfunction;
String label;
String e164;
String prim;
while (phones.readRecord()){
deviceID = phones.get("Mac");
device = phones.get("device");
level = phones.get("level");
keynumber = phones.get("key number");
keyfunction = phones.get("key Function");
label = phones.get("name");
e164 = phones.get("number");
prim = phones.get("prim");
}
See:
Scopes tutorial
Javadoc: Variables
In the end I just called the funtion from the while loop.
while (phones.readRecord()) {
deviceID = phones.get("Mac");
Device = phones.get("device");
Level = phones.get("level");
Keynumber = phones.get("key number");
Keyfunction = phones.get("key function");
Label = phones.get("name");
E164 = phones.get("number");
Prim = phones.get("prim");
tools connect = new tools();
connect.connect();
connect.setkeys(deviceID,Device,Level,Label,Keynumber,Keyfunction,E164,Prim);
//System.out.println(Prim);
}
phones.close();
I am writing a tool that will validate WebSphere settings of a web application. I want to be able to look up all possible values of a WebSphere variable (all scopes) by remotely connecting to the server through the java AdminClient object. I have already read another post about this and although I think I now have the correct code I am not able to use the AdminOperations MBean because the WebSphere account I have to use is not granted admin privileges. I would like to know if there is a way to resolve WebSphere variables without using AdminOperations. Thanks!
Here is my code so far (again, does not work due to privilege issues):
private static String expandVariable(AdminClient client, String s)
throws Exception
{
Set result = client.queryNames(new ObjectName("*:*,type=AdminOperations,process=exampleProcess"), null);
return (String)client.invoke((javax.management.ObjectName)
result.iterator().next(),"expandVariable",new Object[]
{"${"+s+"}"}, new String[] {"java.lang.String"});
}
A User with Monitor role can use ConfigService's queryConfigObjects API and other configservice APIs to access the variables from configuration(not runtime).
Infocenter link :
http://pic.dhe.ibm.com/infocenter/wasinfo/v8r0/index.jsp?topic=%2Fcom.ibm.websphere.javadoc.doc%2Fweb%2Fapidocs%2Fcom%2Fibm%2Fwebsphere%2Fmanagement%2Fconfigservice%2Fpackage-summary.html&resultof=%22ConfigServiceProxy%22%20%22configserviceproxi%22%20
Sample snippet as below:
//name of variable that needs to be expanded
String varName ="DERBY_JDBC_DRIVER_PATH";
//create a configservice proxy
configService = new ConfigServiceProxy(adminClient);
//create a session
Session session = new Session();
//ObjectName for the variables.xml
ObjectName varMapObjName = ConfigServiceHelper.createObjectName(null, "VariableMap", null);
//query all variables.xml under cell.scope is null
ObjectName[] variableMaps = configService.queryConfigObjects(session, null, varMapObjName, null);
for (int i = 0; i < variableMaps.length; i++) {
ObjectName varMap = (ObjectName) variableMaps[i];
//retrieve each variable entry
AttributeList varEntries = configService.getAttributes(session, varMap, new String[]{"entries"}, false);
List entryList = (List) ConfigServiceHelper.getAttributeValue(varEntries, "entries");
//Iterate through each entry and get the value for the specified variable(symbolicName) name.
for (int j = 0; j < entryList.size(); j++) {
ObjectName varObj = (ObjectName)entryList.get(j);
String symbolicName= (String)configService.getAttribute(session, varObj, "symbolicName");
String value = null;
if (symbolicName.equals(varName)){
value= (String)configService.getAttribute(session, varObj, "value");
System.out.println(symbolicName+"="+value);
}
}
}