file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
MD5.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android-new/app/src/main/java/com/example/drcom/MD5.java | package com.example.drcom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by lin on 2017-01-10-010.
* MD5
*/
public class MD5 {
private static final byte[] zero16 = new byte[16];
public static byte[] md5(byte[]... bytes) {
int len = 0;
for (byte[] bs : bytes) {
len += bs.length;//数据总长度
}
byte[] data = new byte[len];
len = 0;//记录已拷贝索引
for (byte[] bs : bytes) {
System.arraycopy(bs, 0, data, len, bs.length);
len += bs.length;
}
return md5(data);
}
public static byte[] md5(byte[] bytes) {
try {
MessageDigest instance = MessageDigest.getInstance("MD5");
instance.update(bytes);
return instance.digest();
} catch (NoSuchAlgorithmException ignore) {
}
return zero16;//容错
}
/*//http://www.tuicool.com/articles/QJ7bYr
* 字符串 DESede(3DES) 加密
* ECB模式/使用PKCS7方式填充不足位,目前给的密钥是192位
* 3DES(即Triple DES)是DES向AES过渡的加密算法(1999年,NIST将3-DES指定为过渡的
* 加密标准),是DES的一个更安全的变形。它以DES为基本模块,通过组合分组方法设计出分组加
* 密算法,其具体实现如下:设Ek()和Dk()代表DES算法的加密和解密过程,K代表DES算法使用的
* 密钥,P代表明文,C代表密表,这样,
* 3DES加密过程为:C=Ek3(Dk2(Ek1(P)))
* 3DES解密过程为:P=Dk1((EK2(Dk3(C)))
* <p>
* args在java中调用sun公司提供的3DES加密解密算法时,需要使
* 用到$JAVA_HOME/jre/lib/目录下如下的4个jar包:
* jce.jar
* security/US_export_policy.jar
* security/local_policy.jar
* ext/sunjce_provider.jar
*/
private static final String Algorithm = "DESede"; //定义加密算法,可用 DES,DESede,Blowfish
private static final byte[] none = new byte[]{};
public static final int DES_KEY_LEN = 24;
private static byte[] des(int mode, byte[] key, byte[] data) {
try {
SecretKey deskey = new SecretKeySpec(key, Algorithm);//生成密钥
Cipher c1 = Cipher.getInstance(Algorithm);//加密或解密
c1.init(mode, deskey);
return c1.doFinal(data);//在单一方面的加密或解密
} catch (NoSuchAlgorithmException | javax.crypto.NoSuchPaddingException ignore) {
} catch (Exception e3) {
e3.printStackTrace();
}
return none;
}
public static byte[] encrypt3DES(byte[] keybyte, byte[] src) {
return des(Cipher.ENCRYPT_MODE, keybyte, src);
}
public static byte[] decrypt3DES(byte[] keybyte, byte[] secret) {
return des(Cipher.DECRYPT_MODE, keybyte, secret);
}
public static void main(String[] args) {
byte[] enk = ByteUtil.ljust("1".getBytes(), DES_KEY_LEN);//用于加密的密码,必须 24 长度
String password = "a";//要加密的字符串
System.out.println("加密前的字符串:" + password + " | " + ByteUtil.toHexString(password.getBytes()));
byte[] encoded = encrypt3DES(enk, password.getBytes());
System.out.println("加密后:" + ByteUtil.toHexString(encoded));
byte[] srcBytes = decrypt3DES(enk, ByteUtil.fromHex(ByteUtil.toHexString(encoded), ' '));
System.out.println("解密后的字符串:" + new String(srcBytes) + " | " + ByteUtil.toHexString(srcBytes));
}/*
* 加密前的字符串:123456 | 31 32 33 34 35 36
* 加密后的字符串:Nj�Y�_l� | C7 8B C1 59 94 5F 6C AE
* 解密后的字符串:123456 | 31 32 33 34 35 36
*/
}
| 3,886 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
DrcomException.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android-new/app/src/main/java/com/example/drcom/DrcomException.java | package com.example.drcom;
/**
* Created by lin on 2017-01-09-009.
* 异常
*/
public class DrcomException extends Exception {
public DrcomException(String msg) {
super('[' + CODE.ex_unknown.name() + "] " + msg);
}
public DrcomException(String msg, CODE code) {
super('[' + code.name() + "] " + msg);
}
public DrcomException(String msg, Throwable cause) {
super('[' + CODE.ex_unknown.name() + "] " + msg, cause);
}
public DrcomException(String msg, Throwable cause, CODE code) {
super('[' + code.name() + "] " + msg, cause);
}
public enum CODE {
ex_unknown, ex_init, ex_challenge, ex_login, ex_timeout, ex_io, ex_thread
}
}
| 712 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
ByteUtil.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android-new/app/src/main/java/com/example/drcom/ByteUtil.java | package com.example.drcom;
import java.math.BigInteger;
import java.util.Random;
/**
* Created by lin on 2017-01-11-011.
* 字节数组工具, byte 数字当作无符号数处理. 因此 toInt(0xff) 将得到 255.
*/
public class ByteUtil {
private static final Random random = new Random(System.currentTimeMillis());
public static byte randByte() {
return (byte) random.nextInt();
}
public static int toInt(byte b) {
return b & 0xff;//0xff -> 255
}
/*得到两位长度的 16 进制表示*/
public static String toHexString(byte b) {
String tmp = Integer.toHexString(toInt(b));
if (tmp.length() == 1) {
tmp = '0' + tmp;
}
return tmp;
}
/*使用空格分割的十六进制表示字符串*/
public static String toHexString(byte[] bytes) {
return toHexString(bytes, ' ');
}
/*使用 split 字符分割的十六进制表示字符串*/
public static String toHexString(byte[] bytes, char split) {
if (bytes == null || bytes.length == 0) {
return "";
}
int len = bytes.length;
StringBuilder sb = new StringBuilder(len * 3);//两位数字+split
for (byte b : bytes) {
sb.append(toHexString(b)).append(split);
}
return sb.toString().substring(0, len * 3 - 1).toUpperCase();
}
public static byte[] fromHex(String hexStr) {
return fromHex(hexStr, ' ');
}
public static byte[] fromHex(String hexStr, char split) {
// hexStr = 00 01 AB str len = 8 length = (8+1)/3=3
int length = (hexStr.length() + 1) / 3;
byte[] ret = new byte[length];
for (int i = 0; i < length; i++) {
ret[i] = (byte) Integer.parseInt(hexStr.substring(i * 3, i * 3 + 2), 16);
}
return ret;
}
public static byte[] ljust(byte[] src, int count) {
return ljust(src, count, (byte) 0x00);
}
private static byte[] ljust(byte[] src, int count, byte fill) {
int srcLen = src.length;
byte[] ret = new byte[count];
if (srcLen >= count) {//只返回前 count 位
System.arraycopy(src, 0, ret, 0, count);
return ret;
}
System.arraycopy(src, 0, ret, 0, srcLen);
for (int i = srcLen; i < count; i++) {
ret[i] = fill;
}
return ret;
}
public static byte[] ror(byte[] md5a, byte[] password) {
int len = password.length;
byte[] ret = new byte[len];
int x;
for (int i = 0; i < len; i++) {
x = toInt(md5a[i]) ^ toInt(password[i]);
//e.g. x = 0xff 1111_1111
// x<<3 = 0x07f8 0111_1111_1000
// x>>>5 = 0x0007 0111
// + 0x07ff 0111_1111_1111
//(byte)截断=0xff
ret[i] = (byte) ((x << 3) + (x >>> 5));
}
return ret;
}
/**
* 每四个数倒过来后与sum相与, 最后*1968取后4个数.
* <p>
* Python版用<code>'....'</code>匹配四个字节,但是这个正则会忽略换行符 0x0a, 因此计算出来的是错误的.
* 但是python版代码是可用的,因此应该是服务器没有检验
* (Python 版协议与本工程有些许不一样, 所以这里需要返回正确的校验码)
* <pre>
* import struct
* import re
* def checksum(s):
* ret = 1234
* for i in re.findall('....', s):
* tmp = int(i[::-1].encode('hex'), 16)
* print(i, i[::-1], ret, tmp, ret ^ tmp)
* ret ^= tmp
* ret = (1968 * ret) & 0xffffffff
* return struct.pack('<I', ret)
* </pre>
**/
public static byte[] checksum(byte[] data) {
// 1234 = 0x_00_00_04_d2
byte[] sum = new byte[]{0x00, 0x00, 0x04, (byte) 0xd2};
int len = data.length;
int i = 0;
//0123_4567_8901_23
for (; i + 3 < len; i = i + 4) {
//abcd ^ 3210
//abcd ^ 7654
//abcd ^ 1098
sum[0] ^= data[i + 3];
sum[1] ^= data[i + 2];
sum[2] ^= data[i + 1];
sum[3] ^= data[i];
}
if (i < len) {
//剩下_23
//i=12,len=14
byte[] tmp = new byte[4];
for (int j = 3; j >= 0 && i < len; j--) {
//j=3 tmp = 0 0 0 2 i=12 13
//j=2 tmp = 0 0 3 2 i=13 14
tmp[j] = data[i++];
}
for (int j = 0; j < 4; j++) {
sum[j] ^= tmp[j];
}
}
BigInteger bigInteger = new BigInteger(1, sum);//无符号数即正数
bigInteger = bigInteger.multiply(BigInteger.valueOf(1968));
bigInteger = bigInteger.and(BigInteger.valueOf(0xff_ff_ff_ffL));
byte[] bytes = bigInteger.toByteArray();
//System.out.println(ByteUtil.toHexString(bytes));
len = bytes.length;
i = 0;
byte[] ret = new byte[4];
for (int j = len - 1; j >= 0 && i < 4; j--) {
ret[i++] = bytes[j];
}
return ret;
}
//参考了 Python 版
public static byte[] crc(byte[] data) {
byte[] sum = new byte[2];
int len = data.length;
for (int i = 0; i + 1 < len; i = i + 2) {
sum[0] ^= data[i + 1];
sum[1] ^= data[i];
}//现在数据都是偶数位
BigInteger b = new BigInteger(1, sum);
b = b.multiply(BigInteger.valueOf(711));
byte[] bytes = b.toByteArray();
len = bytes.length;
//System.out.println(toHexString(bytes));
byte[] ret = new byte[4];
for (int i = 0; i < 4 && len > 0; i++) {
ret[i] = bytes[--len];
}
return ret;
}
}
| 5,818 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
HostInfo.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android-new/app/src/main/java/com/example/drcom/HostInfo.java | package com.example.drcom;
/**
* Created by lin on 2017-01-10-010.
* 机器的IP、HostName、MAC等
*/
public class HostInfo {
private final byte[] macBytes = new byte[6];
private String hostname;
private String macHexDash;
private String macNoDash;
public HostInfo(String hostname, String macHex) {
this.hostname = hostname;
checkHexToDashMac(macHex);
}
private void checkHexToDashMac(String mac) {
if (mac.contains("-")) {
mac = mac.replaceAll("-", "");
}
if (mac.length() != 12) {
throw new RuntimeException("MAC 地址格式错误。应为 xx-xx-xx-xx-xx-xx 或 xxxxxxxxxxxx 格式的 16 进制: " + mac);
}
try {
//noinspection ResultOfMethodCallIgnored
Long.parseLong(mac, 16);
} catch (NumberFormatException e) {
throw new RuntimeException("MAC 地址格式错误。应为 xx-xx-xx-xx-xx-xx 或 xxxxxxxxxxxx 格式的 16 进制: " + mac);
}
StringBuilder sb = new StringBuilder(18);
for (int i = 0; i < 12; i++) {
sb.append(mac.charAt(i++)).append(mac.charAt(i)).append("-");
}
macHexDash = sb.substring(0, 17);
macNoDash = mac;
String[] split = macHexDash.split("-");
for (int i = 0; i < split.length; i++) {
macBytes[i] = (byte) Integer.parseInt(split[i], 16);
}
}
@Override
public String toString() {
return "[" + macHexDash + '/' + hostname + ']';
}
public byte[] getMacBytes() {
return macBytes;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getMacHexDash() {
return macHexDash;
}
public void setMacHexDash(String macHexDash) {
checkHexToDashMac(macHexDash);
}
public String getMacNoDash() {
return macNoDash;
}
public void setMacNoDash(String macNoDash) {
checkHexToDashMac(macNoDash);
}
}
| 2,093 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
Constants.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android-new/app/src/main/java/com/example/drcom/Constants.java | package com.example.drcom;
/**
* Created by lin on 2017-01-09-009.
* 常量
*/
public class Constants {
public static final String AUTH_SERVER = "10.100.61.3"; //"auth.jlu.edu.cn"
public static final int PORT = 61440;
public static final int TIMEOUT = 10000;//10s
}
| 282 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
STATUS.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android-new/app/src/main/java/com/example/drcom/STATUS.java | package com.example.drcom;
/**
* Created by lin on 2017-01-13-013.
* 登录状态
*/
public enum STATUS {
offline, online;
}
| 133 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
DrcomTask.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android-new/app/src/main/java/com/example/drcom/DrcomTask.java | package com.example.drcom;
import android.os.AsyncTask;
import android.util.Log;
import com.example.service.KeepListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by lin on 2017-01-11-011.
* challenge, login, keep_alive, logout
*/
public class DrcomTask extends AsyncTask<Void, String, Void> {
// private static final Logger log = LoggerFactory.getLogger(DrcomTask.class);
//region //Drcom 协议若干字段信息
/**
* 在 keep38 的回复报文中获得[28:30]
*/
private static final byte[] keepAliveVer = {(byte) 0xdc, 0x02};
/**
* 官方客户端在密码错误后重新登录时,challenge 包的这个数会递增,因此这里设为静态的
*/
private static int challengeTimes = 0;
/**
* 在 challenge 的回复报文中获得 [4:8]
*/
private final byte[] salt = new byte[4];
/**
* 在 challenge 的回复报文中获得 [20:24], 当是有线网时,就是网络中心分配的 IP 地址,当是无线网时,是局域网地址
*/
private final byte[] clientIp = new byte[4];
/**
* 在 login 的回复报文中获得[23:39]
*/
private final byte[] tail1 = new byte[16];
/**
* 在 login 报文计算,计算时需要用到 salt,password
*/
private final byte[] md5a = new byte[16];
/**
* 初始为 {0,0,0,0} , 在 keep40_1 的回复报文更新[16:20]
*/
private final byte[] tail2 = new byte[4];
/**
* 在 keep alive 中计数.
* 初始在 keep40_extra : 0x00, 之后每次 keep40 都加一
*/
private int count = 0;
private int keep38Count = 0;//仅用于日志计数
//endregion
private boolean notifyLogout = false;
private DatagramSocket client;
private InetAddress serverAddress;
private String username;
private String password;
private String mac;
private HostInfo hostInfo;
private static final String TAG = "DrcomTask";
private KeepListener keepListener;
private STATUS status = STATUS.offline;
public boolean canReconnect = false;
public DrcomTask(KeepListener listener) {
keepListener = listener;
}
public void setNamePassMAC(String username, String password, String macAddr) {
this.username = username;
this.password = password;
this.mac = macAddr;
hostInfo = new HostInfo("windows", macAddr);
}
public String[] getNamePassMAC() {
String[] strings = new String[3];
strings[0] = username;
strings[1] = password;
strings[2] = mac;
return strings;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d(TAG, "onProgressUpdate: 要更新的进度值为" + values[0]);
if ("保持在线".equals(values[0])) {
keepListener.keepingAlive("保持在线");
} else if ("登录成功".equals(values[0])) {
keepListener.informLogStatus(STATUS.online, getNamePassMAC());
} else if ("已离线".equals(values[0])) {
keepListener.informLogStatus(STATUS.offline, getNamePassMAC());
}
}
@Override
protected Void doInBackground(Void... voids) {
try {
init();
Thread.currentThread().setName("Challenge");
if (!challenge(challengeTimes++)) {
throw new DrcomException("Server refused the request.{0}", DrcomException.CODE.ex_challenge);
}
Thread.currentThread().setName("L o g i n");
if (!login()) {
Log.d(TAG, "doInBackground: 登录失败");
throw new DrcomException("Failed to send authentication information.{0}", DrcomException.CODE.ex_login);
}
status = STATUS.online;
canReconnect = true;
Log.d(TAG, "doInBackground: 登录成功");
publishProgress("登录成功");
//keep alive
Thread.currentThread().setName("KeepAlive");
count = 0;
while (!notifyLogout && alive() && !isCancelled()) {//收到注销通知则停止
status = STATUS.online;
Log.d(TAG, "doInBackground: 保持在线");
publishProgress("保持在线");
Thread.sleep(20000);//每 20s 一次
}
status = STATUS.offline;
} catch (SocketTimeoutException e) {
Log.e(TAG, "doInBackground: 超时异常", e);
} catch (IOException e) {
Log.e(TAG, "doInBackground: IO异常", e);
} catch (InterruptedException e) {
Log.e(TAG, "doInBackground: 睡眠被打断异常", e);
} catch (DrcomException e) {
Log.e(TAG, "doInBackground: 登录失败", e);
Log.d(TAG, "doInBackground: 当前是否可登录" + canReconnect);
// 提醒用户输入有误
if ("[ex_login] Invalid Mac Address".equals(e.getMessage())) {
keepListener.informInvalidMAC();
} else if ("[ex_login] Invalid username or password".equals(e.getMessage())) {
keepListener.informInvalidNameOrPass();
}
} catch (Exception e) {
Log.e(TAG, "doInBackground: 其他异常", e);
} finally {
if (client != null) {
client.close();
client = null;
}
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
Log.d(TAG, "onPostExecute: AsyncTask DrClient已停止");
status = STATUS.offline;
publishProgress("已离线");
keepListener.informCanLoginNow(canReconnect, getNamePassMAC());
}
@Override
protected void onCancelled(Void aVoid) {
Log.d(TAG, "onCancelled(Void aVoid): 任务取消");
status = STATUS.offline;
publishProgress("已离线");
keepListener.informCanLoginNow(canReconnect, getNamePassMAC());
}
@Override
protected void onCancelled() {
Log.d(TAG, "onCancelled(): 任务取消");
}
public boolean isOnline() {
Log.d(TAG, "isOnline: 在异步任务中查看是否在线");
return status == STATUS.online;
}
/**
* 初始化套接字、设置超时时间、设置服务器地址
*/
private void init() throws DrcomException {
try {
//每次使用同一个端口 若有多个客户端运行这里会抛出异常
client = new DatagramSocket(Constants.PORT);
client.setSoTimeout(Constants.TIMEOUT);
serverAddress = InetAddress.getByName(Constants.AUTH_SERVER);
} catch (SocketException e) {
throw new DrcomException("The port is occupied, do you have any other clients not exited?", e, DrcomException.CODE.ex_init);
} catch (UnknownHostException e) {
throw new DrcomException("The server could not be found. (check DNS settings)", DrcomException.CODE.ex_init);
}
}
/**
* 在回复报文中取得 salt 和 clientIp
*/
private boolean challenge(int tryTimes) throws DrcomException {
try {
byte[] buf = {0x01, (byte) (0x02 + tryTimes), ByteUtil.randByte(), ByteUtil.randByte(), 0x6a,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00};
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddress, Constants.PORT);
client.send(packet);
// log.trace("send challenge data.【{}】", ByteUtil.toHexString(buf));
buf = new byte[76];
packet = new DatagramPacket(buf, buf.length);
client.receive(packet);
if (buf[0] == 0x02) {
// log.trace("recv challenge data.【{}】", ByteUtil.toHexString(buf));
// 保存 salt 和 clientIP
System.arraycopy(buf, 4, salt, 0, 4);
System.arraycopy(buf, 20, clientIp, 0, 4);
return true;
}
// log.warn("challenge fail, unrecognized response.【{}】", ByteUtil.toHexString(buf));
return false;
} catch (SocketTimeoutException e) {
throw new DrcomException("Challenge server failed, time out. {0}", DrcomException.CODE.ex_challenge);
} catch (IOException e) {
throw new DrcomException("Failed to send authentication information. {0}", DrcomException.CODE.ex_challenge);
}
}
private boolean login() throws IOException, DrcomException {
byte[] buf = makeLoginPacket();
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddress, Constants.PORT);
client.send(packet);
// log.trace("send login packet.【{}】", ByteUtil.toHexString(buf));
byte[] recv = new byte[128];//45
client.receive(new DatagramPacket(recv, recv.length));
// log.trace("recv login packet.【{}】", ByteUtil.toHexString(recv));
if (recv[0] != 0x04) {
if (recv[0] == 0x05) {
if (recv[4] == 0x0B) {
canReconnect = false;
throw new DrcomException("Invalid Mac Address", DrcomException.CODE.ex_login);
}
canReconnect = false;
throw new DrcomException("Invalid username or password", DrcomException.CODE.ex_login);
} else {
throw new DrcomException("Failed to login, unknown error", DrcomException.CODE.ex_login);
}
}
// 保存 tail1. 构造 keep38 要用 md5a(在mkptk中保存) 和 tail1
// 注销也要用 tail1
System.arraycopy(recv, 23, tail1, 0, 16);
return true;
}
/**
* 需要用来自 challenge 回复报文中的 salt, 构造报文时会保存 md5a keep38 要用
*/
private byte[] makeLoginPacket() {
byte code = 0x03;
byte type = 0x01;
byte EOF = 0x00;
byte controlCheck = 0x20;
byte adapterNum = 0x05;
byte ipDog = 0x01;
byte[] primaryDNS = {10, 10, 10, 10};
byte[] dhcp = {0, 0, 0, 0};
byte[] md5b;
int passLen = password.length();
if (passLen > 16) {
passLen = 16;
}
int dataLen = 334 + (passLen - 1) / 4 * 4;
byte[] data = new byte[dataLen];
data[0] = code;
data[1] = type;
data[2] = EOF;
data[3] = (byte) (username.length() + 20);
System.arraycopy(MD5.md5(new byte[]{code, type}, salt, password.getBytes()),
0, md5a, 0, 16);//md5a保存起来
System.arraycopy(md5a, 0, data, 4, md5a.length);//md5a 4+16=20
byte[] user = ByteUtil.ljust(username.getBytes(), 36);
System.arraycopy(user, 0, data, 20, user.length);//username 20+36=56
data[56] = controlCheck;//0x20
data[57] = adapterNum;//0x05
//md5a[0:6] xor mac
System.arraycopy(md5a, 0, data, 58, 6);
byte[] macBytes = hostInfo.getMacBytes();
for (int i = 0; i < 6; i++) {
data[i + 58] ^= macBytes[i];//md5a oxr mac
}// xor 58+6=64
md5b = MD5.md5(new byte[]{0x01}, password.getBytes(), salt, new byte[]{0x00, 0x00, 0x00, 0x00});
System.arraycopy(md5b, 0, data, 64, md5b.length);//md5b 64+16=80
data[80] = 0x01;//number of ip
System.arraycopy(clientIp, 0, data, 81, clientIp.length);//ip1 81+4=85
System.arraycopy(new byte[]{
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
}, 0, data, 85, 12);//ip2/3/4 85+12=97
data[97] = 0x14;//临时放,97 ~ 97+8 是 md5c[0:8]
data[98] = 0x00;
data[99] = 0x07;
data[100] = 0x0b;
byte[] tmp = new byte[101];
System.arraycopy(data, 0, tmp, 0, tmp.length);//前 97 位 和 0x14_00_07_0b
byte[] md5c = MD5.md5(tmp);
System.arraycopy(md5c, 0, data, 97, 8);//md5c 97+8=105
data[105] = ipDog;//0x01
//0 106+4=110
byte[] hostname = ByteUtil.ljust(hostInfo.getHostname().getBytes(), 32);
System.arraycopy(hostname, 0, data, 110, hostname.length);//hostname 110+32=142
System.arraycopy(primaryDNS, 0, data, 142, 4);//primaryDNS 142+4=146
System.arraycopy(dhcp, 0, data, 146, 4);//dhcp 146+4=150
//second dns 150+4=154
//delimiter 154+8=162
data[162] = (byte) 0x94;//unknown 162+4=166
data[166] = 0x06; //os major 166+4=170
data[170] = 0x02; //os minor 170+4=174
data[174] = (byte) 0xf0;//os build
data[175] = 0x23; //os build 174+4=178
data[178] = 0x02; //os unknown 178+4=182
//DRCOM CHECK
data[182] = 0x44;//\x44\x72\x43\x4f\x4d\x00\xcf\x07
data[183] = 0x72;
data[184] = 0x43;
data[185] = 0x4f;
data[186] = 0x4d;
data[187] = 0x00;
data[188] = (byte) 0xcf;
data[189] = 0x07;
data[190] = 0x6a;
//0 191+55=246
System.arraycopy("1c210c99585fd22ad03d35c956911aeec1eb449b".getBytes(),
0, data, 246, 40);//246+40=286
//0 286+24=310
data[310] = 0x6a;//0x6a 0x00 0x00 310+3=313
data[313] = (byte) passLen;//password length
byte[] ror = ByteUtil.ror(md5a, password.getBytes());
System.arraycopy(ror, 0, data, 314, passLen);//314+passlen
data[314 + passLen] = 0x02;
data[315 + passLen] = 0x0c;
//checksum(data+'\x01\x26\x07\x11\x00\x00'+dump(mac))
//\x01\x26\x07\x11\x00\x00
data[316 + passLen] = 0x01;//临时放, 稍后被 checksum 覆盖
data[317 + passLen] = 0x26;
data[318 + passLen] = 0x07;
data[319 + passLen] = 0x11;
data[320 + passLen] = 0x00;
data[321 + passLen] = 0x00;
System.arraycopy(macBytes, 0, data, 322 + passLen, 4);
tmp = new byte[326 + passLen];//data+'\x01\x26\x07\x11\x00\x00'+dump(mac)
System.arraycopy(data, 0, tmp, 0, tmp.length);
tmp = ByteUtil.checksum(tmp);
System.arraycopy(tmp, 0, data, 316 + passLen, 4);//checksum 316+passlen+4=320+passLen
data[320 + passLen] = 0x00;
data[321 + passLen] = 0x00;//分割
System.arraycopy(macBytes, 0, data, 322 + passLen, macBytes.length);
//mac 322+passLen+6=328+passLen
// passLen % 4=mod 补0个数 4-mod (4-mod)%4
// 0 0 4
// 1 3 3
// 2 2 2
// 3 1 1
int zeroCount = (4 - passLen % 4) % 4;
for (int i = 0; i < zeroCount; i++) {
data[328 + passLen + i] = 0x00;
}
data[328 + passLen + zeroCount] = ByteUtil.randByte();
data[329 + passLen + zeroCount] = ByteUtil.randByte();
return data;
}
private boolean alive() throws IOException {
boolean needExtra = false;
Log.d(TAG, "alive: " + "count = " + count + ", keep38count = " + (++keep38Count) + "\n");
// log.trace("count = {}, keep38count = {}", count, ++keep38Count);
if (count % 21 == 0) {//第一个 keep38 后有 keep40_extra, 十个 keep38 后 count 就加了21
needExtra = true;
}//每10个keep38
//-------------- keep38 ----------------------------------------------------
byte[] packet38 = makeKeepPacket38();
DatagramPacket packet = new DatagramPacket(packet38, packet38.length, serverAddress, Constants.PORT);
client.send(packet);
// log.trace("[rand={}|{}]send keep38. 【{}】",
// ByteUtil.toHexString(packet38[36]), ByteUtil.toHexString(packet38[37]),
// ByteUtil.toHexString(packet38));
Log.d(TAG, "alive: " + "[rand=" + ByteUtil.toHexString(packet38[36]) + "|" + ByteUtil.toHexString(packet38[37])
+ "]send keep38. 【" + ByteUtil.toHexString(packet38) + "】");
byte[] recv = new byte[128];
client.receive(new DatagramPacket(recv, recv.length));
// log.trace("[rand={}|{}]recv Keep38. [{}.{}.{}.{}] 【{}】",
// ByteUtil.toHexString(recv[6]), ByteUtil.toHexString(recv[7]),
// ByteUtil.toInt(recv[12]), ByteUtil.toInt(recv[13]), ByteUtil.toInt(recv[14]), ByteUtil.toInt(recv[15]),
// ByteUtil.toHexString(recv));
Log.d(TAG, "alive: " + "[rand=" + ByteUtil.toHexString(recv[6]) + "|" + ByteUtil.toHexString(recv[7]) + "]recv keep38. ["
+ ByteUtil.toInt(recv[12]) + "." + ByteUtil.toInt(recv[13]) + "." + ByteUtil.toInt(recv[14]) + "."
+ ByteUtil.toInt(recv[15]) + "] 【" + ByteUtil.toHexString(recv) + "】");
keepAliveVer[0] = recv[28];//收到keepAliveVer//通常不会变
keepAliveVer[1] = recv[29];
if (needExtra) {//每十次keep38都要发一个 keep40_extra
// log.debug("Keep40_extra...");
Log.d(TAG, "alive: " + "keep40_extra...");
//--------------keep40_extra--------------------------------------------
//先发 keep40_extra 包
byte[] packet40extra = makeKeepPacket40(1, true);
packet = new DatagramPacket(packet40extra, packet40extra.length, serverAddress, Constants.PORT);
client.send(packet);
// log.trace("[seq={}|type={}][rand={}|{}]send Keep40_extra. 【{}】", packet40extra[1], packet40extra[5],
// ByteUtil.toHexString(packet40extra[8]), ByteUtil.toHexString(packet40extra[9]),
// ByteUtil.toHexString(packet40extra));
Log.d(TAG, "alive: " + "[seq=" + packet40extra[1] + "|type=" + packet40extra[5] + "][rand=" + ByteUtil.toHexString(packet40extra[8])
+ "|" + ByteUtil.toHexString(packet40extra[9]) + "]send keep40_extra. 【" + ByteUtil.toHexString(packet40extra) + "】");
recv = new byte[512];
client.receive(new DatagramPacket(recv, recv.length));
// log.trace("[seq={}|type={}][rand={}|{}]recv Keep40_extra. 【{}】", recv[1], recv[5],
// ByteUtil.toHexString(recv[8]), ByteUtil.toHexString(recv[9]), ByteUtil.toHexString(recv));
Log.d(TAG, "alive: " + "[seq=" + recv[1] + "|type=" + recv[5] + "][rand=" + ByteUtil.toHexString(recv[8])
+ "|" + ByteUtil.toHexString(recv[9]) + "]recv keep40_extra. 【" + ByteUtil.toHexString(recv) + "】");
//不理会回复
}
//--------------keep40_1----------------------------------------------------
byte[] packet40_1 = makeKeepPacket40(1, false);
packet = new DatagramPacket(packet40_1, packet40_1.length, serverAddress, Constants.PORT);
client.send(packet);
// log.trace("[seq={}|type={}][rand={}|{}]send Keep40_1. 【{}】", packet40_1[1], packet40_1[5],
// ByteUtil.toHexString(packet40_1[8]), ByteUtil.toHexString(packet40_1[9]),
// ByteUtil.toHexString(packet40_1));
Log.d(TAG, "alive: " + "[seq=" + packet40_1[1] + "|type=" + packet40_1[5] + "][rand=" + ByteUtil.toHexString(packet40_1[8])
+ "|" + ByteUtil.toHexString(packet40_1[9]) + "]send keep40_1. 【" + ByteUtil.toHexString(packet40_1) + "】");
recv = new byte[64];//40
client.receive(new DatagramPacket(recv, recv.length));
// log.trace("[seq={}|type={}][rand={}|{}]recv Keep40_1. 【{}】", recv[1], recv[5],
// ByteUtil.toHexString(recv[8]), ByteUtil.toHexString(recv[9]), ByteUtil.toHexString(recv));
Log.d(TAG, "alive: " + "[seq=" + recv[1] + "|type=" + recv[5] + "][rand=" + ByteUtil.toHexString(recv[8])
+ "|" + ByteUtil.toHexString(recv[9]) + "]recv keep40_1. 【" + ByteUtil.toHexString(recv) + "】");
//保存 tail2 , 待会儿构造 packet 要用
System.arraycopy(recv, 16, tail2, 0, 4);
//--------------keep40_2----------------------------------------------------
byte[] packet40_2 = makeKeepPacket40(2, false);
packet = new DatagramPacket(packet40_2, packet40_2.length, serverAddress, Constants.PORT);
client.send(packet);
// log.trace("[seq={}|type={}][rand={}|{}]send Keep40_2. 【{}】", packet40_2[1], packet40_2[5],
// ByteUtil.toHexString(packet40_2[8]), ByteUtil.toHexString(packet40_2[9]),
// ByteUtil.toHexString(packet40_2));
Log.d(TAG, "alive: " + "[seq=" + packet40_2[1] + "|type=" + packet40_2[5] + "][rand=" + ByteUtil.toHexString(packet40_2[8])
+ "|" + ByteUtil.toHexString(packet40_2[9]) + "]send keep40_2. 【" + ByteUtil.toHexString(packet40_2) + "】");
client.receive(new DatagramPacket(recv, recv.length));
// log.trace("[seq={}|type={}][rand={}|{}]recv Keep40_2. 【{}】", recv[1], recv[5],
// ByteUtil.toHexString(recv[8]), ByteUtil.toHexString(recv[9]), ByteUtil.toHexString(recv));
Log.d(TAG, "alive: " + "[seq=" + recv[1] + "|type=" + recv[5] + "][rand=" + ByteUtil.toHexString(recv[8])
+ "|" + ByteUtil.toHexString(recv[9]) + "]recv keep40_2. 【" + ByteUtil.toHexString(recv) + "】");
//keep40_2 的回复也不用理会
return true;
}
/**
* 0xff md5a:16位 0x00 0x00 0x00 tail1:16位 rand rand
*/
private byte[] makeKeepPacket38() {
byte[] data = new byte[38];
data[0] = (byte) 0xff;
System.arraycopy(md5a, 0, data, 1, md5a.length);//1+16=17
//17 18 19
System.arraycopy(tail1, 0, data, 20, tail1.length);//20+16=36
data[36] = ByteUtil.randByte();
data[37] = ByteUtil.randByte();
return data;
}
/**
* keep40_额外的 就是刚登录时, keep38 后发的那个会收到 272 This Program can not run in dos mode
* keep40_1 每 秒发送
* keep40_2
*/
private byte[] makeKeepPacket40(int firstOrSecond, boolean extra) {
byte[] data = new byte[40];
data[0] = 0x07;
data[1] = (byte) count++;//到了 0xff 会回到 0x00
data[2] = 0x28;
data[3] = 0x00;
data[4] = 0x0b;
// keep40_1 keep40_2
// 发送 接收 发送 接收
// 0x01 0x02 0x03 0xx04
if (firstOrSecond == 1 || extra) {//keep40_1 keep40_extra 是 0x01
data[5] = 0x01;
} else {
data[5] = 0x03;
}
if (extra) {
data[6] = 0x0f;
data[7] = 0x27;
} else {
data[6] = keepAliveVer[0];
data[7] = keepAliveVer[1];
}
data[8] = ByteUtil.randByte();
data[9] = ByteUtil.randByte();
//[10-15]:0
System.arraycopy(tail2, 0, data, 16, 4);//16+4=20
//20 21 22 23 : 0
if (firstOrSecond == 2) {
System.arraycopy(clientIp, 0, data, 24, 4);
byte[] tmp = new byte[28];
System.arraycopy(data, 0, tmp, 0, tmp.length);
tmp = ByteUtil.crc(tmp);
System.arraycopy(tmp, 0, data, 24, 4);//crc 24+4=28
System.arraycopy(clientIp, 0, data, 28, 4);//28+4=32
//之后 8 个 0
}
return data;
}
public void logoutNow() {
notifyLogout = true;// 终止后台进程
this.cancel(true);
Log.d(TAG, "logoutNow: 收到注销指令");
new Thread(new Runnable() {
@Override
public void run() {
try {
challenge(challengeTimes++);
logout();
} catch (Throwable t) {
Log.e(TAG, "logoutNow: 注销异常", t);
} finally {
// 重新登录
status = STATUS.offline;
keepListener.informLogoutSucceed();
// keepListener.informLogStatus(STATUS.offline);
if (client != null) {
client.close();
client = null;
}
}
}
}).start();
}
private boolean logout() throws IOException {
byte[] buf = makeLogoutPacket();
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddress, Constants.PORT);
client.send(packet);
// log.trace("send logout packet.【{}】", ByteUtil.toHexString(buf));
Log.d(TAG, "logout: " + "send logout packet.【" + ByteUtil.toHexString(buf) + "】");
byte[] recv = new byte[512];//25
client.receive(new DatagramPacket(recv, recv.length));
// log.trace("recv logout packet response.【{}】", ByteUtil.toHexString(recv));
Log.d(TAG, "logout: " + "recv logout packet response.【" + ByteUtil.toHexString(recv) + "】");
if (recv[0] == 0x04) {
// log.debug("注销成功");
Log.d(TAG, "logout: 注销成功");
} else {
// log.debug("注销...失败?");
Log.d(TAG, "logout: 注销失败");
}
this.cancel(true);
return true;
}
private byte[] makeLogoutPacket() {
byte[] data = new byte[80];
data[0] = 0x06;//code
data[1] = 0x01;//type
data[2] = 0x00;//EOF
data[3] = (byte) (username.length() + 20);
byte[] md5 = MD5.md5(new byte[]{0x06, 0x01}, salt, password.getBytes());
System.arraycopy(md5, 0, data, 4, md5.length);//md5 4+16=20
System.arraycopy(ByteUtil.ljust(username.getBytes(), 36),
0, data, 20, 36);//username 20+36=56
data[56] = 0x20;
data[57] = 0x05;
byte[] macBytes = hostInfo.getMacBytes();
for (int i = 0; i < 6; i++) {
data[58 + i] = (byte) (data[4 + i] ^ macBytes[i]);
}// mac xor md5 58+6=64
System.arraycopy(tail1, 0, data, 64, tail1.length);//64+16=80
return data;
}
}
| 26,323 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
SettingsActivity.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android-new/app/src/main/java/com/example/gui/SettingsActivity.java | package com.example.gui;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SwitchCompat;
import android.widget.CompoundButton;
import com.example.drclient.R;
public class SettingsActivity extends AppCompatActivity {
private SwitchCompat autoReconnectSwitch;
private SwitchCompat doNotSaveSwitch;
private SharedPreferences sharedPreferences;
public static final String FILE_NAME = "settings";
public static final String AUTO_RECONNECT = "auto_reconnect";
public static final String DO_NOT_SAVE = "not_save";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// 获取保存的设置信息
sharedPreferences = getSharedPreferences(FILE_NAME, MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
// 设置控件
autoReconnectSwitch = findViewById(R.id.auto_reconnect_when_disconnected_switch);
doNotSaveSwitch = findViewById(R.id.do_not_save_switch);
autoReconnectSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
editor.remove(AUTO_RECONNECT);
editor.putBoolean(AUTO_RECONNECT, isChecked);
editor.apply();
}
});
doNotSaveSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
editor.remove(DO_NOT_SAVE);
editor.putBoolean(DO_NOT_SAVE, isChecked);
editor.apply();
}
});
// 还原控件的设置选项
autoReconnectSwitch.setChecked(sharedPreferences.getBoolean(AUTO_RECONNECT, false));
doNotSaveSwitch.setChecked(sharedPreferences.getBoolean(DO_NOT_SAVE, false));
}
}
| 2,145 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
MainActivity.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android-new/app/src/main/java/com/example/gui/MainActivity.java | package com.example.gui;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.KeyListener;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.drclient.R;
import com.example.drcom.STATUS;
import com.example.service.KeepService;
import com.example.service.UIController;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private EditText userNameEditText;
private EditText passwordEditText;
private EditText macAddrEditText;
private Button loginButton;
private Context context = this;
private static final String TAG = "MainActivity";
private KeepService.KeepBinder keepBinder;
private STATUS status = STATUS.offline;
public boolean isAutoReconnect = false;
private boolean isNotSave = false;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG, "onServiceConnected: 已绑定服务");
keepBinder = (KeepService.KeepBinder) service;
keepBinder.setUIController(uiController);
Log.d(TAG, "onServiceConnected: 获取是否在线的信息");
status = keepBinder.isOnline() ? STATUS.online : STATUS.offline;
adjustUI(keepBinder.isOnline());
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG, "onServiceDisconnected: 已解绑服务");
}
};
private UIController uiController = new UIController() {
@Override
public void loggedIn(final String[] s) { // 登录成功
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "已登录", Toast.LENGTH_SHORT).show();
// 注销按钮可用
loginButton.setEnabled(true);
adjustUI(true);
status = STATUS.online;
SharedPreferences.Editor editor = getSharedPreferences("name_pass_mac", MODE_PRIVATE).edit();
editor.clear();
if (isNotSave) {
editor.apply();
Log.d(TAG, "run: 已清除密码");
userNameEditText.setText("");
passwordEditText.setText("");
macAddrEditText.setText("");
return;
}
editor.putString("name", s[0]);
editor.putString("pass", s[1]);
editor.putString("mac", s[2]);
editor.apply();
Log.d(TAG, "run: 已保存密码");
}
});
}
@Override
public void offline() {
runOnUiThread(new Runnable() {
@Override
public void run() {
// 掉线了,可能是注销了也可能是异常了,此时暂时还不允许重新登录,等待后台释放资源
if (!isAutoReconnect)
Toast.makeText(context, "已离线", Toast.LENGTH_SHORT).show();
status = STATUS.offline;
}
});
}
@Override
public void canLoginNow(final String[] s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
SharedPreferences settingsPreferences = getSharedPreferences(SettingsActivity.FILE_NAME, MODE_PRIVATE);
if (isAutoReconnect && keepBinder.canReconnect()) {
Log.d(TAG, "run: 无限重连中");
// 读取设置
isAutoReconnect = settingsPreferences.getBoolean(SettingsActivity.AUTO_RECONNECT, false);
status = STATUS.online;
adjustUI(true);
// 读取保存的用户名密码MAC地址
SharedPreferences preferences = getSharedPreferences("name_pass_mac", MODE_PRIVATE);
userNameEditText.setText(preferences.getString("name", ""));
passwordEditText.setText(preferences.getString("pass", ""));
macAddrEditText.setText(preferences.getString("mac", ""));
loginButton.setEnabled(false);
loginButton.setText("无限重连中");
keepBinder.login(s[0], s[1], s[2], context);
} else {
// 读取设置
isAutoReconnect = settingsPreferences.getBoolean(SettingsActivity.AUTO_RECONNECT, false);
adjustUI(false);
loginButton.setEnabled(true);
}
}
});
}
@Override
public void logoutSucceed() {
runOnUiThread(new Runnable() {
@Override
public void run() {
// 注销成功后暂时还不允许重新登录,等待后台释放资源
Toast.makeText(context, "注销成功", Toast.LENGTH_SHORT).show();
// adjustUI(false);
status = STATUS.offline;
}
});
}
@Override
public void invalidNameOrPass() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "用户名或密码错误", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void invalidMAC() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "MAC地址错误", Toast.LENGTH_SHORT).show();
}
});
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: 创建界面");
// 初始化各个控件
userNameEditText = findViewById(R.id.user_name_editText);
passwordEditText = findViewById(R.id.password_editText);
macAddrEditText = findViewById(R.id.mac_addr_editText);
loginButton = findViewById(R.id.login_button);
loginButton.setOnClickListener(this);
// 启动服务
Intent intent = new Intent(this, KeepService.class);
startService(intent);
// 绑定服务
bindService(intent, connection, BIND_AUTO_CREATE);
// 读取保存的用户名密码MAC地址
Log.d(TAG, "onCreate: 读取保存的密码");
SharedPreferences preferences = getSharedPreferences("name_pass_mac", MODE_PRIVATE);
userNameEditText.setText(preferences.getString("name", ""));
passwordEditText.setText(preferences.getString("pass", ""));
macAddrEditText.setText(preferences.getString("mac", ""));
// 读取设置
SharedPreferences settingsPreferences = getSharedPreferences(SettingsActivity.FILE_NAME, MODE_PRIVATE);
isAutoReconnect = settingsPreferences.getBoolean(SettingsActivity.AUTO_RECONNECT, false);
isNotSave = settingsPreferences.getBoolean(SettingsActivity.DO_NOT_SAVE, false);
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart: 重启界面");
// 读取保存的用户名密码MAC地址
SharedPreferences preferences = getSharedPreferences("name_pass_mac", MODE_PRIVATE);
userNameEditText.setText(preferences.getString("name", ""));
passwordEditText.setText(preferences.getString("pass", ""));
macAddrEditText.setText(preferences.getString("mac", ""));
// 读取设置
SharedPreferences settingsPreferences = getSharedPreferences(SettingsActivity.FILE_NAME, MODE_PRIVATE);
isAutoReconnect = settingsPreferences.getBoolean(SettingsActivity.AUTO_RECONNECT, false);
isNotSave = settingsPreferences.getBoolean(SettingsActivity.DO_NOT_SAVE, false);
// 设置当前状态以及按钮是否可用
Log.d(TAG, "onRestart: 获取是否在线的信息");
status = keepBinder.isOnline() ? STATUS.online : STATUS.offline;
adjustUI(keepBinder.isOnline());
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_button: {
if (status == STATUS.offline) {
String userName = userNameEditText.getText().toString();
String password = passwordEditText.getText().toString();
String macAddr = macAddrEditText.getText().toString();
if (!checkInput(userName, password, macAddr)) {
Toast.makeText(this, "输入有误", Toast.LENGTH_SHORT).show();
return;
}
status = STATUS.online;
adjustUI(true);
loginButton.setEnabled(false);
keepBinder.login(userName, password, macAddr, context);
} else if (status == STATUS.online){
loginButton.setEnabled(false);
isAutoReconnect = false;
keepBinder.logout();
}
break;
}
default:
}
}
private boolean checkInput(String name, String pass, String mac) {
if ("".equals(name)) return false;
if ("".equals(pass)) return false;
if ("".equals(mac)) return false;
if (mac.length() != 12) return false;
for (int i = 0; i < 12; i++) {
char x = mac.charAt(i);
if (!((x <= '9' && x >= '0') || (x >= 'a' && x <= 'z'))) return false;
}
return true;
}
@Override
protected void onDestroy() {
super.onDestroy();
// 解绑服务
Log.d(TAG, "onDestroy: 正在解绑服务");
unbindService(connection);
if (!keepBinder.isOnline()) {
stopService(new Intent(this, KeepService.class));
}
if (isNotSave) {
SharedPreferences.Editor editor = getSharedPreferences("name_pass_mac", MODE_PRIVATE).edit();
editor.clear();
editor.apply();
Log.d(TAG, "onDestroy: 已清除密码");
}
}
private void adjustUI(boolean online) {
if (online) {
userNameEditText.setKeyListener(null);
passwordEditText.setKeyListener(null);
macAddrEditText.setKeyListener(null);
loginButton.setText(R.string.logout);
} else {
KeyListener keyListener = (new EditText(getApplicationContext())).getKeyListener();
userNameEditText.setKeyListener(keyListener);
passwordEditText.setKeyListener(keyListener);
macAddrEditText.setKeyListener(keyListener);
loginButton.setText(R.string.login);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings: {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
break;
}
default:
break;
}
return true;
}
}
| 12,261 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
KeepListener.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android-new/app/src/main/java/com/example/service/KeepListener.java | package com.example.service;
import com.example.drcom.STATUS;
public interface KeepListener {
void keepingAlive(String content);
void informLogStatus(STATUS status, String[] s);
void informCanLoginNow(boolean canReconnect, String[] s);
void informLogoutSucceed();
void informInvalidNameOrPass();
void informInvalidMAC();
}
| 349 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
UIController.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android-new/app/src/main/java/com/example/service/UIController.java | package com.example.service;
public interface UIController {
void loggedIn(String[] s);
void offline();
void canLoginNow(String[] s);
void logoutSucceed();
void invalidNameOrPass();
void invalidMAC();
}
| 228 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
KeepService.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android-new/app/src/main/java/com/example/service/KeepService.java | package com.example.service;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.example.gui.MainActivity;
import com.example.drclient.R;
import com.example.drcom.DrcomTask;
import com.example.drcom.STATUS;
public class KeepService extends Service {
private static final String TAG = "KeepService";
private KeepBinder binder = new KeepBinder();
private KeepService keepService;
private UIController uiController;
private KeepListener keepListener = new KeepListener() {
@Override
public void keepingAlive(String content) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("com.example.service.KeepService", "DrClientChannel", NotificationManager.IMPORTANCE_LOW);
channel.enableVibration(false);
channel.enableLights(false);
notificationManager.createNotificationChannel(channel);
notification = new NotificationCompat.Builder(KeepService.this, "com.example.service.KeepService")
.setContentTitle(content)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(PendingIntent.getActivity(KeepService.this, 0, new Intent(KeepService.this, MainActivity.class), 0))
.build();
} else {
notification = new NotificationCompat.Builder(KeepService.this, "com.example.service.KeepService")
.setVibrate(new long[]{0L})
.setContentTitle(content)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(PendingIntent.getActivity(KeepService.this, 0, new Intent(KeepService.this, MainActivity.class), 0))
.build();
}
startForeground(1, notification);
}
@Override
public void informLogStatus(STATUS status, String[] s) {
if (status == STATUS.offline) {
uiController.offline();
stopForeground(true);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancelAll();
} else if (status == STATUS.online) {
uiController.loggedIn(s);
}
}
@Override
public void informCanLoginNow(boolean canReconnect, String[] s) {
drcomTask = new DrcomTask(keepListener);
drcomTask.canReconnect = canReconnect;
uiController.canLoginNow(s);
}
@Override
public void informLogoutSucceed() {
stopForeground(true);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancelAll();
uiController.logoutSucceed();
}
@Override
public void informInvalidNameOrPass() {
uiController.invalidNameOrPass();
}
@Override
public void informInvalidMAC() {
uiController.invalidMAC();
}
};
private DrcomTask drcomTask = new DrcomTask(keepListener);
private Context contextInMainActivity;
public KeepService() {
keepService = this;
}
@Override
public void onCreate() {
Log.d(TAG, "onCreate: 已启动服务");
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy: 已停止服务");
}
public class KeepBinder extends Binder {
public void setUIController(UIController uiController) {
keepService.uiController = uiController;
}
public void login(String name, String pass, String mac, Context context) {
contextInMainActivity = context;
drcomTask.setNamePassMAC(name, pass, mac);
drcomTask.execute();
}
public void logout() {
drcomTask.logoutNow();
}
public boolean isOnline() {
Log.d(TAG, "isOnline: 在service中查看是否在线");
return drcomTask.isOnline();
}
public boolean canReconnect() {
return drcomTask.canReconnect;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
}
}
| 4,921 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
ExampleInstrumentedTest.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android-new/app/src/androidTest/java/com/example/drclient/ExampleInstrumentedTest.java | package com.example.drclient;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.drclient", appContext.getPackageName());
}
}
| 724 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
packet_CRC.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android/src/com/example/drcom/packet_CRC.java | package com.example.drcom;
public class packet_CRC {
public static byte[] crc(byte[] check) throws NumberFormatException, Exception{
long ret = 0;
byte[] check_foo = new byte[2];
int j_foo = 1;
for(int j=0;j<check.length;j=j+2){
int i_foo = 0;
for(int i=0;i<2;i++){
if(2*j_foo-1-i_foo>check.length){break;}
check_foo[i] = check[2*j_foo-1-i_foo];
++i_foo;
}
j_foo++;
ret ^= Long.parseLong(ByteArr2HexStr.byteArr2HexStr(check_foo), 16);
}
ret = ret * 711;
byte[] pack = Int2ByteArr.intToByteArray(ret);
return pack;
}
}
| 584 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
keep_alive_package_builder.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android/src/com/example/drcom/keep_alive_package_builder.java | package com.example.drcom;
public class keep_alive_package_builder {
public static byte[] build(int number, byte[] random, byte[] tail, int type, boolean first) throws NumberFormatException, Exception{
byte[] data_1_1 = {0x07, (byte) number};
byte[] data_1_2 = {0x28, 0x00, 0x0b, (byte)type};
byte[] data_1 = ByteMerge.byteMerger(data_1_1, data_1_2);
byte[] data_2_1 = {0x0F, 0x27};
byte[] data_2_2 = {(byte) 0xdc, 0x02};
byte[] data_2;
if (first == true){
data_2 = ByteMerge.byteMerger(data_1, data_2_1);
}else{
data_2 = ByteMerge.byteMerger(data_1, data_2_2);
}
byte[] data_3_1 = random;
byte[] data_3_2 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
byte[] data_3_3 = ByteMerge.byteMerger(data_3_1, data_3_2);
byte[] data_3 = ByteMerge.byteMerger(data_2, data_3_3);
byte[] data_4 = ByteMerge.byteMerger(data_3, tail);
byte[] data_5_1 = {0x00, 0x00, 0x00, 0x00};
byte[] data_5 = ByteMerge.byteMerger(data_4, data_5_1);
byte[] data_6;
if(type==3){
byte[] foo = {0x31, (byte) 0x8c, 0x62, 0x31};
byte[] crc = packet_CRC.crc(ByteMerge.byteMerger(data_5, foo));
byte[] data_6_1 = {0x00, 0x00 ,0x00, 0x00 ,0x00, 0x00 ,0x00, 0x00};
byte[] data_6_2 = ByteMerge.byteMerger(crc, foo);
byte[] data_6_3 = ByteMerge.byteMerger(data_6_2, data_6_1);
data_6 = ByteMerge.byteMerger(data_5, data_6_3);
}else{
byte[] data_6_1 = {0x00, 0x00 ,0x00, 0x00 ,0x00, 0x00 ,0x00, 0x00, 0x00, 0x00 ,0x00, 0x00 ,0x00, 0x00 ,0x00, 0x00};
data_6 = ByteMerge.byteMerger(data_5, data_6_1);
}
return data_6;
}
}
| 1,562 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
mkpkt.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android/src/com/example/drcom/mkpkt.java | package com.example.drcom;
public class mkpkt {
public static byte[] dr_mkpkt(byte[] salt, String ipaddr, String usr, String pwd, String mac) throws Exception{
byte[] data_3 = new byte[36];
byte[] data_5 = new byte[6];
byte[] data_8 = new byte[16];
byte[] data_9 = new byte[8];
byte[] data_11 = new byte [32];
String ip = ipaddr; //MainActivity.ipaddr;
String[] ip_foo = ip.split("\\.");
int account_length = usr.length() + 20;
byte[] account = usr.getBytes();
byte[] mac_addr = HexStr2ByteArr.hexStr2ByteArr(mac);
byte[] foo_1 = {0x03, 0x01};
byte[] foo_2 = {0x01};
byte[] foo_3 = {0x00, 0x00, 0x00, 0x00};
byte[] foo_4 = {0x14, 0x00, 0x07, 0x0b};
// byte[] foo_5 = {0x03, 0x01};
byte[] foo_6 = {0x01, 0x26, 0x07, 0x11, 0x00, 0x00};
byte[] foo_7 = {0x00, 0x00};
byte[] merge_1 = ByteMerge.byteMerger(foo_1, salt);
byte[] merge_2 = ByteMerge.byteMerger(merge_1, pwd.getBytes());
byte[] merge_3 = ByteMerge.byteMerger(foo_2, pwd.getBytes());
byte[] merge_4 = ByteMerge.byteMerger(merge_3, salt);
byte[] merge_5 = ByteMerge.byteMerger(merge_4, foo_3);
// byte[] merge_6 = ByteMerge.byteMerger(foo_5, salt);
// byte[] merge_7 = ByteMerge.byteMerger(merge_6, pwd.getBytes());
byte[] data_1 = {0x03, 0x01, 0x00, (byte) account_length}; //code, type, EOF, username_length
byte[] data_2 = ByteMD5.MD5_lite(merge_2); //md5a
for(int data3_j=0;data3_j<account.length;data3_j++){
data_3[data3_j] = account[data3_j]; //username
}
for(int data3_i=account.length;data3_i<36;data3_i++){
data_3[data3_i] = 0x00;
}
byte[] data_4 = {0x00, 0x00}; //unknow, mac_flag
for(int i=0;i<6;i++){
data_5[i] = (byte) (data_2[i] ^ mac_addr[i]); //mac xor md5a
}
byte[] data_6 = ByteMD5.MD5_lite(merge_5); //md5b
byte[] data_7 = {0x01}; //nic count
for(int ip_i=0;ip_i<ip_foo.length;ip_i++){
data_8[ip_i] = (byte) Integer.parseInt(ip_foo[ip_i]); //ips
}
byte[] sum_1 = ByteMerge.byteMerger(data_1, data_2);
byte[] sum_2 = ByteMerge.byteMerger(sum_1, data_3);
byte[] sum_3 = ByteMerge.byteMerger(sum_2, data_4);
byte[] sum_4 = ByteMerge.byteMerger(sum_3, data_5);
byte[] sum_5 = ByteMerge.byteMerger(sum_4, data_6);
byte[] sum_6 = ByteMerge.byteMerger(sum_5, data_7);
byte[] sum_7 = ByteMerge.byteMerger(sum_6, data_8);
byte[] sum_8 = ByteMerge.byteMerger(sum_7, foo_4);
byte[] sum_foo = ByteMD5.MD5_lite(sum_8);
for(int sum_i=0;sum_i<8;sum_i++){
data_9[sum_i] = sum_foo[sum_i]; //checksum1
}
byte[] data_10 = {0x01, 0x00, 0x00, 0x00, 0x00}; //ipdog, zeros
for(int host_j=0;host_j<8;host_j++){
data_11[host_j] = 0x69;
} //hostname:iiiiiiii
for(int host_i=8;host_i<32;host_i++){
data_11[host_i] = 0x00;
}
byte[] data_12 = {0x0a, 0x0a, 0x0a, 0x0a}; //dns
byte[] data_13 = new byte[164]; //zero
byte[] data_14 = {0x6e, 0x00, 0x00, (byte)pwd.length()}; //unknown
byte[] data_15 = ror.dr_ror(ByteMD5.MD5_lite(merge_2), pwd); //md5 ror pwd
byte[] data_16 = {0x02, 0x0c};
byte[] sum_7_1 = ByteMerge.byteMerger(sum_7, data_9);
byte[] sum_7_2 = ByteMerge.byteMerger(sum_7_1, data_10);
byte[] sum_7_3 = ByteMerge.byteMerger(sum_7_2, data_11);
byte[] sum_7_4 = ByteMerge.byteMerger(sum_7_3, data_12);
byte[] sum_7_5 = ByteMerge.byteMerger(sum_7_4, data_13);
byte[] sum_7_6 = ByteMerge.byteMerger(sum_7_5, data_14);
byte[] sum_7_7 = ByteMerge.byteMerger(sum_7_6, data_15);
byte[] sum_7_8 = ByteMerge.byteMerger(sum_7_7, data_16);
byte[] merge_foo_6 = ByteMerge.byteMerger(sum_7_8, foo_6);
byte[] merge_foo_mac = ByteMerge.byteMerger(merge_foo_6, dump.dr_dump(mac));
byte[] data_17 = checksum.dr_checksum(merge_foo_mac);
byte[] data_18 = ByteMerge.byteMerger(foo_7, dump.dr_dump(mac));
byte[] merge_data_1 = ByteMerge.byteMerger(sum_7_8, data_17);
byte[] data = ByteMerge.byteMerger(merge_data_1, data_18);
return data;
}
}
| 4,067 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
MainActivity.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android/src/com/example/drcom/MainActivity.java | package com.example.drcom;
import android.os.Bundle;
import android.os.Looper;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private String ipaddr;
private String _account;
private String _mac;
private String _password;
private EditText account;
private EditText password;
private EditText mac;
private EditText ip;
private Button B_login;
private Button B_logout;
private SharedPreferences sp;
private byte[] authinfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
account = (EditText)this.findViewById(R.id.editText1);
password = (EditText)this.findViewById(R.id.editText2);
mac = (EditText)this.findViewById(R.id.editText3);
ip = (EditText)this.findViewById(R.id.editText4);
B_login = (Button)this.findViewById(R.id.button1);
B_logout = (Button)this.findViewById(R.id.button2);
account.setText(sp.getString("account", ""));
password.setText(sp.getString("password", ""));
mac.setText(sp.getString("mac", ""));
ip.setText(sp.getString("ip", ""));
B_login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
ipaddr = ip.getText().toString();
_account = account.getText().toString();
_password = password.getText().toString();
_mac = mac.getText().toString();
Editor editor = sp.edit();
editor.putString("account", _account);
editor.putString("password",_password);
editor.putString("ip", ipaddr);
editor.putString("mac", _mac);
editor.commit();
new Thread(new LoginThread(_account, ipaddr, _password, _mac)).start();
new Thread(new KeepThread()).start();
}
});
B_logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
ipaddr = ip.getText().toString();
_account = account.getText().toString();
_password = password.getText().toString();
_mac = mac.getText().toString();
Editor editor = sp.edit();
editor.putString("account", _account);
editor.putString("password",_password);
editor.putString("ip", ipaddr);
editor.putString("mac", _mac);
editor.commit();
new Thread(new LogoutThread(_account, ipaddr, _password, _mac, authinfo)).start();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class LoginThread implements Runnable{
private String dusr;
private String dipaddr;
private String dpwd;
private String dmac;
public LoginThread(String usr, String ipaddr, String pwd, String mac){
this.dusr = usr;
this.dipaddr = ipaddr;
this.dpwd = pwd;
this.dmac = mac;
}
@Override
public void run(){
String svr = "10.100.61.3";
try {
Looper.prepare();
authinfo = login.dr_login(this.dusr, this.dipaddr, this.dpwd, svr, this.dmac, getApplicationContext());
Looper.loop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class KeepThread implements Runnable{
@Override
public void run(){
String svr = "10.100.61.3";
try {
keep_alive.keep(svr);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class LogoutThread implements Runnable{
private String dusr;
private String dipaddr;
private String dpwd;
private String dmac;
private byte[] dauthinfo;
public LogoutThread(String usr, String ipaddr, String pwd, String mac, byte[] authinfo){
this.dusr = usr;
this.dipaddr = ipaddr;
this.dpwd = pwd;
this.dmac = mac;
this.dauthinfo = authinfo;
}
@Override
public void run(){
String svr = "10.100.61.3";
try {
Looper.prepare();
logout.dr_logout(this.dusr, this.dipaddr, this.dpwd, svr, this.dmac, authinfo, getApplicationContext());
Looper.loop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
| 5,098 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
ByteMerge.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android/src/com/example/drcom/ByteMerge.java | package com.example.drcom;
public class ByteMerge {
public static byte[] byteMerger(byte[] byte_1, byte[] byte_2){
byte[] byte_3 = new byte[byte_1.length+byte_2.length];
System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
return byte_3;
}
}
| 359 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
challenge.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android/src/com/example/drcom/challenge.java | package com.example.drcom;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Random;
public class challenge {
public static byte[] dr_challenge(String svr, boolean flag) throws Exception{
DatagramSocket client = new DatagramSocket();
InetAddress addr = InetAddress.getByName(svr);
Random random = new Random();
byte t = (byte)((random.nextInt(0xF)+0xF0) % 0xFFFF);
byte[] foo = {0x01, 0x02, t, 0x09,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00};
if(flag==false){
foo[1] = 0x03;
foo[3] = 0x6e;
}
DatagramPacket sendPacket = new DatagramPacket(foo, foo.length, addr, 61440);
client.send(sendPacket);
byte[] v = new byte[76];
DatagramPacket packet=new DatagramPacket(v, 76);
client.receive(packet);
if(v[0]==0x02){
System.out.println("challenge packet received");
}
//String pack_foo = "";
byte[] pack = new byte[4];
System.arraycopy(v, 4, pack, 0, 4);
return pack;
}
}
| 1,078 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
mkopkt.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android/src/com/example/drcom/mkopkt.java | package com.example.drcom;
public class mkopkt {
public static byte[] dr_mkopkt(byte[] salt, String ipaddr, String usr, String pwd, String mac, byte[] authinfo) throws Exception{
String ip = ipaddr; //MainActivity.ipaddr;
String[] ip_foo = ip.split("\\.");
byte[] username = new byte[36];
byte[] mxm = new byte[6];
int account_length = usr.length() + 20;
byte[] ctea = {0x06, 0x01, 0x00, (byte) account_length};
byte[] md5_foo_10 = {0x06, 0x01};
byte[] md5_foo_1 = ByteMerge.byteMerger(md5_foo_10, salt);
byte[] md5_foo = ByteMerge.byteMerger(md5_foo_1, pwd.getBytes());
byte[] md5a = ByteMD5.MD5_lite(md5_foo);
byte[] account = usr.getBytes();
for(int i=0;i<usr.length();i++){
username[i] = account[i];
}
for(int i=usr.length();i<35;i++){
username[i] = 0x00;
}
byte[] fm = {0x00, 0x03};
byte[] mac_addr = HexStr2ByteArr.hexStr2ByteArr(mac);
for(int i=0;i<6;i++){
mxm[i] = (byte) (mac_addr[i] ^ md5a[i]);
}
byte[] usr_ip = new byte[4];
for(int ip_i=0;ip_i<ip_foo.length;ip_i++){
usr_ip[ip_i] = (byte) Integer.parseInt(ip_foo[ip_i]);
}
byte[] data_1 = ByteMerge.byteMerger(ctea, md5a);
byte[] data_2 = ByteMerge.byteMerger(data_1, username);
byte[] data_3 = ByteMerge.byteMerger(data_2, fm);
byte[] data_4 = ByteMerge.byteMerger(data_3, mxm);
byte[] data = ByteMerge.byteMerger(data_4, authinfo);
System.out.println(data.length);
return data;
}
}
| 1,442 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
dump.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android/src/com/example/drcom/dump.java | package com.example.drcom;
public class dump {
public static byte[] dr_dump(String mac) throws NumberFormatException, Exception{
long foo = Long.parseLong(mac, 16);;
String s= Long.toHexString(foo);
if(s.length() % 2 == 1){
String str_foo = "0" + s;
return HexStr2ByteArr.hexStr2ByteArr(str_foo);
}
return HexStr2ByteArr.hexStr2ByteArr(s);
}
}
| 370 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
checksum.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android/src/com/example/drcom/checksum.java | package com.example.drcom;
public class checksum {
public static byte[] dr_checksum(byte[] check) throws Exception{
long ret = 1234;
byte[] check_foo = new byte[4];
int j_foo = 1;
for(int j=0;j<check.length;j=j+4){
int i_foo = 0;
for(int i=0;i<4;i++){
if(4*j_foo-1-i_foo>check.length){break;}
check_foo[i] = check[4*j_foo-1-i_foo];
++i_foo;
}
j_foo++;
ret ^= Long.parseLong(ByteArr2HexStr.byteArr2HexStr(check_foo), 16);
}
long ret_foo = 4294967295L;
ret = (1968 * ret) & ret_foo;
byte[] pack = Int2ByteArr.intToByteArray(ret);
return pack;
}
}
| 631 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
ror.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android/src/com/example/drcom/ror.java | package com.example.drcom;
public class ror {
public static byte[] dr_ror(byte[] md5, String pwd) throws Exception{
String ret = "";
char[] pwd_foo = pwd.toCharArray();
for(int i=0;i<pwd.length();i++){
byte[] gg = {md5[i]};
int x = Integer.valueOf(ByteArr2HexStr.byteArr2HexStr(gg), 16) ^ Integer.valueOf(pwd_foo[i]);
int a = (x << 3)&0xFF;
int b = x >> 5;
int c = (a + b) & 0xFF;
if(Integer.toHexString(c).length()==1){
String foo = "0" + Integer.toHexString(c);
ret += foo;
}else{
ret = ret + Integer.toHexString(c);
}
}
return HexStr2ByteArr.hexStr2ByteArr(ret);
}
}
| 638 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
keep_alive.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android/src/com/example/drcom/keep_alive.java | package com.example.drcom;
import java.util.Random;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class keep_alive {
public static void keep(String svr) throws NumberFormatException, Exception{
Random random = new Random();
byte[] tail = new byte[4];
int ran = random.nextInt(0xFFFF);
ran = ran + 1 + random.nextInt(9);
byte[] tail_foo = {0x00, 0x00, 0x00, 0x00};
byte[] packet = keep_alive_package_builder.build(0, Int2ByteArr.intToByteArray(ran), tail_foo, 1, true);
DatagramSocket client = new DatagramSocket();
InetAddress addr = InetAddress.getByName(svr);
DatagramPacket sendPacket = new DatagramPacket(packet, packet.length, addr, 61440);
client.send(sendPacket);
ran = ran + 1 + random.nextInt(9);
byte[] packet_2 = keep_alive_package_builder.build(1, Int2ByteArr.intToByteArray(ran), tail_foo, 1, false);
DatagramSocket client_2 = new DatagramSocket();
DatagramPacket sendPacket_2 = new DatagramPacket(packet_2, packet_2.length, addr, 61440);
client_2.send(sendPacket_2);
byte[] receive_2 = new byte[40];
DatagramPacket re_packet_2=new DatagramPacket(receive_2, 40);
client_2.receive(re_packet_2);
for(int i=0;i<4;i++){
tail[i] = receive_2[16+i];
}
ran = ran + 1 + random.nextInt(9);
byte[] packet_3 = keep_alive_package_builder.build(2, Int2ByteArr.intToByteArray(ran), tail, 3, false);
DatagramSocket client_3 = new DatagramSocket();
DatagramPacket sendPacket_3 = new DatagramPacket(packet_3, packet_3.length, addr, 61440);
client_3.send(sendPacket_3);
byte[] receive_3 = new byte[40];
DatagramPacket re_packet_3=new DatagramPacket(receive_3, 40);
client_3.receive(re_packet_3);
for(int i=0;i<4;i++){
tail[i] = receive_3[16+i];
}
System.out.println("[keep-alive2] keep-alive2 loop was in daemon.");
while(true){
Thread.sleep(5000);
//sleep 5
ran = ran + 1 + random.nextInt(9);
byte[] packet_4 = keep_alive_package_builder.build(2, Int2ByteArr.intToByteArray(ran), tail, 1, false);
DatagramSocket client_4 = new DatagramSocket();
DatagramPacket sendPacket_4 = new DatagramPacket(packet_4, packet_4.length, addr, 61440);
client_4.send(sendPacket_4);
byte[] receive_4 = new byte[40];
DatagramPacket re_packet_4=new DatagramPacket(receive_4, 40);
client_4.receive(re_packet_4);
for(int i=0;i<4;i++){
tail[i] = receive_4[16+i];
}
ran = ran + 1 + random.nextInt(9);
byte[] packet_5 = keep_alive_package_builder.build(2, Int2ByteArr.intToByteArray(ran), tail, 3, false);
DatagramSocket client_5 = new DatagramSocket();
DatagramPacket sendPacket_5 = new DatagramPacket(packet_5, packet_5.length, addr, 61440);
client_5.send(sendPacket_5);
byte[] receive_5 = new byte[40];
DatagramPacket re_packet_5=new DatagramPacket(receive_5, 40);
client_5.receive(re_packet_5);
for(int i=0;i<4;i++){
tail[i] = receive_5[16+i];
}
}
}
}
| 2,973 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
logout.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android/src/com/example/drcom/logout.java | package com.example.drcom;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.content.Context;
import android.widget.Toast;
public class logout {
public static void dr_logout(String usr, String ipaddr, String pwd, String svr, String mac, byte[] authinfo, Context context) throws Exception{
byte[] salt = challenge.dr_challenge(svr, false);
byte[] packet = mkopkt.dr_mkopkt(salt, ipaddr, usr, pwd, mac, authinfo);
DatagramSocket client = new DatagramSocket();
InetAddress addr = InetAddress.getByName(svr);
DatagramPacket sendPacket = new DatagramPacket(packet, packet.length, addr, 61440);
client.send(sendPacket);
byte[] receive = new byte[25];
DatagramPacket re_packet=new DatagramPacket(receive, 25);
client.receive(re_packet);
if(receive[0]==0x04){
Toast.makeText(context, "注销成功", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "注销失败", Toast.LENGTH_SHORT).show();
}
}
}
| 1,007 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
login.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/drcom-android/src/com/example/drcom/login.java | package com.example.drcom;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.annotation.SuppressLint;
import android.content.Context;
import android.widget.Toast;
public class login {
@SuppressLint("ShowToast")
public static byte[] dr_login(String usr, String ipaddr, String pwd, String svr, String mac, Context context) throws Exception{
byte[] salt = challenge.dr_challenge(svr, true);
/*for(int i=0;i<salt.length;i++){
System.out.println(Integer.toHexString(salt[i]));
}*/
//String salt_foo = "c122a300";
//byte[] salt = HexStr2ByteArr.hexStr2ByteArr(salt_foo);
byte[] packet = mkpkt.dr_mkpkt(salt, ipaddr, usr, pwd, mac);
DatagramSocket client = new DatagramSocket();
InetAddress addr = InetAddress.getByName(svr);
DatagramPacket sendPacket = new DatagramPacket(packet, packet.length, addr, 61440);
client.send(sendPacket);
byte[] receive = new byte[45];
DatagramPacket re_packet=new DatagramPacket(receive, 45);
client.receive(re_packet);
if(receive[0]==0x04){
Toast.makeText(context, "登陆成功", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "登陆失败", Toast.LENGTH_SHORT).show();
}
byte[] data = new byte[16];
for(int i=23;i<39;i++){
data[i-23] = receive[i];
}
return data;
}
}
| 1,345 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
Drcom.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/jlu-drcom-java/src/main/java/com/youthlin/jlu/drcom/Drcom.java | package com.youthlin.jlu.drcom;
import com.youthlin.jlu.drcom.bean.STATUS;
import com.youthlin.jlu.drcom.controller.AppController;
import com.youthlin.jlu.drcom.util.Constants;
import com.youthlin.jlu.drcom.util.FxUtil;
import com.youthlin.utils.i18n.Translation;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.UUID;
import static com.youthlin.jlu.drcom.util.FxUtil.icon;
import static com.youthlin.utils.i18n.Translation.__;
//Created by lin on 2017-01-08-008.
public class Drcom extends Application {
public static final String TITLE;
static {
//放在 log 之前初始化//前一次commit被IDEA自动格式化放乱了
System.setProperty("drcom.java.sessionID", UUID.randomUUID().toString().substring(24));
System.setProperty("drcom.java.data.home", Constants.DATA_HOME);
Translation.setDft(Translation.getBundle("Drcom"));
TITLE = __("JLU Drcom Java Version");
}
private static final Logger log = LoggerFactory.getLogger(Drcom.class);
private static AppController appController;
private static Stage stage;
private static long lastKey;
private static long thisKey;
private TrayIcon trayIcon;
public static void main(String[] args) {
Application.launch(Drcom.class, args);
}
public static void setAppController(AppController appController) {
Drcom.appController = appController;
}
public static Stage getStage() {
return stage;
}
@Override
public void start(Stage stage) throws IOException {
Thread.currentThread().setName("JavaFxApp");
log.trace("重命名 Fx 线程名称为{}", Thread.currentThread().getName());
Drcom.stage = stage;
if (!checkSingleton()) {
log.debug("已有运行中客户端");
Alert alert = FxUtil.buildAlert(__("There is a running client, no necessary to start a new client."));
alert.setHeaderText(__("Note: There is already a running client."));
alert.setOnHiding(e -> Platform.exit());//关闭对话框后退出
alert.show();
return;
}
stage.getIcons().add(icon);
stage.setTitle(TITLE);
Parent root = FXMLLoader.load(getClass().getResource("/login.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.sizeToScene();
stage.setMinWidth(310);
stage.centerOnScreen();
stage.setResizable(false);
// https://gist.github.com/jewelsea/e231e89e8d36ef4e5d8a#file-javafxtrayiconsample-java-L39
// instructs the javafx system not to exit implicitly when the last application window is shut.
// 最后一个窗口关闭也不退出
Platform.setImplicitExit(false);//仅通过退出按钮或退出菜单退出
enableTray(stage);//启用托盘
stage.show();
appController.init();
}
// Java Swing 每次打开只运行一个实例,并激活任务栏里的程序
// http://blog.csdn.net/lovoo/article/details/52541632
private boolean checkSingleton() {
File tmp = new File(Constants.DATA_HOME, Constants.LOCK_FILE_NAME);
log.trace("lock file = {}", tmp);
try {
//noinspection ResultOfMethodCallIgnored
tmp.createNewFile();
RandomAccessFile r = new RandomAccessFile(tmp, "rw");
FileChannel fc = r.getChannel();
FileLock lock = fc.tryLock();
if (lock == null || !lock.isValid()) {
// 如果没有得到锁,则程序退出.
// 没有必要手动释放锁和关闭流,当程序退出时,他们会被关闭的.
return false;
}
{
//@since (ver=1) 使用 3DES 加密密码进行存储
log.trace("lock file len = {}", r.length());
if (r.length() > 0) {
int version = r.readInt();
lastKey = r.readLong();//读取上次用于加密的key
log.trace("version = {},long = {}", version, lastKey);
}
thisKey = System.currentTimeMillis();
r.seek(0L);//从头开始写(覆盖)
r.writeInt(Constants.VER_1);
r.writeLong(thisKey);//保存本次退出时用于加密的 key
}
} catch (IOException e) {
log.debug("IOException", e);
return false;
}
return true;
}
@Override
public void stop() throws Exception {
SystemTray.getSystemTray().remove(trayIcon);
if (appController != null) {
appController.updateConf();//退出时再检查配置文件是否发生改变
}
log.debug("stop app.");
}
private void enableTray(final Stage stage) {
PopupMenu popupMenu = new PopupMenu();
java.awt.MenuItem openItem = new java.awt.MenuItem(__("Show / Hide"));
java.awt.MenuItem logout = new java.awt.MenuItem(__("Logout"));
java.awt.MenuItem quitItem = new java.awt.MenuItem(__("Quit"));
openItem.addActionListener(e -> {
if (stage.isShowing()) {
Platform.runLater(stage::hide);
} else {
Platform.runLater(stage::show);
}
});
logout.addActionListener(e -> {
if (appController != null && appController.getStatus().equals(STATUS.logged)) {
appController.logout();
Platform.runLater(stage::show);
}
});
quitItem.addActionListener(e -> {
if (appController != null) {
appController.logout();
}
Platform.exit();
});
popupMenu.add(openItem);
popupMenu.add(logout);
popupMenu.add(quitItem);
try {
SystemTray tray = SystemTray.getSystemTray();
BufferedImage image = ImageIO.read(Drcom.class.getResourceAsStream(Constants.LOGO_URL));
trayIcon = new TrayIcon(image, TITLE, popupMenu);
trayIcon.setImageAutoSize(true);
tray.add(trayIcon);
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {//鼠标左键
if (stage.isShowing()) {
Platform.runLater(stage::hide);
} else {
Platform.runLater(stage::show);
}
}
}
});
} catch (Exception e) {
log.debug("Exception. 托盘不可用.", e);
}
}
public static long getLastKey() {
return lastKey;
}
public static long getThisKey() {
return thisKey;
}
}
| 7,534 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
HostInfo.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/jlu-drcom-java/src/main/java/com/youthlin/jlu/drcom/bean/HostInfo.java | package com.youthlin.jlu.drcom.bean;
/**
* Created by lin on 2017-01-10-010.
* 机器的IP、HostName、MAC等
*/
public class HostInfo {
private final byte[] macBytes = new byte[6];
private String hostname;
private String macHexDash;
private String macNoDash;
private String address4 = "0.0.0.0";//仅用于显示
private String networkInterfaceDisplayName;
public HostInfo(String hostname, String macHex, String networkInterfaceDisplayName) {
this.hostname = hostname;
this.networkInterfaceDisplayName = networkInterfaceDisplayName;
checkHexToDashMac(macHex);
}
private void checkHexToDashMac(String mac) {
if (mac.contains("-")) {
mac = mac.replaceAll("-", "");
}
if (mac.length() != 12) {
throw new RuntimeException("MAC 地址格式错误。应为 xx-xx-xx-xx-xx-xx 或 xxxxxxxxxxxx 格式的 16 进制: " + mac);
}
try {
//noinspection ResultOfMethodCallIgnored
Long.parseLong(mac, 16);
} catch (NumberFormatException e) {
throw new RuntimeException("MAC 地址格式错误。应为 xx-xx-xx-xx-xx-xx 或 xxxxxxxxxxxx 格式的 16 进制: " + mac);
}
StringBuilder sb = new StringBuilder(18);
for (int i = 0; i < 12; i++) {
sb.append(mac.charAt(i++)).append(mac.charAt(i)).append("-");
}
macHexDash = sb.substring(0, 17);
macNoDash = mac;
String[] split = macHexDash.split("-");
for (int i = 0; i < split.length; i++) {
macBytes[i] = (byte) Integer.parseInt(split[i], 16);
}
}
@Override
public String toString() {
return "[" + macHexDash + '/' + address4 + " - "
+ networkInterfaceDisplayName + '/' + hostname + ']';
}
public byte[] getMacBytes() {
return macBytes;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getAddress4() {
return address4;
}
public void setAddress4(String address4) {
this.address4 = address4;
}
public String getMacHexDash() {
return macHexDash;
}
public void setMacHexDash(String macHexDash) {
checkHexToDashMac(macHexDash);
}
public String getMacNoDash() {
return macNoDash;
}
public void setMacNoDash(String macNoDash) {
checkHexToDashMac(macNoDash);
}
public String getNetworkInterfaceDisplayName() {
return networkInterfaceDisplayName;
}
public void setNetworkInterfaceDisplayName(String networkInterfaceDisplayName) {
this.networkInterfaceDisplayName = networkInterfaceDisplayName;
}
}
| 2,811 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
STATUS.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/jlu-drcom-java/src/main/java/com/youthlin/jlu/drcom/bean/STATUS.java | package com.youthlin.jlu.drcom.bean;
/**
* Created by lin on 2017-01-13-013.
* 登录状态
*/
public enum STATUS {
init, ready, onLogin, logged
}
| 155 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
AppController.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/jlu-drcom-java/src/main/java/com/youthlin/jlu/drcom/controller/AppController.java | package com.youthlin.jlu.drcom.controller;
import com.youthlin.jlu.drcom.Drcom;
import com.youthlin.jlu.drcom.bean.HostInfo;
import com.youthlin.jlu.drcom.bean.STATUS;
import com.youthlin.jlu.drcom.task.DrcomTask;
import com.youthlin.jlu.drcom.util.ByteUtil;
import com.youthlin.jlu.drcom.util.Constants;
import com.youthlin.jlu.drcom.util.FxUtil;
import com.youthlin.jlu.drcom.util.IPUtil;
import com.youthlin.jlu.drcom.util.MD5;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventTarget;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.text.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.time.Year;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.ResourceBundle;
import static com.youthlin.jlu.drcom.util.FxUtil.icon;
import static com.youthlin.jlu.drcom.util.FxUtil.loading;
import static com.youthlin.utils.i18n.Translation.__;
import static com.youthlin.utils.i18n.Translation._x;
/**
* Created by lin on 2017-01-08-008.
* 登录页面
*/
@SuppressWarnings("unused")
public class AppController implements Initializable {
private static final Logger log = LoggerFactory.getLogger(AppController.class);
public Menu fileMenu;
public Menu helpMenu;
public Button logoutButton;
public Button loginButton;
public TextField usernameTextField;
public Label tipLabel;
public CheckBox rememberCheckBox;
public PasswordField passwordField;
public Label statusLabel;
public ComboBox<HostInfo> macComboBox;
public CheckBox autoLoginCheckBox;
public ImageView imageView;
public Label autoLoginLabel;
public Label rememberLabel;
public MenuItem noticeMenuItem;
public MenuItem quitMenuItem;
public MenuItem introduceMenuItem;
public MenuItem aboutMenuItem;
public Label usernameLabel;
public Tooltip usernameToolTip;
public Tooltip passwordToolTip;
public Tooltip macToolTip;
public Label passwordLabel;
public Text welcomeText;
private STATUS status = STATUS.ready;
private DrcomTask drcomTask;
private String savedMac;//保存之前配置的 MAC: 当 ready 之前 init 时就退出时界面中没有 MAC 地址
@Override
public void initialize(URL location, ResourceBundle resources) {
log.debug("初始化界面...");
welcomeText.setText(__("Welcome to use JLU Drcom (Java Version)"));
fileMenu.setText(__("File(F)"));
noticeMenuItem.setText(_x("Notice", "校园网通知"));
quitMenuItem.setText(__("Quit"));
helpMenu.setText(__("Help(H)"));
introduceMenuItem.setText(__("Introduce"));
aboutMenuItem.setText(__("About"));
usernameLabel.setText(__("Username"));
usernameToolTip.setText(__("Part before @ symbol of your JLU email account"));
passwordLabel.setText(__("Password"));
passwordField.setPromptText(__("Password"));
passwordToolTip.setText(__("Password of your JLU email account"));
macToolTip.setText(__("MAC address registered in Network Center"));
rememberLabel.setText(__("Remember"));
autoLoginLabel.setText(__("Auto Login"));
loginButton.setText(__("Login(L)"));
logoutButton.setText(__("Logout(X)"));
statusLabel.setText(__("Ready"));
Drcom.setAppController(this);
imageView.setImage(loading);
setStatus(STATUS.init);
}
public STATUS getStatus() {
return status;
}
public void setStatus(STATUS status) {
log.debug("Change status to: " + status.name());
this.status = status;
switch (status) {
case init:
imageView.setVisible(true);
statusLabel.setText(__("Initialization..."));
loginButton.setDisable(true);
setUIDisable(true);
logoutButton.setFocusTraversable(false);//不能tab到按钮
break;
case ready:
imageView.setVisible(false);
statusLabel.setText(__("Ready"));
loginButton.setText(__("Login(L)"));
loginButton.setDisable(false);
setUIDisable(false);
logoutButton.setFocusTraversable(true);//可以tab到按钮
break;
case onLogin:
imageView.setVisible(true);
statusLabel.setText(__("Logging in..."));
loginButton.setText(__("Logging in..."));
loginButton.setDisable(true);
setUIDisable(true);
statusLabel.requestFocus();
break;
case logged:
imageView.setVisible(false);
statusLabel.setText(__("Logout"));
loginButton.setText(__("Logout(L)"));
loginButton.setDisable(false);
setUIDisable(true);
break;
}
}
public void init() {
readNamePass();//先把可以立即确定的输入项填充
readNetWorkInfo();
}
private void readNamePass() {
log.debug("读取配置文件中用户名密码信息...");
File file = new File(Constants.CONF_HOME, Constants.CONF_FILE_NAME);
if (file.exists()) {
try {
Properties conf = new Properties();
conf.load(new FileInputStream(file));
String username = conf.getProperty(Constants.KEY_USERNAME, "");
usernameTextField.setText(username);
String pass = conf.getProperty(Constants.KEY_PASSWORD, "");
try {
//@since 1.0.1 使用 3DES 加密密码进行存储
String version = conf.getProperty(Constants.KEY_VERSION, "");
//上次加密的 key username 可长达25位 因此 lastKey 放在前
String key = Drcom.getLastKey() + username;
if (version.equals(Constants.VER_1 + "")) {
if (pass.length() > 0 && Drcom.getLastKey() != 0L) {
byte[] bytes = ByteUtil.fromHex(pass);
pass = new String(MD5.decrypt3DES(ByteUtil.ljust(key.getBytes(), MD5.DES_KEY_LEN), bytes));
//log.trace("load key = {}, pass = {}", key, pass);
}
}
} catch (Exception e) {
log.debug("读取保存的密码时出现异常, 可能的原因: 上次未正确关闭软件. {}", e.getMessage(), e);
pass = "";
}//第一个版本是明文
///log.trace("load pass = {}", pass);
passwordField.setText(pass);
savedMac = conf.getProperty(Constants.KEY_DASH_MAC);
rememberCheckBox.setSelected(Boolean.valueOf(conf.getProperty(Constants.KEY_REMEMBER, "true")));
autoLoginCheckBox.setSelected(Boolean.valueOf(conf.getProperty(Constants.KEY_AUTO_LOGIN, "false")));
// 获取 MAC 后才自动登录
log.debug("读取配置文件完成");
} catch (IOException e) {
log.debug("读取配置文件时 IO 异常", e);
e.printStackTrace();
}
} else {
log.debug("配置文件不存在");
}
}
private void readNetWorkInfo() {
log.debug("获取网络接口信息...");
statusLabel.setText(__("Getting network interface information..."));
long start = System.currentTimeMillis();
new Thread(() -> IPUtil.getHostInfo(
new IPUtil.OnGetHostInfoCallback() {
@Override
public void update(int current, int total) {
FxUtil.updateLabel(statusLabel, __("({0}/{1})Getting network interface information...", 0, current, total));
}
@Override
public void done(List<HostInfo> hostInfoList) {
log.debug("获取网络接口信息完成.[用时:{}ms]", System.currentTimeMillis() - start);
Platform.runLater(() -> {
macComboBox.getItems().addAll(hostInfoList);
if (hostInfoList.size() == 1) {
macComboBox.getSelectionModel().select(0);
} else {
for (HostInfo p : hostInfoList) {
if (IPUtil.isPublicIP(p.getAddress4())) {
macComboBox.getSelectionModel().select(p);
}
}
}
log.debug("初始化界面完成.[用时:{}ms]", System.currentTimeMillis() - start);
readMac();
});
}
}),
"Host Info"
).start();
}
private void readMac() {
log.debug("读取配置文件中 MAC 地址信息...");
File file = new File(Constants.CONF_HOME, Constants.CONF_FILE_NAME);
if (file.exists()) {
try {
Properties conf = new Properties();
conf.load(new FileInputStream(file));
ObservableList<HostInfo> items = macComboBox.getItems();
String dashMac = conf.getProperty(Constants.KEY_DASH_MAC);
boolean find = false;
if (dashMac != null && dashMac.trim().length() > 0) {
for (HostInfo info : items) {//保存了 MAC 地址
if (info.getMacHexDash().equals(dashMac)) {
macComboBox.getSelectionModel().select(info);
find = true;
break;
}
}
}
//用无线上网会保存无线接口MAC//当改用有线时不能用无线的MAC
for (HostInfo info : items) {
if (IPUtil.isPublicIP(info.getAddress4())) {
macComboBox.getSelectionModel().select(info);
find = true;
break;
}
}
if (!find && dashMac != null && dashMac.trim().length() > 0) {
//保存的MAC不是本机MAC地址,保存的配置也加入选项并设为默认: 比如是用的路由器MAC
HostInfo hostInfo = new HostInfo(conf.getProperty(Constants.KEY_HOSTNAME, "Windows-10"),
dashMac, __("Saved Mac Address"));
macComboBox.getItems().add(hostInfo);
macComboBox.getSelectionModel().select(hostInfo);
}
log.debug("读取配置文件完成");
} catch (IOException e) {
log.debug("读取配置文件时 IO 异常", e);
e.printStackTrace();
} finally {
readConfDone();
}
} else {
log.debug("配置文件不存在");
readConfDone();
}
}
private void readConfDone() {
setStatus(STATUS.ready);
if (usernameTextField.getText() != null && usernameTextField.getText().trim().length() == 0) {
usernameTextField.requestFocus();//输入用户名
} else if (passwordField.getText() != null && passwordField.getText().trim().length() == 0) {
passwordField.requestFocus();//输入密码
} else if (macComboBox.getSelectionModel().getSelectedItem() == null) {
macComboBox.requestFocus();//选择 MAC 地址
} else {
loginButton.requestFocus();//登录
}
// 获取 MAC 后才自动登录
if (autoLoginCheckBox.isSelected()) {
onLoginButtonClick(new ActionEvent(autoLoginCheckBox, loginButton));
}
}
public void onLoginButtonClick(ActionEvent actionEvent) {
log.debug("点击{}按钮", loginButton.getText());
switch (status) {
case ready:
if (!checkInput()) {
return;
}
updateConf();
login();
break;
case logged:
logout();
break;
}
}
private boolean checkInput() {
log.trace("检查输入项目...");
tipLabel.setText("");
String username = usernameTextField.getText();
String password = passwordField.getText();
HostInfo item = macComboBox.getSelectionModel().getSelectedItem();
boolean success = true;
if (username == null || username.trim().length() == 0) {
success = false;
tipLabel.setText(__("{0} Please input username.", 0, tipLabel.getText()));
usernameTextField.requestFocus();
}
if (password == null || password.trim().length() == 0) {
if (success) {
passwordField.requestFocus();
}
success = false;
tipLabel.setText(__("{0} Please input password.", 0, tipLabel.getText()));
}
if (item == null) {
if (success) {
macComboBox.requestFocus();
}
success = false;
tipLabel.setText(__("{0} Please choose Mac.", 0, tipLabel.getText()));
}
return success;
}
public void updateConf() {
boolean remember = rememberCheckBox.isSelected();
boolean auto = autoLoginCheckBox.isSelected();
String username = usernameTextField.getText();
String password = passwordField.getText();
HostInfo hostInfo = macComboBox.getSelectionModel().getSelectedItem();
String macHexDash = "";
if (hostInfo != null) {
macHexDash = hostInfo.getMacHexDash();
}
log.debug("username = {}, password = {}, mac = {}, remember = {},auto login = {}",
username, "*" + password.length() + '*', macHexDash, remember, auto);
File file = new File(Constants.CONF_HOME, Constants.CONF_FILE_NAME);
if (remember) {
log.trace("写入配置文件...");
Properties conf = new Properties();
conf.put(Constants.KEY_USERNAME, username);
{
//@since (ver=1) 使用 3DES 加密密码进行存储
conf.put(Constants.KEY_VERSION, Constants.VER_1 + "");
byte[] bytes = new byte[0];
String key = Drcom.getThisKey() + username;//本次加密的 key
if (password.length() > 0 && Drcom.getThisKey() != 0L) {//有密码才加密
bytes = MD5.encrypt3DES(ByteUtil.ljust(key.getBytes(), MD5.DES_KEY_LEN), password.getBytes());
//log.trace("store key = {}, pass = {}", key, ByteUtil.toHexString(bytes));
}
conf.put(Constants.KEY_PASSWORD, ByteUtil.toHexString(bytes));
}
if (macHexDash.length() > 0) {
conf.put(Constants.KEY_DASH_MAC, macHexDash);
} else if (savedMac != null) {//正在获取 MAC 信息时就退出就保存上次配置的
conf.put(Constants.KEY_DASH_MAC, savedMac);
}
conf.put(Constants.KEY_REMEMBER, Boolean.toString(true));
conf.put(Constants.KEY_AUTO_LOGIN, Boolean.toString(auto));
try {
if (!file.getParentFile().exists()) {
//noinspection ResultOfMethodCallIgnored
file.getParentFile().mkdirs();
}
if (!file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.createNewFile();
}
conf.store(new FileWriter(file), "Config file for Dr.Com(Java) By YouthLin");
} catch (Exception e) {
log.debug("保存配置文件时发生异常", e);
FxUtil.showAlertWithException(new Exception("保存配置文件时发生异常", e));
}
} else {
//不勾选记住密码, 删掉原来保存的配置
if (file.exists()) {
log.trace("删除配置文件...");
try {
//noinspection ResultOfMethodCallIgnored
file.delete();
} catch (Exception e) {
log.debug("删除配置文件异常");
}
}
}
}
private void login() {
setStatus(STATUS.onLogin);//登陆中
drcomTask = new DrcomTask(this);
Thread thread = new Thread(drcomTask);
thread.setDaemon(true);
thread.start();//登录成功或异常都会改变status
}
public void logout() {
if (drcomTask != null) {
new Thread(() -> drcomTask.notifyLogout(), "Log out").start();
}
}
private void setUIDisable(boolean flag) {
usernameTextField.setDisable(flag);
passwordField.setDisable(flag);
rememberCheckBox.setDisable(flag);
autoLoginCheckBox.setDisable(flag);
macComboBox.setDisable(flag);
}
public void onExitMenuItemClick(ActionEvent actionEvent) {
log.trace("点击退出菜单项...");
logout();
Platform.exit();
}
public void onInfoMenuItemClick(ActionEvent actionEvent) {
log.trace("点击说明菜单项...");
FxUtil.showAlert(__("Welcome to use JLU Drcom(Java Version, 3rd party)\nPlease do not connect wired network and wireless network at the same time\nYou may need to restart the client when network changed.\nYou can contact me on 'About' menu.\n"));
}
public void onAboutMenuItemClick(ActionEvent actionEvent) {
log.trace("点击关于菜单项...");
String yearStr;
if (Year.now().isAfter(Year.parse(Constants.COPYRIGHT_YEAR_START))) {
yearStr = Constants.COPYRIGHT_YEAR_START + " - " + Year.now().toString();
} else {
yearStr = Constants.COPYRIGHT_YEAR_START;
}
Alert alert = FxUtil.buildAlert(/*TRANSLATORS: 0 year(eg:2017-2018). 1 Author nickname. 2 QQ Group. 3 CC by-nc-sa. 4 blog url.*/
__("© {0} {1}\nQQ Group: {2}\nLicense : {3}\nArticle : {4}", 0, yearStr, "Youth.霖", "597417651", "CC BY-NC-SA", Constants.ARTICLE_URL)
);
ButtonType contact = new ButtonType(__("Contact Author"));
ButtonType projectHome = new ButtonType(__("Project Home"));
alert.getButtonTypes().addAll(contact, projectHome);
alert.setTitle(__("About"));
alert.setGraphic(new ImageView(icon));
alert.setHeaderText(__("About this software"));
Platform.runLater(() -> {
Optional<ButtonType> result = alert.showAndWait();
if (result.isPresent()) {
if (contact == result.get()) {
Platform.runLater(() -> {
log.trace("点击[联系作者]按钮");
FxUtil.showWebPage(Constants.ARTICLE_URL);
});
}
if (projectHome == result.get()) {
log.trace("点击[项目主页]按钮");
FxUtil.showWebPage(Constants.PROJECT_HOME);
}
}
});
}
//region //记住密码与自动登录的关系
public void onRememberLabelClick(MouseEvent mouseEvent) {
//记住密码取消后不能自动登录
rememberCheckBox.setSelected(!rememberCheckBox.isSelected());
if (!rememberCheckBox.isSelected()) {
autoLoginCheckBox.setSelected(false);
}
}
public void onRememberAction(ActionEvent event) {
if (!rememberCheckBox.isSelected()) {
autoLoginCheckBox.setSelected(false);
}
}
public void onAutoAction(ActionEvent actionEvent) {
if (autoLoginCheckBox.isSelected()) {
rememberCheckBox.setSelected(true);
}
}
public void onAutoLabelClick(MouseEvent mouseEvent) {
//选了自动登录必须勾选记住密码
autoLoginCheckBox.setSelected(!autoLoginCheckBox.isSelected());
if (autoLoginCheckBox.isSelected()) {
rememberCheckBox.setSelected(true);
}
}
//endregion
public void onKeyReleased(KeyEvent event) {
KeyCode keyCode = event.getCode();
EventTarget target = event.getTarget();
//log.trace("event={},target={}", event, target);
if (target == usernameTextField && !fileMenu.isShowing() && !helpMenu.isShowing()) {
String text = usernameTextField.getText();
if (text != null && text.length() > 25) {
usernameTextField.setText(text.substring(0, 25));
}
if (KeyCode.ENTER.equals(keyCode) || KeyCode.DOWN.equals(keyCode)) {
passwordField.requestFocus();//用户名回车后定位到密码
}
} else if (target == passwordField && !fileMenu.isShowing() && !helpMenu.isShowing()) {
String text = passwordField.getText();
if (text != null && text.length() > 25) {
passwordField.setText(text.substring(0, 25));
}
if (KeyCode.ENTER.equals(keyCode)) {
onLoginButtonClick(new ActionEvent(event.getSource(), loginButton));//密码回车后登录
}
if (KeyCode.DOWN.equals(keyCode)) {
macComboBox.requestFocus();
}
if (KeyCode.UP.equals(keyCode)) {
usernameTextField.requestFocus();
}
}
if (event.isAltDown()) {
if (KeyCode.L.equals(keyCode)) {//登录注销快捷键 ALT+L
onLoginButtonClick(new ActionEvent(event.getSource(), loginButton));
} else if (KeyCode.X.equals(keyCode)) {//退出 ALT+X
onExitMenuItemClick(new ActionEvent(event.getSource(), logoutButton));
} else if (KeyCode.F.equals(keyCode)) {
//文件菜单
fileMenu.show();
} else if (KeyCode.H.equals(keyCode)) {
helpMenu.show();
}
}
if (event.isControlDown()) {
if (KeyCode.W.equals(keyCode)) {
Drcom.getStage().hide();
}
}
}
public void onNoticeMenuItemClick(ActionEvent e) {
FxUtil.showWebPage(Constants.NOTICE_URL, Constants.NOTICE_W, Constants.NOTICE_H);
}
}
| 23,567 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
DrcomTask.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/jlu-drcom-java/src/main/java/com/youthlin/jlu/drcom/task/DrcomTask.java | package com.youthlin.jlu.drcom.task;
import com.youthlin.jlu.drcom.Drcom;
import com.youthlin.jlu.drcom.bean.HostInfo;
import com.youthlin.jlu.drcom.bean.STATUS;
import com.youthlin.jlu.drcom.controller.AppController;
import com.youthlin.jlu.drcom.exception.DrcomException;
import com.youthlin.jlu.drcom.util.ByteUtil;
import com.youthlin.jlu.drcom.util.Constants;
import com.youthlin.jlu.drcom.util.FxUtil;
import com.youthlin.jlu.drcom.util.MD5;
import javafx.application.Platform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import static com.youthlin.utils.i18n.Translation.__;
/**
* Created by lin on 2017-01-11-011.
* challenge, login, keep_alive, logout
*/
public class DrcomTask implements Runnable {
private static final Logger log = LoggerFactory.getLogger(DrcomTask.class);
//region //Drcom 协议若干字段信息
/**
* 在 keep38 的回复报文中获得[28:30]
*/
private static final byte[] keepAliveVer = {(byte) 0xdc, 0x02};
/**
* 官方客户端在密码错误后重新登录时,challenge 包的这个数会递增,因此这里设为静态的
*/
private static int challengeTimes = 0;
/**
* 在 challenge 的回复报文中获得 [4:8]
*/
private final byte[] salt = new byte[4];
/**
* 在 challenge 的回复报文中获得 [20:24], 当是有线网时,就是网络中心分配的 IP 地址,当时无线网时,是局域网地址
*/
private final byte[] clientIp = new byte[4];
/**
* 在 login 的回复报文中获得[23:39]
*/
private final byte[] tail1 = new byte[16];
/**
* 在 login 报文计算,计算时需要用到 salt,password
*/
private final byte[] md5a = new byte[16];
/**
* 初始为 {0,0,0,0} , 在 keep40_1 的回复报文更新[16:20]
*/
private final byte[] tail2 = new byte[4];
/**
* 在 keep alive 中计数.
* 初始在 keep40_extra : 0x00, 之后每次 keep40 都加一
*/
private int count = 0;
private int keep38Count = 0;//仅用于日志计数
//endregion
private AppController appController;
private boolean notifyLogout = false;
private DatagramSocket client;
private InetAddress serverAddress;
private String username;
private String password;
private HostInfo hostInfo;
public DrcomTask(AppController appController) {
this.appController = appController;
this.username = appController.usernameTextField.getText();
this.password = appController.passwordField.getText();
this.hostInfo = appController.macComboBox.getSelectionModel().getSelectedItem();
}
@Override
public void run() {
boolean exception = false;
try {
init();
Thread.currentThread().setName("Challenge");
if (!challenge(challengeTimes++)) {
log.debug("challenge failed...");
/*TRANSLATORS: 0 Exception code*/
throw new DrcomException(__("Server refused the request.{0}", 0, DrcomException.CODE.ex_challenge));
}
Thread.currentThread().setName("L o g i n");
if (!login()) {
log.debug("login failed...");
/*TRANSLATORS: 0 Exception code*/
throw new DrcomException(__("Failed to send authentication information.{0}", 0, DrcomException.CODE.ex_login));
}
log.debug("登录成功!");
if (Drcom.getStage() != null) {
Platform.runLater(() -> Drcom.getStage().hide());//登录后隐藏窗口,弹出通知
}
FxUtil.showWebPage(Constants.NOTICE_URL, Constants.NOTICE_W, Constants.NOTICE_H);
Platform.runLater(() -> appController.setStatus(STATUS.logged));
//keep alive
Thread.currentThread().setName("KeepAlive");
count = 0;
while (!notifyLogout && alive()) {//收到注销通知则停止
Thread.sleep(20000);//每 20s 一次
}
} catch (SocketTimeoutException e) {
log.debug("通信超时", e);
exception = true;
FxUtil.showAlertWithException(new DrcomException(__("Waisting server response time out.\nIt may caused by Network state changed or your device slept too long.\nPlease try login again.\n"),
e, DrcomException.CODE.ex_timeout));
} catch (IOException e) {
log.debug("IO 异常", e);
exception = true;
FxUtil.showAlertWithException(new DrcomException(__("IO Exception, please check your network."), e, DrcomException.CODE.ex_io));
} catch (DrcomException e) {
log.debug("登录异常", e);
exception = true;
FxUtil.showAlertWithException(e);
} catch (InterruptedException e) {
log.debug("线程异常", e);
exception = true;
FxUtil.showAlertWithException(new DrcomException(__("Thread Exception, There is a error."), e, DrcomException.CODE.ex_thread));
} catch (Exception e) {
exception = true;
FxUtil.showAlertWithException(new DrcomException(__("Unknown error"), e));
} finally {
if (exception) {//若发生了异常:密码错误等。 则应允许重新登录
Platform.runLater(() -> {
appController.setStatus(STATUS.ready);
appController.statusLabel.setText(__("You are off line now."));
});
}
if (client != null) {
client.close();
client = null;
}
}
}
/**
* 初始化套接字、设置超时时间、设置服务器地址
*/
private void init() throws DrcomException {
try {
//每次使用同一个端口 若有多个客户端运行这里会抛出异常
client = new DatagramSocket(Constants.PORT);
client.setSoTimeout(Constants.TIMEOUT);
serverAddress = InetAddress.getByName(Constants.AUTH_SERVER);
} catch (SocketException e) {
throw new DrcomException(__("The port is occupied, do you have any other clients not exited?"), e, DrcomException.CODE.ex_init);
} catch (UnknownHostException e) {
throw new DrcomException(__("The server could not be found. (check DNS settings)"), DrcomException.CODE.ex_init);
}
}
/**
* 在回复报文中取得 salt 和 clientIp
*/
private boolean challenge(int tryTimes) throws DrcomException {
try {
byte[] buf = {0x01, (byte) (0x02 + tryTimes), ByteUtil.randByte(), ByteUtil.randByte(), 0x6a,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00};
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddress, Constants.PORT);
client.send(packet);
log.trace("send challenge data.【{}】", ByteUtil.toHexString(buf));
buf = new byte[76];
packet = new DatagramPacket(buf, buf.length);
client.receive(packet);
if (buf[0] == 0x02) {
log.trace("recv challenge data.【{}】", ByteUtil.toHexString(buf));
// 保存 salt 和 clientIP
System.arraycopy(buf, 4, salt, 0, 4);
System.arraycopy(buf, 20, clientIp, 0, 4);
return true;
}
log.debug("challenge fail, unrecognized response.【{}】", ByteUtil.toHexString(buf));
return false;
} catch (SocketTimeoutException e) {
throw new DrcomException(__("Challenge server failed, time out. {0}", 0, DrcomException.CODE.ex_challenge));
} catch (IOException e) {
throw new DrcomException(__("Failed to send authentication information. {0}", 0, DrcomException.CODE.ex_challenge));
}
}
private boolean login() throws IOException, DrcomException {
byte[] buf = makeLoginPacket();
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddress, Constants.PORT);
client.send(packet);
log.trace("send login packet.【{}】", ByteUtil.toHexString(buf));
byte[] recv = new byte[128];//45
client.receive(new DatagramPacket(recv, recv.length));
log.trace("recv login packet.【{}】", ByteUtil.toHexString(recv));
if (recv[0] != 0x04) {
if (recv[0] == 0x05) {
if (recv[4] == 0x0B) {
throw new DrcomException(__("Invalid Mac Address, please select the address registered in ip.jlu.edu.cn") + "MAC 地址错误, 请选择在网络中心注册的地址.", DrcomException.CODE.ex_login);
}
throw new DrcomException(__("Invalid username or password."), DrcomException.CODE.ex_login);
} else {
throw new DrcomException(__("Failed to login, unknown error."), DrcomException.CODE.ex_login);
}
}
// 保存 tail1. 构造 keep38 要用 md5a(在mkptk中保存) 和 tail1
// 注销也要用 tail1
System.arraycopy(recv, 23, tail1, 0, 16);
return true;
}
/**
* 需要用来自 challenge 回复报文中的 salt, 构造报文时会保存 md5a keep38 要用
*/
private byte[] makeLoginPacket() {
byte code = 0x03;
byte type = 0x01;
byte EOF = 0x00;
byte controlCheck = 0x20;
byte adapterNum = 0x05;
byte ipDog = 0x01;
byte[] primaryDNS = {10, 10, 10, 10};
byte[] dhcp = {0, 0, 0, 0};
byte[] md5b;
int passLen = password.length();
if (passLen > 16) {
passLen = 16;
}
int dataLen = 334 + (passLen - 1) / 4 * 4;
byte[] data = new byte[dataLen];
data[0] = code;
data[1] = type;
data[2] = EOF;
data[3] = (byte) (username.length() + 20);
System.arraycopy(MD5.md5(new byte[]{code, type}, salt, password.getBytes()),
0, md5a, 0, 16);//md5a保存起来
System.arraycopy(md5a, 0, data, 4, md5a.length);//md5a 4+16=20
byte[] user = ByteUtil.ljust(username.getBytes(), 36);
System.arraycopy(user, 0, data, 20, user.length);//username 20+36=56
data[56] = controlCheck;//0x20
data[57] = adapterNum;//0x05
//md5a[0:6] xor mac
System.arraycopy(md5a, 0, data, 58, 6);
byte[] macBytes = hostInfo.getMacBytes();
for (int i = 0; i < 6; i++) {
data[i + 58] ^= macBytes[i];//md5a oxr mac
}// xor 58+6=64
md5b = MD5.md5(new byte[]{0x01}, password.getBytes(), salt, new byte[]{0x00, 0x00, 0x00, 0x00});
System.arraycopy(md5b, 0, data, 64, md5b.length);//md5b 64+16=80
data[80] = 0x01;//number of ip
System.arraycopy(clientIp, 0, data, 81, clientIp.length);//ip1 81+4=85
System.arraycopy(new byte[]{
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
}, 0, data, 85, 12);//ip2/3/4 85+12=97
data[97] = 0x14;//临时放,97 ~ 97+8 是 md5c[0:8]
data[98] = 0x00;
data[99] = 0x07;
data[100] = 0x0b;
byte[] tmp = new byte[101];
System.arraycopy(data, 0, tmp, 0, tmp.length);//前 97 位 和 0x14_00_07_0b
byte[] md5c = MD5.md5(tmp);
System.arraycopy(md5c, 0, data, 97, 8);//md5c 97+8=105
data[105] = ipDog;//0x01
//0 106+4=110
byte[] hostname = ByteUtil.ljust(hostInfo.getHostname().getBytes(), 32);
System.arraycopy(hostname, 0, data, 110, hostname.length);//hostname 110+32=142
System.arraycopy(primaryDNS, 0, data, 142, 4);//primaryDNS 142+4=146
System.arraycopy(dhcp, 0, data, 146, 4);//dhcp 146+4=150
//second dns 150+4=154
//delimiter 154+8=162
data[162] = (byte) 0x94;//unknown 162+4=166
data[166] = 0x06; //os major 166+4=170
data[170] = 0x02; //os minor 170+4=174
data[174] = (byte) 0xf0;//os build
data[175] = 0x23; //os build 174+4=178
data[178] = 0x02; //os unknown 178+4=182
//DRCOM CHECK
data[182] = 0x44;//\x44\x72\x43\x4f\x4d\x00\xcf\x07
data[183] = 0x72;
data[184] = 0x43;
data[185] = 0x4f;
data[186] = 0x4d;
data[187] = 0x00;
data[188] = (byte) 0xcf;
data[189] = 0x07;
data[190] = 0x6a;
//0 191+55=246
System.arraycopy("1c210c99585fd22ad03d35c956911aeec1eb449b".getBytes(),
0, data, 246, 40);//246+40=286
//0 286+24=310
data[310] = 0x6a;//0x6a 0x00 0x00 310+3=313
data[313] = (byte) passLen;//password length
byte[] ror = ByteUtil.ror(md5a, password.getBytes());
System.arraycopy(ror, 0, data, 314, passLen);//314+passlen
data[314 + passLen] = 0x02;
data[315 + passLen] = 0x0c;
//checksum(data+'\x01\x26\x07\x11\x00\x00'+dump(mac))
//\x01\x26\x07\x11\x00\x00
data[316 + passLen] = 0x01;//临时放, 稍后被 checksum 覆盖
data[317 + passLen] = 0x26;
data[318 + passLen] = 0x07;
data[319 + passLen] = 0x11;
data[320 + passLen] = 0x00;
data[321 + passLen] = 0x00;
System.arraycopy(macBytes, 0, data, 322 + passLen, 4);
tmp = new byte[326 + passLen];//data+'\x01\x26\x07\x11\x00\x00'+dump(mac)
System.arraycopy(data, 0, tmp, 0, tmp.length);
tmp = ByteUtil.checksum(tmp);
System.arraycopy(tmp, 0, data, 316 + passLen, 4);//checksum 316+passlen+4=320+passLen
data[320 + passLen] = 0x00;
data[321 + passLen] = 0x00;//分割
System.arraycopy(macBytes, 0, data, 322 + passLen, macBytes.length);
//mac 322+passLen+6=328+passLen
// passLen % 4=mod 补0个数 4-mod (4-mod)%4
// 0 0 4
// 1 3 3
// 2 2 2
// 3 1 1
int zeroCount = (4 - passLen % 4) % 4;
for (int i = 0; i < zeroCount; i++) {
data[328 + passLen + i] = 0x00;
}
data[328 + passLen + zeroCount] = ByteUtil.randByte();
data[329 + passLen + zeroCount] = ByteUtil.randByte();
return data;
}
private boolean alive() throws IOException {
boolean needExtra = false;
log.trace("count = {}, keep38count = {}", count, ++keep38Count);
if (count % 21 == 0) {//第一个 keep38 后有 keep40_extra, 十个 keep38 后 count 就加了21
needExtra = true;
}//每10个keep38
//-------------- keep38 ----------------------------------------------------
byte[] packet38 = makeKeepPacket38();
DatagramPacket packet = new DatagramPacket(packet38, packet38.length, serverAddress, Constants.PORT);
client.send(packet);
log.trace("[rand={}|{}]send keep38. 【{}】",
ByteUtil.toHexString(packet38[36]), ByteUtil.toHexString(packet38[37]),
ByteUtil.toHexString(packet38));
byte[] recv = new byte[128];
client.receive(new DatagramPacket(recv, recv.length));
log.trace("[rand={}|{}]recv Keep38. [{}.{}.{}.{}] 【{}】",
ByteUtil.toHexString(recv[6]), ByteUtil.toHexString(recv[7]),
ByteUtil.toInt(recv[12]), ByteUtil.toInt(recv[13]), ByteUtil.toInt(recv[14]), ByteUtil.toInt(recv[15]),
ByteUtil.toHexString(recv));
keepAliveVer[0] = recv[28];//收到keepAliveVer//通常不会变
keepAliveVer[1] = recv[29];
if (needExtra) {//每十次keep38都要发一个 keep40_extra
log.debug("Keep40_extra...");
//--------------keep40_extra--------------------------------------------
//先发 keep40_extra 包
byte[] packet40extra = makeKeepPacket40(1, true);
packet = new DatagramPacket(packet40extra, packet40extra.length, serverAddress, Constants.PORT);
client.send(packet);
log.trace("[seq={}|type={}][rand={}|{}]send Keep40_extra. 【{}】", packet40extra[1], packet40extra[5],
ByteUtil.toHexString(packet40extra[8]), ByteUtil.toHexString(packet40extra[9]),
ByteUtil.toHexString(packet40extra));
recv = new byte[512];
client.receive(new DatagramPacket(recv, recv.length));
log.trace("[seq={}|type={}][rand={}|{}]recv Keep40_extra. 【{}】", recv[1], recv[5],
ByteUtil.toHexString(recv[8]), ByteUtil.toHexString(recv[9]), ByteUtil.toHexString(recv));
//不理会回复
}
//--------------keep40_1----------------------------------------------------
byte[] packet40_1 = makeKeepPacket40(1, false);
packet = new DatagramPacket(packet40_1, packet40_1.length, serverAddress, Constants.PORT);
client.send(packet);
log.trace("[seq={}|type={}][rand={}|{}]send Keep40_1. 【{}】", packet40_1[1], packet40_1[5],
ByteUtil.toHexString(packet40_1[8]), ByteUtil.toHexString(packet40_1[9]),
ByteUtil.toHexString(packet40_1));
recv = new byte[64];//40
client.receive(new DatagramPacket(recv, recv.length));
log.trace("[seq={}|type={}][rand={}|{}]recv Keep40_1. 【{}】", recv[1], recv[5],
ByteUtil.toHexString(recv[8]), ByteUtil.toHexString(recv[9]), ByteUtil.toHexString(recv));
//保存 tail2 , 待会儿构造 packet 要用
System.arraycopy(recv, 16, tail2, 0, 4);
//--------------keep40_2----------------------------------------------------
byte[] packet40_2 = makeKeepPacket40(2, false);
packet = new DatagramPacket(packet40_2, packet40_2.length, serverAddress, Constants.PORT);
client.send(packet);
log.trace("[seq={}|type={}][rand={}|{}]send Keep40_2. 【{}】", packet40_2[1], packet40_2[5],
ByteUtil.toHexString(packet40_2[8]), ByteUtil.toHexString(packet40_2[9]),
ByteUtil.toHexString(packet40_2));
client.receive(new DatagramPacket(recv, recv.length));
log.trace("[seq={}|type={}][rand={}|{}]recv Keep40_2. 【{}】", recv[1], recv[5],
ByteUtil.toHexString(recv[8]), ByteUtil.toHexString(recv[9]), ByteUtil.toHexString(recv));
//keep40_2 的回复也不用理会
return true;
}
/**
* 0xff md5a:16位 0x00 0x00 0x00 tail1:16位 rand rand
*/
private byte[] makeKeepPacket38() {
byte[] data = new byte[38];
data[0] = (byte) 0xff;
System.arraycopy(md5a, 0, data, 1, md5a.length);//1+16=17
//17 18 19
System.arraycopy(tail1, 0, data, 20, tail1.length);//20+16=36
data[36] = ByteUtil.randByte();
data[37] = ByteUtil.randByte();
return data;
}
/**
* keep40_额外的 就是刚登录时, keep38 后发的那个会收到 272 This Program can not run in dos mode
* keep40_1 每 秒发送
* keep40_2
*/
private byte[] makeKeepPacket40(int firstOrSecond, boolean extra) {
byte[] data = new byte[40];
data[0] = 0x07;
data[1] = (byte) count++;//到了 0xff 会回到 0x00
data[2] = 0x28;
data[3] = 0x00;
data[4] = 0x0b;
// keep40_1 keep40_2
// 发送 接收 发送 接收
// 0x01 0x02 0x03 0xx04
if (firstOrSecond == 1 || extra) {//keep40_1 keep40_extra 是 0x01
data[5] = 0x01;
} else {
data[5] = 0x03;
}
if (extra) {
data[6] = 0x0f;
data[7] = 0x27;
} else {
data[6] = keepAliveVer[0];
data[7] = keepAliveVer[1];
}
data[8] = ByteUtil.randByte();
data[9] = ByteUtil.randByte();
//[10-15]:0
System.arraycopy(tail2, 0, data, 16, 4);//16+4=20
//20 21 22 23 : 0
if (firstOrSecond == 2) {
System.arraycopy(clientIp, 0, data, 24, 4);
byte[] tmp = new byte[28];
System.arraycopy(data, 0, tmp, 0, tmp.length);
tmp = ByteUtil.crc(tmp);
System.arraycopy(tmp, 0, data, 24, 4);//crc 24+4=28
System.arraycopy(clientIp, 0, data, 28, 4);//28+4=32
//之后 8 个 0
}
return data;
}
public void notifyLogout() {
notifyLogout = true;//终止 keep 线程
//logout
log.debug("收到注销指令");
if (STATUS.logged.equals(appController.getStatus())) {//已登录才注销
boolean succ = true;
try {
challenge(challengeTimes++);
logout();
} catch (Throwable t) {
succ = false;
log.debug("注销异常", t);
FxUtil.showAlertWithException(new DrcomException(__("Exception when logout."), t));
} finally {
//不管怎样重新登录
Platform.runLater(() -> appController.setStatus(STATUS.ready));
if (succ) {
FxUtil.showAlert(__("Logout success."));
}
if (client != null) {
client.close();
client = null;
}
}
}
}
private boolean logout() throws IOException {
byte[] buf = makeLogoutPacket();
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddress, Constants.PORT);
client.send(packet);
log.trace("send logout packet.【{}】", ByteUtil.toHexString(buf));
byte[] recv = new byte[512];//25
client.receive(new DatagramPacket(recv, recv.length));
log.trace("recv logout packet response.【{}】", ByteUtil.toHexString(recv));
if (recv[0] == 0x04) {
log.debug("注销成功");
} else {
log.debug("注销...失败?");
}
return true;
}
private byte[] makeLogoutPacket() {
byte[] data = new byte[80];
data[0] = 0x06;//code
data[1] = 0x01;//type
data[2] = 0x00;//EOF
data[3] = (byte) (username.length() + 20);
byte[] md5 = MD5.md5(new byte[]{0x06, 0x01}, salt, password.getBytes());
System.arraycopy(md5, 0, data, 4, md5.length);//md5 4+16=20
System.arraycopy(ByteUtil.ljust(username.getBytes(), 36),
0, data, 20, 36);//username 20+36=56
data[56] = 0x20;
data[57] = 0x05;
byte[] macBytes = hostInfo.getMacBytes();
for (int i = 0; i < 6; i++) {
data[58 + i] = (byte) (data[4 + i] ^ macBytes[i]);
}// mac xor md5 58+6=64
System.arraycopy(tail1, 0, data, 64, tail1.length);//64+16=80
return data;
}
}
| 23,282 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
DrcomException.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/jlu-drcom-java/src/main/java/com/youthlin/jlu/drcom/exception/DrcomException.java | package com.youthlin.jlu.drcom.exception;
/**
* Created by lin on 2017-01-09-009.
* 异常
*/
public class DrcomException extends Exception {
public DrcomException(String msg) {
super('[' + CODE.ex_unknown.name() + "] " + msg);
}
public DrcomException(String msg, CODE code) {
super('[' + code.name() + "] " + msg);
}
public DrcomException(String msg, Throwable cause) {
super('[' + CODE.ex_unknown.name() + "] " + msg, cause);
}
public DrcomException(String msg, Throwable cause, CODE code) {
super('[' + code.name() + "] " + msg, cause);
}
public enum CODE {
ex_unknown, ex_init, ex_challenge, ex_login, ex_timeout, ex_io, ex_thread
}
}
| 728 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
MD5.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/jlu-drcom-java/src/main/java/com/youthlin/jlu/drcom/util/MD5.java | package com.youthlin.jlu.drcom.util;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by lin on 2017-01-10-010.
* MD5
*/
public class MD5 {
private static final byte[] zero16 = new byte[16];
public static byte[] md5(byte[]... bytes) {
int len = 0;
for (byte[] bs : bytes) {
len += bs.length;//数据总长度
}
byte[] data = new byte[len];
len = 0;//记录已拷贝索引
for (byte[] bs : bytes) {
System.arraycopy(bs, 0, data, len, bs.length);
len += bs.length;
}
return md5(data);
}
public static byte[] md5(byte[] bytes) {
try {
MessageDigest instance = MessageDigest.getInstance("MD5");
instance.update(bytes);
return instance.digest();
} catch (NoSuchAlgorithmException ignore) {
}
return zero16;//容错
}
/*//http://www.tuicool.com/articles/QJ7bYr
* 字符串 DESede(3DES) 加密
* ECB模式/使用PKCS7方式填充不足位,目前给的密钥是192位
* 3DES(即Triple DES)是DES向AES过渡的加密算法(1999年,NIST将3-DES指定为过渡的
* 加密标准),是DES的一个更安全的变形。它以DES为基本模块,通过组合分组方法设计出分组加
* 密算法,其具体实现如下:设Ek()和Dk()代表DES算法的加密和解密过程,K代表DES算法使用的
* 密钥,P代表明文,C代表密表,这样,
* 3DES加密过程为:C=Ek3(Dk2(Ek1(P)))
* 3DES解密过程为:P=Dk1((EK2(Dk3(C)))
* <p>
* args在java中调用sun公司提供的3DES加密解密算法时,需要使
* 用到$JAVA_HOME/jre/lib/目录下如下的4个jar包:
* jce.jar
* security/US_export_policy.jar
* security/local_policy.jar
* ext/sunjce_provider.jar
*/
private static final String Algorithm = "DESede"; //定义加密算法,可用 DES,DESede,Blowfish
private static final byte[] none = new byte[]{};
public static final int DES_KEY_LEN = 24;
private static byte[] des(int mode, byte[] key, byte[] data) {
try {
SecretKey deskey = new SecretKeySpec(key, Algorithm);//生成密钥
Cipher c1 = Cipher.getInstance(Algorithm);//加密或解密
c1.init(mode, deskey);
return c1.doFinal(data);//在单一方面的加密或解密
} catch (NoSuchAlgorithmException | javax.crypto.NoSuchPaddingException ignore) {
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return none;
}
public static byte[] encrypt3DES(byte[] keybyte, byte[] src) {
return des(Cipher.ENCRYPT_MODE, keybyte, src);
}
public static byte[] decrypt3DES(byte[] keybyte, byte[] secret) {
return des(Cipher.DECRYPT_MODE, keybyte, secret);
}
public static void main(String[] args) {
byte[] enk = ByteUtil.ljust("1".getBytes(), DES_KEY_LEN);//用于加密的密码,必须 24 长度
String password = "a";//要加密的字符串
System.out.println("加密前的字符串:" + password + " | " + ByteUtil.toHexString(password.getBytes()));
byte[] encoded = encrypt3DES(enk, password.getBytes());
System.out.println("加密后:" + ByteUtil.toHexString(encoded));
byte[] srcBytes = decrypt3DES(enk, ByteUtil.fromHex(ByteUtil.toHexString(encoded), ' '));
System.out.println("解密后的字符串:" + new String(srcBytes) + " | " + ByteUtil.toHexString(srcBytes));
}/*
* 加密前的字符串:123456 | 31 32 33 34 35 36
* 加密后的字符串:Nj�Y�_l� | C7 8B C1 59 94 5F 6C AE
* 解密后的字符串:123456 | 31 32 33 34 35 36
*/
}
| 3,906 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
FxUtil.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/jlu-drcom-java/src/main/java/com/youthlin/jlu/drcom/util/FxUtil.java | package com.youthlin.jlu.drcom.util;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.image.Image;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
import java.io.PrintWriter;
import java.io.StringWriter;
import static com.youthlin.utils.i18n.Translation.__;
/**
* Created by lin on 2017-01-11-011.
* Fx 工具类
*/
@SuppressWarnings("WeakerAccess")
public class FxUtil {
public static final Image icon = new Image(Constants.LOGO_URL);
public static final Image loading = new Image(Constants.LOADING_URL);
public static void showAlertWithException(Exception e) {
Platform.runLater(() -> showAlert(buildAlert(e)));
}
public static void showAlert(String info) {
Platform.runLater(() -> showAlert(buildAlert(info)));
}
public static void showAlert(Alert alert) {
Platform.runLater(alert::show);
}
/**
* buildAlert 需要在 Fx 线程中调用
*/
public static Alert buildAlert(Exception ex) {
// http://code.makery.ch/blog/javafx-dialogs-official/
Alert alert = new Alert(Alert.AlertType.ERROR, ex.getMessage());
((Stage) alert.getDialogPane().getScene().getWindow()).getIcons().add(icon);
alert.setHeaderText(__("Error"));
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String exceptionText = sw.toString();
Label label = new Label(__("The exception stacktrace was:"));
TextArea textArea = new TextArea(exceptionText);
textArea.setEditable(false);
textArea.setWrapText(true);
GridPane.setVgrow(textArea, Priority.ALWAYS);
GridPane.setHgrow(textArea, Priority.ALWAYS);
GridPane expContent = new GridPane();
expContent.add(label, 0, 0);
expContent.add(textArea, 0, 1);
alert.getDialogPane().setExpandableContent(expContent);
alert.getDialogPane().expandedProperty().addListener((invalidationListener) -> Platform.runLater(() -> {
alert.getDialogPane().requestLayout();
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.sizeToScene();
}));
return alert;
}
/**
* buildAlert 需要在 Fx 线程中调用
*/
public static Alert buildAlert(String info) {
Alert alert = new Alert(Alert.AlertType.INFORMATION, info);
((Stage) alert.getDialogPane().getScene().getWindow()).getIcons().add(icon);
alert.setHeaderText(__("Note"));
return alert;
}
public static void showWebPage(String url) {
showWebPage(url, Browser.prefWidth, Browser.prefHeight);
}
public static void showWebPage(String url, double prefWidth, double prefHeight) {
Platform.runLater(() -> new Browser(url, prefWidth, prefHeight).show());
}
public static void updateLabel(Label label, String newText) {
Platform.runLater(() -> label.setText(newText));
}
}
| 3,156 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
ByteUtil.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/jlu-drcom-java/src/main/java/com/youthlin/jlu/drcom/util/ByteUtil.java | package com.youthlin.jlu.drcom.util;
import java.math.BigInteger;
import java.util.Random;
/**
* Created by lin on 2017-01-11-011.
* 字节数组工具, byte 数字当作无符号数处理. 因此 toInt(0xff) 将得到 255.
*/
@SuppressWarnings("WeakerAccess")
public class ByteUtil {
private static final Random random = new Random(System.currentTimeMillis());
public static byte randByte() {
return (byte) random.nextInt();
}
public static int toInt(byte b) {
return b & 0xff;//0xff -> 255
}
/*得到两位长度的 16 进制表示*/
public static String toHexString(byte b) {
String tmp = Integer.toHexString(toInt(b));
if (tmp.length() == 1) {
tmp = '0' + tmp;
}
return tmp;
}
/*使用空格分割的十六进制表示字符串*/
public static String toHexString(byte[] bytes) {
return toHexString(bytes, ' ');
}
/*使用 split 字符分割的十六进制表示字符串*/
public static String toHexString(byte[] bytes, char split) {
if (bytes == null || bytes.length == 0) {
return "";
}
int len = bytes.length;
StringBuilder sb = new StringBuilder(len * 3);//两位数字+split
for (byte b : bytes) {
sb.append(toHexString(b)).append(split);
}
return sb.toString().substring(0, len * 3 - 1).toUpperCase();
}
public static byte[] fromHex(String hexStr) {
return fromHex(hexStr, ' ');
}
public static byte[] fromHex(String hexStr, char split) {
// hexStr = 00 01 AB str len = 8 length = (8+1)/3=3
int length = (hexStr.length() + 1) / 3;
byte[] ret = new byte[length];
for (int i = 0; i < length; i++) {
ret[i] = (byte) Integer.parseInt(hexStr.substring(i * 3, i * 3 + 2), 16);
}
return ret;
}
public static byte[] ljust(byte[] src, int count) {
return ljust(src, count, (byte) 0x00);
}
public static byte[] ljust(byte[] src, int count, byte fill) {
int srcLen = src.length;
byte[] ret = new byte[count];
if (srcLen >= count) {//只返回前 count 位
System.arraycopy(src, 0, ret, 0, count);
return ret;
}
System.arraycopy(src, 0, ret, 0, srcLen);
for (int i = srcLen; i < count; i++) {
ret[i] = fill;
}
return ret;
}
public static byte[] ror(byte[] md5a, byte[] password) {
int len = password.length;
byte[] ret = new byte[len];
int x;
for (int i = 0; i < len; i++) {
x = toInt(md5a[i]) ^ toInt(password[i]);
//e.g. x = 0xff 1111_1111
// x<<3 = 0x07f8 0111_1111_1000
// x>>>5 = 0x0007 0111
// + 0x07ff 0111_1111_1111
//(byte)截断=0xff
ret[i] = (byte) ((x << 3) + (x >>> 5));
}
return ret;
}
/**
* 每四个数倒过来后与sum相与, 最后*1968取后4个数.
* <p>
* Python版用<code>'....'</code>匹配四个字节,但是这个正则会忽略换行符 0x0a, 因此计算出来的是错误的.
* 但是python版代码是可用的,因此应该是服务器没有检验
* (Python 版协议与本工程有些许不一样, 所以这里需要返回正确的校验码)
* <pre>
* import struct
* import re
* def checksum(s):
* ret = 1234
* for i in re.findall('....', s):
* tmp = int(i[::-1].encode('hex'), 16)
* print(i, i[::-1], ret, tmp, ret ^ tmp)
* ret ^= tmp
* ret = (1968 * ret) & 0xffffffff
* return struct.pack('<I', ret)
* </pre>
**/
public static byte[] checksum(byte[] data) {
// 1234 = 0x_00_00_04_d2
byte[] sum = new byte[]{0x00, 0x00, 0x04, (byte) 0xd2};
int len = data.length;
int i = 0;
//0123_4567_8901_23
for (; i + 3 < len; i = i + 4) {
//abcd ^ 3210
//abcd ^ 7654
//abcd ^ 1098
sum[0] ^= data[i + 3];
sum[1] ^= data[i + 2];
sum[2] ^= data[i + 1];
sum[3] ^= data[i];
}
if (i < len) {
//剩下_23
//i=12,len=14
byte[] tmp = new byte[4];
for (int j = 3; j >= 0 && i < len; j--) {
//j=3 tmp = 0 0 0 2 i=12 13
//j=2 tmp = 0 0 3 2 i=13 14
tmp[j] = data[i++];
}
for (int j = 0; j < 4; j++) {
sum[j] ^= tmp[j];
}
}
BigInteger bigInteger = new BigInteger(1, sum);//无符号数即正数
bigInteger = bigInteger.multiply(BigInteger.valueOf(1968));
bigInteger = bigInteger.and(BigInteger.valueOf(0xff_ff_ff_ffL));
byte[] bytes = bigInteger.toByteArray();
//System.out.println(ByteUtil.toHexString(bytes));
len = bytes.length;
i = 0;
byte[] ret = new byte[4];
for (int j = len - 1; j >= 0 && i < 4; j--) {
ret[i++] = bytes[j];
}
return ret;
}
//参考了 Python 版
public static byte[] crc(byte[] data) {
byte[] sum = new byte[2];
int len = data.length;
for (int i = 0; i + 1 < len; i = i + 2) {
sum[0] ^= data[i + 1];
sum[1] ^= data[i];
}//现在数据都是偶数位
BigInteger b = new BigInteger(1, sum);
b = b.multiply(BigInteger.valueOf(711));
byte[] bytes = b.toByteArray();
len = bytes.length;
//System.out.println(toHexString(bytes));
byte[] ret = new byte[4];
for (int i = 0; i < 4 && len > 0; i++) {
ret[i] = bytes[--len];
}
return ret;
}
}
| 5,861 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
IPUtil.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/jlu-drcom-java/src/main/java/com/youthlin/jlu/drcom/util/IPUtil.java | package com.youthlin.jlu.drcom.util;
import com.youthlin.jlu.drcom.bean.HostInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* Created by lin on 2017-01-09-009.
* 工具类
*/
@SuppressWarnings("WeakerAccess")
public class IPUtil {
private static final Logger log = LoggerFactory.getLogger(IPUtil.class);
public static <T> List<T> asList(Enumeration<T> enumeration) {
List<T> ret = new ArrayList<>();
while (enumeration.hasMoreElements()) {
ret.add(enumeration.nextElement());
}
return ret;
}
public interface OnGetHostInfoCallback {
void update(int current, int total);
void done(List<HostInfo> hostInfoList);
}
public static List<HostInfo> getHostInfo(OnGetHostInfoCallback callback) {
List<HostInfo> hostInfoList = new ArrayList<>();
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
if (networkInterfaces == null) {
return hostInfoList;//空结果 -> 补救:使用配置文件手动指定
}
List<NetworkInterface> networkInterfacesList = asList(networkInterfaces);
int size = networkInterfacesList.size();
int index = 0;
for (NetworkInterface networkInterface : networkInterfacesList) {
index++;
callback.update(index, size);
if (!networkInterface.isUp()) {
continue;
}
String addr = null;
String hostname = null;
List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
for (InterfaceAddress interfaceAddress : interfaceAddresses) {
InetAddress address = interfaceAddress.getAddress();
//log.trace("{}/{}. address = {}", index, size, address);
String hostAddress = address.getHostAddress();//to耗时do
if (hostAddress.contains(".")) {// not ':' -> IPv6
addr = hostAddress;
hostname = address.getHostName();
break;
}
}
byte[] hardwareAddress = networkInterface.getHardwareAddress();//to耗时do
String dashMAC = getDashMAC(hardwareAddress);
//log.trace("Dash Mac = {}", dashMAC);
if (dashMAC != null && dashMAC.length() == 17 && addr != null && hostname != null) { // 00-00-00-00-00-00
HostInfo hostInfo = new HostInfo(hostname, dashMAC, networkInterface.getDisplayName());
hostInfo.setAddress4(addr);
hostInfoList.add(hostInfo);
}
}
} catch (SocketException e) {
log.debug("Socket Exception: {}", e.getMessage(), e);
}
callback.done(hostInfoList);
return hostInfoList;
}
public static String getDashMAC(byte[] hardwareAddress) {
if (hardwareAddress == null) {
//throw new NullPointerException("Hardware address should not be null.");
return null;
}
return ByteUtil.toHexString(hardwareAddress, '-');
}
public static boolean isPublicIP(String dotIP) {
try {
String[] split = dotIP.trim().split("\\.");
int a = Integer.parseInt(split[0]);
int b = Integer.parseInt(split[1]);
//int c = Integer.parseInt(split[2]);
//int d = Integer.parseInt(split[3]);
//A 类:1.0.0.0 到 127.255.255.255 //A 类:10.0.0.0 到 10.255.255.255
// 127.0.0.0 到 127.255.255.255 为系统回环地址
if (a > 0 && a < 128) {
if (!(a == 10 || a == 127)) {
return true;
}
}
//B 类:128.0.0.0 到 191.255.255.255 //B 类:172.16.0.0 到 172.31.255.255
else if (a >= 128 && a < 192) {
// 169.254.X.X 是保留地址。
// 如果你的 IP 地址是自动获取 IP 地址,
// 而你在网络上又没有找到可用的 DHCP 服务器。就会得到其中一个 IP。
// UPDATE at 2017-01-23: http://baike.baidu.com/subview/8370/15816170.htm#5
if (!(a == 172 && (b >= 16 && b < 31)) && !(a == 169 && b == 254)) {
return true;
}
}
//C 类:192.0.0.0 到 223.255.255.255 //C 类:192.168.0.0 到 192.168.255.255
else if (a >= 192 && a < 224) {
if (!(a == 192 && b == 168)) {
return true;
}
}
//D 类:224.0.0.0 到 239.255.255.255
//E 类:240.0.0.0 到 255.255.255.255
} catch (Exception e) {
log.debug("判断是否为公网 IP 时发生异常: " + dotIP);
return false;
}
return false;
}
}
| 5,308 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
Constants.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/jlu-drcom-java/src/main/java/com/youthlin/jlu/drcom/util/Constants.java | package com.youthlin.jlu.drcom.util;
import java.io.File;
/**
* Created by lin on 2017-01-09-009.
* 常量
*/
@SuppressWarnings("WeakerAccess")
public class Constants {
public static final String LOGO_URL = "/dr-logo.png";
public static final String LOADING_URL = "/loading.gif";
public static final String AUTH_SERVER = "auth.jlu.edu.cn";//10.100.61.3
public static final String COPYRIGHT_YEAR_START = "2017";
public static final int PORT = 61440;
public static final int TIMEOUT = 10000;//10s
public static final String ARTICLE_URL = "http://youthlin.com/?p=1391";
public static final String PROJECT_HOME = "https://github.com/YouthLin/jlu-drcom-client/tree/master/jlu-drcom-java";
public static final String NOTICE_URL = "http://login.jlu.edu.cn/notice.php";
public static final double NOTICE_W = 592;
public static final double NOTICE_H = 450;
public static final String DATA_HOME = System.getProperty("user.home", ".") + File.separator + ".drcom";
public static final String CONF_HOME = DATA_HOME + File.separator + "conf";
public static final String LOCK_FILE_NAME = "drcom.java.lock";
public static final String CONF_FILE_NAME = "drcom.java.conf";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_DASH_MAC = "dash_mac";
public static final String KEY_HOSTNAME = "hostname";
public static final String KEY_REMEMBER = "remember";
public static final String KEY_AUTO_LOGIN = "auto_login";
public static final String KEY_VERSION = "version";
public static final int VER_1 = 1;//添加 3DES 加密: conf, lock 文件
}
| 1,716 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
Browser.java | /FileExtraction/Java_unseen/drcoms_jlu-drcom-client/jlu-drcom-java/src/main/java/com/youthlin/jlu/drcom/util/Browser.java | package com.youthlin.jlu.drcom.util;
import com.youthlin.jlu.drcom.Drcom;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
/**
* Created by lin on 2017-01-14-014.
* 简易浏览器
* new/show 需要在 JavaFx 线程中
*/
@SuppressWarnings("WeakerAccess")
public class Browser {
public static final double prefWidth = 800;
public static final double prefHeight = 600;
private final TextField urlBar = new TextField();
private final WebView webView = new WebView();
private final BorderPane pane = new BorderPane(webView, urlBar, null, null, null);
private final Stage stage = new Stage();
public Browser(String url, Double width, Double height) {
urlBar.setText(url);
stage.setTitle(Drcom.TITLE);
WebEngine engine = webView.getEngine();
engine.load(url);
//http://blog.csdn.net/oppo117/article/details/17354453
engine.locationProperty().addListener((observable, oldValue, newValue) -> urlBar.setText(newValue));
engine.titleProperty().addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
stage.setTitle(newValue + " - " + Drcom.TITLE);
}
});
stage.getIcons().add(FxUtil.icon);
webView.setPrefWidth(width == null ? prefWidth : width);
webView.setPrefHeight(height == null ? prefHeight : height);
stage.setScene(new Scene(pane));
stage.sizeToScene();
urlBar.setOnKeyReleased(event -> {
if (event.getCode().equals(KeyCode.ENTER)) {//彩蛋: URL输入栏回车则加载新网址
String newUrl = urlBar.getText().trim();
if (!newUrl.startsWith("http") && !newUrl.startsWith("file:")) {
newUrl = "http://" + newUrl;
}
engine.load(newUrl);
webView.requestFocus();
}
});
webView.setOnKeyReleased(event -> {
if (event.isControlDown() && KeyCode.L.equals(event.getCode())) {
urlBar.requestFocus();//仿浏览器 CTRL+L 定位到地址栏
}
});
pane.setOnKeyReleased(event -> {
KeyCode code = event.getCode();
if (event.isControlDown()) {
if ((KeyCode.W.equals(code)) || KeyCode.Q.equals(code)) {
stage.hide();//CTRL+W 或 CTRL+Q 关闭
} else if (KeyCode.R.equals(code) || KeyCode.F5.equals(code)) {
reload();//CTRL+R CTRL+F5 重新加载
}
}
if (event.isAltDown()) {
if (KeyCode.LEFT.equals(code)) {
back();//ALT+LEFT
} else if (KeyCode.RIGHT.equals(code)) {
forward();//ALT+RIGHT
}
}
});
}
public void show() {
stage.show();
}
public TextField getUrlBar() {
return urlBar;
}
public WebView getWebView() {
return webView;
}
public BorderPane getPane() {
return pane;
}
public Stage getStage() {
return stage;
}
public void reload() {
webView.getEngine().reload();
}
public void back() {
webView.getEngine().executeScript("history.back()");
}
public void forward() {
webView.getEngine().executeScript("history.forward()");
}
}
| 3,594 | Java | .java | drcoms/jlu-drcom-client | 142 | 1 | 9 | 2014-10-20T16:26:48Z | 2020-09-01T13:48:47Z |
FunctionUnitTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/test/java/org/flyve/inventory/FunctionUnitTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import org.flyve.inventory.categories.StringUtils;
import org.junit.Test;
import java.util.ArrayList;
import static org.junit.Assert.assertTrue;
public class FunctionUnitTest {
@Test
public void createIP_correct() throws Exception {
int ip = 19216801;
String formatIp = StringUtils.intToIp(ip);
assertTrue(formatIp.split("\\.").length==4);
}
@Test
public void intToByte_correct() throws Exception {
int byteNumber = 19216801;
try {
byte[] byteFormat = StringUtils.intToByte(byteNumber);
assertTrue(true);
} catch (Exception ex) {
assertTrue(false);
}
}
@Test
public void join_correct() throws Exception {
ArrayList<String> arr = new ArrayList<String>();
for (int i =2; i <= 12; i++) {
arr.add(String.valueOf(i*12345));
}
assertTrue(StringUtils.join(arr, "#").split("#").length==11);
}
} | 2,153 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
CryptoUtil.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/CryptoUtil.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.util.Base64;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class CryptoUtil {
private final static String CRYPTO_METHOD = "RSA";
private final static int CRYPTO_BITS = 2048;
public static Map<String, String> generateKeyPair()
throws NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeyException,
IllegalBlockSizeException,
BadPaddingException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(CRYPTO_METHOD);
kpg.initialize(CRYPTO_BITS);
KeyPair kp = kpg.genKeyPair();
PublicKey publicKey = kp.getPublic();
PrivateKey privateKey = kp.getPrivate();
Map<String, String> map = new HashMap<>();
map.put("privateKey", Base64.encodeToString(privateKey.getEncoded(), Base64.DEFAULT));
map.put("publicKey", Base64.encodeToString(publicKey.getEncoded(), Base64.DEFAULT));
return map;
}
public static String encrypt(String plain, String pubk)
throws NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeyException,
IllegalBlockSizeException,
BadPaddingException,
InvalidKeySpecException {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, stringToPublicKey(pubk));
byte[] encryptedBytes = cipher.doFinal(plain.getBytes(StandardCharsets.UTF_8));
return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
}
public static String decrypt(String result, String privk)
throws NoSuchPaddingException,
NoSuchAlgorithmException,
BadPaddingException,
IllegalBlockSizeException,
InvalidKeySpecException,
InvalidKeyException {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, stringToPrivateKey(privk));
byte[] decryptedBytes = cipher.doFinal(Base64.decode(result, Base64.DEFAULT));
return new String(decryptedBytes);
}
private static PublicKey stringToPublicKey(String publicKeyString)
throws InvalidKeySpecException,
NoSuchAlgorithmException {
byte[] keyBytes = Base64.decode(publicKeyString, Base64.DEFAULT);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(CRYPTO_METHOD);
return keyFactory.generatePublic(spec);
}
private static PrivateKey stringToPrivateKey(String privateKeyString)
throws InvalidKeySpecException,
NoSuchAlgorithmException {
byte [] pkcs8EncodedBytes = Base64.decode(privateKeyString, Base64.DEFAULT);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
KeyFactory kf = KeyFactory.getInstance(CRYPTO_METHOD);
return kf.generatePrivate(keySpec);
}
}
| 4,811 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
InventoryTask.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/InventoryTask.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.core.content.FileProvider;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import org.flyve.inventory.categories.Categories;
import java.io.File;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
/**
* This class generate the XML file
*/
public class InventoryTask {
/**
* Set if show FlyveLog in console
*/
public static boolean showFILog = false;
private static Handler uiHandler;
private Boolean running = false;
static {
uiHandler = new Handler(Looper.getMainLooper());
}
private static void runOnUI(Runnable runnable) {
uiHandler.post(runnable);
}
private Context ctx = null;
private String[] categories;
private String appVersion = "";
private String fileNameXML = "Inventory.xml";
private String fileNameJSON = "Inventory.json";
private Boolean storeResult = false;
private String TAG = "";
private String ITEMTYPE = "Computer";
private boolean privateData = false;
public Boolean isRunning() {
return running;
}
/**
* This constructor return a Success XML or Error on asynchronous way
* @param context The context to be use
* @param appVersion The name of the agent
* @param storeResult Boolean
*/
public InventoryTask(Context context, String appVersion, Boolean storeResult) {
this(storeResult);
startInventory(context, appVersion);
}
/**
* This constructor return a Success XML or Error on asynchronous way
* @param context The context to be use
* @param appVersion The name of the agent
* @param storeResult Boolean
* @param categories String[]
*/
public InventoryTask(Context context, String appVersion, Boolean storeResult, String[] categories) {
this(storeResult);
this.categories = categories;
startInventory(context, appVersion);
}
/**
* This constructor return a Success XML or Error on asynchronous way
* @param storeResult Indicate is the result will be stored on file
*/
private InventoryTask(Boolean storeResult) {
this.storeResult = storeResult;
}
private void startInventory(Context context, String appVersion) {
this.appVersion = appVersion;
this.ctx = context;
try {
if (showFILog) {
FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder().build();
Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));
}
} catch (Exception ex) {
ex.getStackTrace();
}
}
/**
* This function load all the categories class dynamically
* @return ArrayList<Categories>
*/
@SuppressWarnings("unchecked")
private ArrayList<Categories> loadCategoriesClass() throws FlyveException {
ArrayList<Categories> mContent = new ArrayList<Categories>();
String[] categories = this.categories == null ? getCategories() : this.categories;
Class<Categories> catClass;
for(String c : categories) {
InventoryLog.v(String.format("new INVENTORY of %s", c));
// Loading the class with name of the ArrayList
try {
Class cCat = Class.forName(String.format("org.flyve.inventory.categories.%s", c));
catClass = (Class<Categories>)cCat;
}
catch (Exception ex) {
InventoryLog.e( ex.getCause().toString() );
throw new FlyveException(ex.getMessage(), ex.getCause());
}
// Instance the class and checking errors
if(catClass!=null) {
try {
Constructor<Categories> co = catClass.getConstructor(Context.class);
mContent.add(co.newInstance(ctx));
} catch ( Exception ex ) {
InventoryLog.e( ex.getCause().toString() );
throw new FlyveException(ex.getMessage(), ex.getCause());
}
}
}
return mContent;
}
public String[] getCategories() {
return new String[]{
"Hardware",
"User",
"Storage",
"OperatingSystem",
"Bios",
"Memory",
"Inputs",
"Sensors",
"Drives",
"Cpus",
"Simcards",
"Videos",
"Cameras",
"Networks",
"Envs",
"Jvm",
"Software",
"Usb",
"Battery",
"Controllers",
"Modems"
};
}
public void setTag(String tag) {
TAG = tag;
}
public String getTag() {
return TAG;
}
public void setAssetItemtype(String asset_itemtype) {
ITEMTYPE = asset_itemtype;
}
public String getAssetItemtype() {
return ITEMTYPE;
}
public void setPrivateData(boolean enable) {
privateData = enable;
}
public boolean getPrivateData() {
return privateData;
}
/**
* Return a XML String or Error OnTaskCompleted interface
* @param listener the interface OnTaskCompleted
*/
public void getXML(final OnTaskCompleted listener) {
running = true;
Thread t = new Thread(new Runnable()
{
public void run() {
try {
ArrayList<Categories> mContent = loadCategoriesClass();
String xml = Utils.createXML(ctx, mContent, InventoryTask.this.appVersion, getPrivateData(), getTag(), getAssetItemtype());
xml = xml.replaceAll("<", "<");
xml = xml.replaceAll(">", ">");
xml = xml.replaceAll("&", "");
if(storeResult) {
Utils.storeFile(ctx.getApplicationContext(), xml, fileNameXML);
}
final String finalXml = xml;
InventoryTask.runOnUI(new Runnable() {
public void run() {
running = false;
listener.onTaskSuccess(finalXml);
}
});
} catch (final Exception ex) {
InventoryTask.runOnUI(new Runnable() {
public void run() {
running = false;
if (ex.getCause() != null) {
listener.onTaskError(ex.getCause());
}
}
});
}
}
});
t.start();
}
/**
* Return a JSON String or Error OnTaskCompleted interface
* @param listener the interface OnTaskCompleted
*/
public void getJSON(final OnTaskCompleted listener) {
running = true;
Thread t = new Thread(new Runnable()
{
public void run() {
try {
ArrayList<Categories> mContent = loadCategoriesClass();
final String json = Utils.createJSON(ctx, mContent, InventoryTask.this.appVersion, getPrivateData(), getTag(), getAssetItemtype());
if(storeResult) {
Utils.storeFile(ctx.getApplicationContext(), json, fileNameJSON);
}
InventoryTask.runOnUI(new Runnable() {
public void run() {
running = false;
listener.onTaskSuccess( json );
}
});
} catch (final Exception ex) {
InventoryTask.runOnUI(new Runnable() {
public void run() {
running = false;
if (ex.getCause() != null) {
listener.onTaskError(ex.getCause());
}
}
});
}
}
});
t.start();
}
/**
* @return json String
*/
public String getJSONSync() {
try {
ArrayList<Categories> mContent = loadCategoriesClass();
String json = Utils.createJSON(ctx, mContent, InventoryTask.this.appVersion, getPrivateData(), getTag(), getAssetItemtype());
if(storeResult) {
Utils.storeFile(ctx.getApplicationContext(), json, fileNameJSON);
}
return json;
} catch (final Exception ex) {
Log.e("Library Exception", ex.getLocalizedMessage());
return null;
}
}
/**
* @return xml String
*/
public String getXMLSyn() {
try {
ArrayList<Categories> mContent = loadCategoriesClass();
String xml = Utils.createXML(ctx, mContent, InventoryTask.this.appVersion, getPrivateData(), getTag(), getAssetItemtype());
if(storeResult) {
Utils.storeFile(ctx.getApplicationContext(), xml, fileNameXML);
}
return xml;
} catch (final Exception ex) {
Log.e("Library Exception", ex.getLocalizedMessage());
return null;
}
}
public void shareInventory(int type){
if(type==1) {
File file = new File(ctx.getFilesDir() , "Inventory.json");
final Uri data = FileProvider.getUriForFile(this.ctx, ctx.getApplicationContext().getPackageName() + ".provider", file);
this.ctx.grantUriPermission(this.ctx.getPackageName(), data, Intent.FLAG_GRANT_READ_URI_PERMISSION);
final Intent intent = new Intent(Intent.ACTION_SEND)
.setType("application/json")
.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION)
.putExtra(Intent.EXTRA_STREAM, data)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
this.ctx.startActivity(intent);
} else {
File file = new File(ctx.getFilesDir() , "Inventory.xml");
final Uri data = FileProvider.getUriForFile(this.ctx, ctx.getApplicationContext().getPackageName() + ".provider", file);
this.ctx.grantUriPermission(this.ctx.getPackageName(), data, Intent.FLAG_GRANT_READ_URI_PERMISSION);
final Intent intent = new Intent(Intent.ACTION_SEND)
.setType("application/xml")
.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION)
.putExtra(Intent.EXTRA_STREAM, data)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
this.ctx.startActivity(intent);
}
}
/**
* This is the interface of return data
*/
public interface OnTaskCompleted {
/**
* if everything is Ok
* @param data String
*/
void onTaskSuccess(String data);
/**
* if something wrong
* @param error String
*/
void onTaskError(Throwable error);
}
}
| 12,941 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
InventoryLog.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/InventoryLog.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import com.orhanobut.logger.Logger;
/**
* This is a Utils class grapper for Log
*/
public final class InventoryLog {
// This is the tag to search on console
static final String TAG = "InventoryLibrary";
/**
* private constructor to prevent instances of this class
*/
private InventoryLog() {
}
/**
* Sends a DEBUG log message
* @param message to log
*/
public static void d(String message) {
if(message != null) {
Log.d(TAG, message);
}
}
/**
* Sends a VERBOSE log message
* @param message to log
*/
public static void v(String message) {
if(message != null) {
Log.v(TAG, message);
}
}
/**
* Sends an INFO log message
* @param message to log
*/
public static void i(String message) {
if(message != null) {
Log.i(TAG, message);
}
}
/**
* Sends an ERROR log message
* @param message to log
*/
public static void e(String message) {
if(message != null) {
Log.e(TAG, message);
}
}
/**
* Sends a low level calling log
* @param obj the name of the class
* @param msg the log message
* @param level the priority/type of the log message
*/
public static void log(Object obj, String msg, int level) {
String final_msg = String.format("[%s] %s", obj.getClass().getName(), msg);
Log.println(level, "InventoryAgent", final_msg);
}
public static String getMessage(Context context, int type, String message) {
Resources resource = context.getResources();
return resource.getString(R.string.error_message_with_number, String.valueOf(type), message);
}
public static String getMessage(String type, String message) {
String resource = Resources.getSystem().getString(R.string.error_message_with_number);
return String.format(resource, type, message);
}
} | 3,282 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
FlyveException.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/FlyveException.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
public class FlyveException extends Exception
{
/**
* Constructor of the class FlyveException
* Call the superclass constructor
*/
public FlyveException() {
super();
}
/**
* The superclass constructor with a matching argument is called
* @param message String
* @param cause Throwable
*/
public FlyveException(String message, Throwable cause)
{
super(message, cause);
}
} | 1,638 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
CommonErrorType.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/CommonErrorType.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
public class CommonErrorType {
/* Battery */
public static final int BATTERY = 100;
public static final int BATTERY_TECHNOLOGY = 101;
public static final int BATTERY_TEMPERATURE = 102;
public static final int BATTERY_VOLTAGE = 103;
public static final int BATTERY_LEVEL = 104;
public static final int BATTERY_HEALTH = 105;
public static final int BATTERY_STATUS = 106;
public static final int BATTERY_CAPACITY = 107;
/* Bios */
public static final int BIOS = 200;
public static final int BIOS_DATE = 201;
public static final int BIOS_MANUFACTURER = 202;
public static final int BIOS_VERSION = 203;
public static final int BIOS_BOARD_MANUFACTURER = 204;
public static final int BIOS_MOTHER_BOARD_MODEL = 205;
public static final int BIOS_TAG = 206;
public static final int BIOS_MOTHER_BOARD_SERIAL = 207;
public static final int BIOS_SYSTEM_SERIAL = 208;
public static final int BIOS_SERIAL_PRIVATE = 209;
public static final int BIOS_CPU_SERIAL = 210;
/* Bluetooth */
public static final int BLUETOOTH = 300;
public static final int BLUETOOTH_HARDWARE_ADDRESS = 301;
public static final int BLUETOOTH_NAME = 302;
/* Camera */
public static final int CAMERA = 400;
public static final int CAMERA_COUNT = 401;
public static final int CAMERA_CHARACTERISTICS = 402;
public static final int CAMERA_RESOLUTION = 403;
public static final int CAMERA_FACING_STATE = 404;
public static final int CAMERA_FLASH_UNIT = 405;
public static final int CAMERA_IMAGE_FORMAT = 406;
public static final int CAMERA_ORIENTATION = 407;
public static final int CAMERA_VIDEO_RESOLUTION = 408;
public static final int CAMERA_FOCAL_LENGTH = 409;
public static final int CAMERA_SENSOR_SIZE = 410;
public static final int CAMERA_MANUFACTURER = 411;
public static final int CAMERA_MODEL = 412;
public static final int CAMERA_BUFFERED = 413;
public static final int CAMERA_VALUE_STRING = 414;
public static final int CAMERA_LIST_BYTES = 415;
/* Controllers */
public static final int CONTROLLERS = 500;
public static final int CONTROLLERS_FILE = 501;
public static final int CONTROLLERS_DRIVERS = 502;
/* CPUs */
public static final int CPU = 600;
public static final int CPU_CORE = 601;
public static final int CPU_ARCH = 602;
public static final int CPU_FAMILY_NAME = 603;
public static final int CPU_FAMILY_NUMBER = 604;
public static final int CPU_MANUFACTURER = 605;
public static final int CPU_MODEL = 606;
public static final int CPU_NAME = 607;
public static final int CPU_FREQUENCY = 608;
public static final int CPU_THREAD = 609;
/* Drives */
public static final int DRIVES = 700;
public static final int DRIVES_VOLUME = 701;
public static final int DRIVES_TOTAL = 702;
public static final int DRIVES_FREE_SPACE = 703;
public static final int DRIVES_FILE_SYSTEM = 704;
public static final int DRIVES_TYPE = 705;
/* Hardware */
public static final int HARDWARE = 800;
public static final int HARDWARE_DATE_LAST_LOGGED_USER = 801;
public static final int HARDWARE_LAST_LOGGED_USER = 802;
public static final int HARDWARE_USER_TAG = 803;
public static final int HARDWARE_USER_INFO = 804;
public static final int HARDWARE_NAME = 805;
public static final int HARDWARE_VERSION = 806;
public static final int HARDWARE_ARCH_NAME = 807;
public static final int HARDWARE_UUID = 808;
/* Inputs */
public static final int INPUTS = 900;
public static final int INPUTS_KEY_BOARD = 901;
public static final int INPUTS_TOUCH_SCREEN = 902;
/* Jvm */
public static final int JVM = 1000;
public static final int JVM_NAME = 1001;
public static final int JVM_VENDOR = 1002;
public static final int JVM_LANGUAGE = 1003;
public static final int JVM_RUNTIME = 1004;
public static final int JVM_HOME = 1005;
public static final int JVM_VERSION = 1006;
public static final int JVM_CLASS_PATH = 1007;
/* Location Providers */
public static final int LOCATION = 1100;
public static final int LOCATION_NAME = 1101;
/* Memory */
public static final int MEMORY = 1200;
public static final int MEMORY_CAPACITY = 1201;
public static final int MEMORY_RAM_INFO = 1202;
public static final int MEMORY_SPLIT_RAM_INFO = 1203;
public static final int MEMORY_RAM_PROP = 1204;
public static final int MEMORY_TYPE = 1205;
public static final int MEMORY_SPEED = 1206;
/* Networks */
public static final int NETWORKS = 1300;
public static final int NETWORKS_MAC_ADDRESS = 1301;
public static final int NETWORKS_MAC_ADDRESS_VALUE = 1302;
public static final int NETWORKS_SPEED = 1303;
public static final int NETWORKS_BSS_ID = 1304;
public static final int NETWORKS_SS_ID = 1305;
public static final int NETWORKS_IP_GATEWAY = 1306;
public static final int NETWORKS_IP_ADDRESS = 1307;
public static final int NETWORKS_IP_MASK = 1308;
public static final int NETWORKS_IP_DH_CP = 1309;
public static final int NETWORKS_IP_SUBNET = 1310;
public static final int NETWORKS_STATUS = 1311;
public static final int NETWORKS_CAT_INFO = 1312;
public static final int NETWORKS_DESCRIPTION = 1313;
public static final int NETWORKS_LOCAL_IPV6 = 1314;
/* Operating System */
public static final int OPERATING_SYSTEM = 1400;
public static final int OPERATING_SYSTEM_BOOT_TIME = 1401;
public static final int OPERATING_SYSTEM_KERNEL = 1402;
public static final int OPERATING_SYSTEM_TIME_ZONE = 1403;
public static final int OPERATING_SYSTEM_CURRENT = 1404;
public static final int OPERATING_SYSTEM_SSH_KEY = 1405;
/* Phone Status */
public static final int PHONE_STATUS = 1500;
/* SENSORS */
public static final int SENSORS = 1600;
public static final int SENSORS_NAME = 1601;
public static final int SENSORS_MANUFACTURER = 1602;
public static final int SENSORS_TYPE = 1603;
public static final int SENSORS_POWER = 1604;
public static final int SENSORS_VERSION = 1605;
/* SIM CARDS */
public static final int SIM_CARDS = 1700;
public static final int SIM_CARDS_MULTIPLE = 1701;
public static final int SIM_CARDS_STATE_BY_SLOT = 1702;
public static final int SIM_CARDS_COUNTRY = 1703;
public static final int SIM_CARDS_OPERATOR_CODE = 1704;
public static final int SIM_CARDS_OPERATOR_NAME = 1705;
public static final int SIM_CARDS_SERIAL = 1706;
public static final int SIM_CARDS_STATE = 1707;
public static final int SIM_CARDS_LINE_NUMBER = 1708;
public static final int SIM_CARDS_SUBSCRIBER_ID = 1709;
/* Software */
public static final int SOFTWARE = 1800;
public static final int SOFTWARE_NAME = 1801;
public static final int SOFTWARE_PACKAGE = 1802;
public static final int SOFTWARE_INSTALL_DATE = 1803;
public static final int SOFTWARE_VERSION = 1804;
public static final int SOFTWARE_FILE_SIZE = 1805;
public static final int SOFTWARE_FOLDER = 1806;
public static final int SOFTWARE_REMOVABLE = 1807;
public static final int SOFTWARE_USER_ID = 1808;
/* Storage */
public static final int STORAGE = 1900;
public static final int STORAGE_PARTITION = 1901;
public static final int STORAGE_VALUES = 1902;
/* Usb */
public static final int USB = 2000;
public static final int USB_SYS_BUS = 2001;
public static final int USB_SERVICE = 2002;
public static final int USB_PID = 2003;
public static final int USB_VID = 2004;
public static final int USB_DEVICE_SUB_CLASS = 2005;
public static final int USB_REPORTED_PRODUCT_NAME = 2006;
public static final int USB_USB_VERSION = 2007;
public static final int USB_SERIAL_NUMBER = 2008;
/* User */
public static final int USER = 2100;
public static final int USER_NAME = 2101;
/* Videos */
public static final int VIDEOS = 2200;
public static final int VIDEOS_RESOLUTION = 2201;
/* Categories */
public static final int CATEGORY_TO_XML = 2300;
public static final int CATEGORY_TO_XML_WITHOUT_PRIVATE = 2301;
public static final int CATEGORY_TO_JSON = 2302;
public static final int CATEGORY_TO_JSON_WITHOUT_PRIVATE = 2303;
public static final int CATEGORIES_TO_XML = 2304;
public static final int CATEGORIES_TO_XML_WITHOUT_PRIVATE = 2305;
public static final int CATEGORIES_TO_JSON = 2306;
public static final int CATEGORIES_TO_JSON_WITHOUT_PRIVATE = 2307;
/* Utils */
public static final int UTILS_CAT_INFO = 2400;
public static final int UTILS_CAT_INFO_MULTIPLE = 2401;
public static final int UTILS_CREATE_XML = 2402;
public static final int UTILS_CREATE_JSON = 2403;
public static final int UTILS_DEVICE_PROPERTIES = 2404;
public static final int UTILS_LOAD_JSON_ASSET = 2405;
/* Modems */
public static final int MODEMS = 2500;
public static final int MODEMS_IMEI = 2501;
} | 10,307 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
GenericFileProvider.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/GenericFileProvider.java | package org.flyve.inventory;
import androidx.core.content.FileProvider;
public class GenericFileProvider extends FileProvider {
}
| 135 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Utils.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/Utils.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.format.DateFormat;
import android.util.Xml;
import org.flyve.inventory.categories.Categories;
import org.flyve.inventory.categories.Hardware;
import org.json.JSONObject;
import org.xmlpull.v1.XmlSerializer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.nio.charset.Charset;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Scanner;
public class Utils {
private static int rating = -1;
private Utils() {
}
/**
* Detects if it is an emulator or a real dvice
* @return true for emulator, false for real device
*/
public static boolean isEmulator() {
int newRating = 0;
if(rating < 0) {
if (Build.PRODUCT.contains("sdk") ||
Build.PRODUCT.contains("Andy") ||
Build.PRODUCT.contains("ttVM_Hdragon") ||
Build.PRODUCT.contains("google_sdk") ||
Build.PRODUCT.contains("Droid4X") ||
Build.PRODUCT.contains("nox") ||
Build.PRODUCT.contains("sdk_x86") ||
Build.PRODUCT.contains("sdk_google") ||
Build.PRODUCT.contains("vbox86p")) {
newRating++;
}
if (Build.MANUFACTURER.equals("unknown") ||
Build.MANUFACTURER.equals("Genymotion") ||
Build.MANUFACTURER.contains("Andy") ||
Build.MANUFACTURER.contains("MIT") ||
Build.MANUFACTURER.contains("nox") ||
Build.MANUFACTURER.contains("TiantianVM")){
newRating++;
}
if (Build.BRAND.equals("generic") ||
Build.BRAND.equals("generic_x86") ||
Build.BRAND.equals("TTVM") ||
Build.BRAND.contains("Andy")) {
newRating++;
}
if (Build.DEVICE.contains("generic") ||
Build.DEVICE.contains("generic_x86") ||
Build.DEVICE.contains("Andy") ||
Build.DEVICE.contains("ttVM_Hdragon") ||
Build.DEVICE.contains("Droid4X") ||
Build.DEVICE.contains("nox") ||
Build.DEVICE.contains("generic_x86_64") ||
Build.DEVICE.contains("vbox86p")) {
newRating++;
}
if (Build.MODEL.equals("sdk") ||
Build.MODEL.equals("google_sdk") ||
Build.MODEL.contains("Droid4X") ||
Build.MODEL.contains("TiantianVM") ||
Build.MODEL.contains("Andy") ||
Build.MODEL.equals("Android SDK built for x86_64") ||
Build.MODEL.equals("Android SDK built for x86")) {
newRating++;
}
if (Build.HARDWARE.equals("goldfish") ||
Build.HARDWARE.equals("vbox86") ||
Build.HARDWARE.contains("nox") ||
Build.HARDWARE.contains("ttVM_x86")) {
newRating++;
}
if (Build.FINGERPRINT.contains("generic/sdk/generic") ||
Build.FINGERPRINT.contains("generic_x86/sdk_x86/generic_x86") ||
Build.FINGERPRINT.contains("Andy") ||
Build.FINGERPRINT.contains("ttVM_Hdragon") ||
Build.FINGERPRINT.contains("generic_x86_64") ||
Build.FINGERPRINT.contains("generic/google_sdk/generic") ||
Build.FINGERPRINT.contains("vbox86p") ||
Build.FINGERPRINT.contains("generic/vbox86p/vbox86p")) {
newRating++;
}
rating = newRating;
}
return rating > 3;
}
/**
* Create a JSON String with al the Categories available
* @param categories ArrayList with the categories
* @param appVersion Name of the agent
* @param context Context
* @param isPrivate boolean
* @param tag String
* @return String with JSON
* @throws FlyveException Exception
*/
protected static String createJSON(Context context, ArrayList<Categories> categories, String appVersion,
boolean isPrivate, String tag, String asset_itemtype) throws FlyveException {
try {
JSONObject jsonAccessLog = new JSONObject();
jsonAccessLog.put("logDate", DateFormat.format("yyyy-MM-dd HH:mm:ss", new Date()).toString());
jsonAccessLog.put("userId", "");
jsonAccessLog.put("keyname", "TAG");
jsonAccessLog.put("keyvalue", tag);
JSONObject content = new JSONObject();
content.put("accessLog", jsonAccessLog);
content.put("accountInfo", jsonAccessLog);
content.put("versionClient", appVersion);
content.put("accountinfo", tag);
for (Categories cat : categories) {
if(isPrivate) {
cat.toJSONWithoutPrivateData(content);
} else {
cat.toJSON(content);
}
}
JSONObject jsonQuery = new JSONObject();
jsonQuery.put("query", "INVENTORY");
jsonQuery.put("itemtype", asset_itemtype);
jsonQuery.put("versionClient", appVersion);
jsonQuery.put("deviceId", getDeviceId(context));
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null &&
(context.checkPermission(android.Manifest.permission.READ_PHONE_STATE, android.os.Process.myPid(), android.os.Process.myUid()) == PackageManager.PERMISSION_GRANTED)) {
//Since Android 10 getDeviceID thrown error
try{
jsonQuery.put("IMEI", telephonyManager.getDeviceId());
}catch (Exception e){
InventoryLog.e(e.getMessage() + e.getCause());
}
}
jsonQuery.put("content", content);
JSONObject jsonRequest = new JSONObject();
jsonRequest.put("request", jsonQuery);
return jsonRequest.toString();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(String.valueOf(CommonErrorType.UTILS_CREATE_JSON), ex.getMessage()));
throw new FlyveException(ex.getMessage(), ex.getCause());
}
}
/**
* Create a XML String with al the Categories available
* @param categories ArrayList with the categories
* @param appVersion Name of the agent
* @param context Context
* @param isPrivate boolean
* @param tag String
* @return String with XML
* @throws FlyveException Exception
*/
protected static String createXML(Context context, ArrayList<Categories> categories, String appVersion,
boolean isPrivate, String tag, String asset_type) throws FlyveException {
if (categories != null) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.setFeature(
"http://xmlpull.org/v1/doc/features.html#indent-output",
true);
// indentation as 3 spaces
serializer.startDocument("utf-8", true);
// Start REQUEST
serializer.startTag(null, "REQUEST");
serializer.startTag(null, "QUERY");
serializer.text("INVENTORY");
serializer.endTag(null, "QUERY");
serializer.startTag(null, "ITEMTYPE");
serializer.text(asset_type);
serializer.endTag(null, "ITEMTYPE");
serializer.startTag(null, "DEVICEID");
serializer.text(getDeviceId(context));
serializer.endTag(null, "DEVICEID");
// Start CONTENT
serializer.startTag(null, "CONTENT");
serializer.startTag(null, "VERSIONCLIENT");
serializer.text(appVersion);
serializer.endTag(null, "VERSIONCLIENT");
// Start ACCOUNTINFO
serializer.startTag(null, "ACCOUNTINFO");
serializer.startTag(null, "KEYNAME");
serializer.text("TAG");
serializer.endTag(null, "KEYNAME");
serializer.startTag(null, "KEYVALUE");
serializer.text(tag);
serializer.endTag(null, "KEYVALUE");
serializer.endTag(null, "ACCOUNTINFO");
// Start ACCESSLOG
serializer.startTag(null, "ACCESSLOG");
serializer.startTag(null, "LOGDATE");
serializer.text(DateFormat.format("yyyy-MM-dd HH:mm:ss", new Date()).toString());
serializer.endTag(null, "LOGDATE");
serializer.startTag(null, "USERID");
serializer.text("");
serializer.endTag(null, "USERID");
serializer.endTag(null, "ACCESSLOG");
// End ACCESSLOG
for (Categories cat : categories) {
if(isPrivate) {
cat.toXMLWithoutPrivateData(serializer);
} else {
cat.toXML(serializer);
}
}
serializer.endTag(null, "CONTENT");
// End CONTENT
serializer.endTag(null, "REQUEST");
// End REQUEST
serializer.endDocument();
// Return XML String
return writer.toString();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(String.valueOf(CommonErrorType.UTILS_CREATE_XML), ex.getMessage()));
throw new FlyveException(ex.getMessage(), ex.getCause());
}
}
return "";
}
private static String getDeviceId(Context context) {
Hardware hardware = new Hardware(context);
String currentTimeStamp = getCurrentTimeStamp("yyyy-MM-dd-HH-mm-ss");
String name = hardware.getName();
String deviceID = name.trim() + "-" + currentTimeStamp.trim();
return deviceID.replaceAll("\\s","");
}
public static Map<String, String> getCatMapInfo(String path) throws FileNotFoundException {
Map<String, String> map = new HashMap<>();
Scanner s = new Scanner(new File(path));
while (s.hasNextLine()) {
String[] values = s.nextLine().split(": ");
if (values.length > 1) {
map.put(values[0].trim(), values[1].trim());
}
}
return map;
}
public static String getValueMapInfo(Map<String, String> mapInfo, String name) {
for (String s : mapInfo.keySet()) {
if (s.equalsIgnoreCase(name)) {
return mapInfo.get(s);
}
}
return "";
}
public static String getValueMapCase(Map<String, String> mapInfo, String name) {
for (String s : mapInfo.keySet()) {
if (s.equals(name)) {
return mapInfo.get(s);
}
}
return "";
}
public static String getCatInfoMultiple(String path) {
StringBuilder concatInfo = new StringBuilder();
try {
Scanner s = new Scanner(new File(path));
while (s.hasNextLine()) {
concatInfo.append(s.nextLine());
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(String.valueOf(CommonErrorType.UTILS_CAT_INFO_MULTIPLE), ex.getMessage()));
}
return concatInfo.toString();
}
public static String getCatInfo(String path) {
try {
Scanner s = new Scanner(new File(path));
return s.next();
} catch (FileNotFoundException ex) {
InventoryLog.e(InventoryLog.getMessage(String.valueOf(CommonErrorType.UTILS_CAT_INFO), ex.getMessage()));
}
return "";
}
public static BufferedReader getBufferedSequentialCatInfo(String[] values) throws IOException, InterruptedException {
Process p = Runtime.getRuntime().exec(values[0]);
DataOutputStream dos = new DataOutputStream(p.getOutputStream());
for (int i = 1; i < values.length; i++)
dos.writeBytes(values[i]);
dos.flush();
dos.close();
p.waitFor();
return new BufferedReader(new InputStreamReader(p.getInputStream()));
}
public static String getSystemProperty(String type) {
ArrayList<HashMap<String, String>> arr = getDeviceProperties();
for (int i = 0; i < arr.size(); i++) {
HashMap<String, String> map = arr.get(i);
if (map.get(type) != null)
return map.get(type);
}
return "";
}
public static ArrayList<HashMap<String, String>> getDeviceProperties() {
try {
// Run the command
Process process = Runtime.getRuntime().exec("getprop");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
// Grab the results
ArrayList<HashMap<String, String>> arr = new ArrayList<>();
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] value = line.split(":");
HashMap<String, String> map = new HashMap<>();
if (value.length >= 2) {
map.put(removeBracket(value[0]), removeBracket(value[1]));
arr.add(map);
}
}
return arr;
} catch (IOException ex) {
InventoryLog.e(InventoryLog.getMessage(String.valueOf(CommonErrorType.UTILS_DEVICE_PROPERTIES), ex.getMessage()));
}
return new ArrayList<>();
}
private static String removeBracket(String str) {
return str.replaceAll("\\[", "").replaceAll("]", "");
}
/** Convert timestamp in a formatted date pattern
* @param time timestamp
* @param pattern string value
* @return converted time
*/
public static String convertTime(long time, String pattern) {
Date date = new Date(time);
Format format = new SimpleDateFormat(pattern, Locale.getDefault());
return format.format(date);
}
/** Get current date
* @param template format date
* @return String of the current date
*/
public static String getCurrentTimeStamp(String template) {
SimpleDateFormat sdfDate = new SimpleDateFormat(template, Locale.getDefault());
Date now = Calendar.getInstance().getTime();
return sdfDate.format(now);
}
public static String loadJSONFromAsset(Context context, String name) {
String json;
try {
InputStream is = context.getAssets().open(name);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
InventoryLog.e(InventoryLog.getMessage(String.valueOf(CommonErrorType.UTILS_LOAD_JSON_ASSET), ex.getMessage()));
return null;
}
return json;
}
/* Checks if external storage is available for read and write */
private static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
public static void createFile(Context context, String filename) {
File file;
InventoryLog.e(context.getFilesDir().getAbsolutePath());
file = new File(context.getFilesDir(), filename);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
InventoryLog.e(e.getLocalizedMessage());
}
} else {
InventoryLog.d(String.format("File %s already exists", filename.toString()));
}
}
public static void writeFile(Context context, String data, String filename) {
try {
FileOutputStream fileOutputStream;
fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
fileOutputStream.write(data.getBytes(Charset.forName("UTF-8")));
} catch (Exception e) {
InventoryLog.e(e.getLocalizedMessage());
}
}
/**
* Logs the message in a directory
* @param message the message
* @param filename name of the file
*/
public static void storeFile(Context context, String message, String filename) {
createFile(context, filename);
writeFile(context,message, filename);
/*String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
InventoryLog.e(path);
File dir = new File(path);
String state = Environment.getExternalStorageState();
InventoryLog.e(state);
if (Environment.MEDIA_MOUNTED.equals(state)) {
if(!dir.exists()) {
if(dir.mkdirs()) {
InventoryLog.d("create path");
} else {
InventoryLog.e("cannot create path");
return;
}
}
File logFile = new File(path + "/" + filename);
if (!logFile.exists()) {
try {
if(logFile.createNewFile()) {
InventoryLog.d("File created");
} else {
InventoryLog.d("Cannot create file");
return;
}
} catch (IOException ex) {
InventoryLog.e(ex.getMessage());
}
}
FileWriter fw = null;
try {
//BufferedWriter for performance, true to set append to file flag
fw = new FileWriter(logFile, false);
BufferedWriter buf = new BufferedWriter(fw);
buf.write(message);
buf.newLine();
buf.flush();
buf.close();
fw.close();
InventoryLog.d("Inventory stored");
}
catch (IOException ex) {
InventoryLog.e(ex.getMessage());
}
finally {
if(fw!=null) {
try {
fw.close();
} catch(Exception ex) {
InventoryLog.e(ex.getMessage());
}
}
}
} else {
InventoryLog.d("External Storage is not available");
}*/
}
public static String getIPAddress(boolean useIPv4) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress();
//boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
boolean isIPv4 = sAddr.indexOf(':')<0;
if (useIPv4) {
if (isIPv4)
return sAddr;
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
return delim<0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
}
}
}
}
}
} catch (Exception ignored) { } // for now eat exceptions
return "";
}
}
| 22,367 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
CategoryValue.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/CategoryValue.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import java.util.ArrayList;
import java.util.List;
public class CategoryValue {
private String value;
private String jsonName;
private String xmlName;
private Boolean isPrivate;
private Boolean hasCDATA;
private Category category;
private List<String> values;
private static final String REGEX="[<>&]";
/** Normal category
* @param value String value
* @param xmlName String xml name
* @param jsonName String json name
*/
public CategoryValue(String value, String xmlName, String jsonName) {
if (value == null) {
value = "";
}
if (xmlName == null) {
xmlName = "";
}
if (jsonName == null) {
jsonName = "";
}
if (hasCharToReplace(value)) {
value = value.replaceAll(REGEX, "");
}
this.value = value;
this.jsonName = jsonName;
this.xmlName = xmlName;
this.isPrivate = false;
this.hasCDATA = false;
}
public CategoryValue(String value, String xmlName, String jsonName, Boolean isPrivate, Boolean hasCDATA) {
if (value == null) {
value = "";
}
if (xmlName == null) {
xmlName = "";
}
if (jsonName == null) {
jsonName = "";
}
if (hasCharToReplace(value)) {
value = value.replaceAll(REGEX, "");
}
this.value = value;
this.jsonName = jsonName;
this.xmlName = xmlName;
this.isPrivate = isPrivate;
this.hasCDATA = hasCDATA;
}
/** Insert list of values to the Category
* @param values List list of values
* @param xmlName String xml name
* @param jsonName String json name
*/
public CategoryValue(List<String> values, String xmlName, String jsonName) {
if (values == null) {
values = new ArrayList<>();
}
if (xmlName == null) {
xmlName = "";
}
if (jsonName == null) {
jsonName = "";
}
for (int i = 0; i < values.size(); i++) {
String value = values.get(i);
if (hasCharToReplace(value)) {
String s = value.replaceAll(REGEX, "");
values.add(i, s);
}
}
this.values = values;
this.jsonName = jsonName;
this.xmlName = xmlName;
this.isPrivate = false;
this.hasCDATA = false;
}
/** Embed an category inside in another category
* @param category instance of the same class CategoryValue
*/
public CategoryValue(Category category){
this.category = category;
}
public CategoryValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String newValue) {
this.value = newValue;
}
public String getJsonName() {
return jsonName;
}
public String getXmlName() {
return xmlName;
}
public Boolean isPrivate() {
return isPrivate;
}
public Boolean hasCDATA() {
return hasCDATA;
}
public Category getCategory() {
return category;
}
public List<String> getValues() {
return values;
}
private boolean hasCharToReplace(final String val) {
return val.matches(REGEX);
}
}
| 4,614 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Memory.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Memory.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import org.flyve.inventory.Utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
* This class get all the information of the Memory
*/
public class Memory extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = -494336872000892273L;
// Properties of this component
private static final String DESCRIPTION = "Memory";
private static final String MEMO_INFO = "/proc/meminfo";
private String[] ramInfo = new String[2];
private final Context context;
/**
* This constructor load the context and the Memory information
*
* @param xCtx Context where this class work
*/
public Memory(Context xCtx) {
super(xCtx);
context = xCtx;
try {
getRamInfo();
Category c = new Category("MEMORIES", "memories");
c.put("DESCRIPTION", new CategoryValue(DESCRIPTION, "DESCRIPTION", "description"));
c.put("CAPACITY", new CategoryValue(getCapacity(), "CAPACITY", "capacity"));
c.put("TYPE", new CategoryValue(getType(), "TYPE", "type"));
c.put("SPEED", new CategoryValue(getSpeed(), "SPEED", "speed"));
this.add(c);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.MEMORY, ex.getMessage()));
}
}
/**
* Get total memory of the device
* @return String Total Memory
*/
public String getCapacity() {
String capacity = "N/A";
try {
FileReader fr = null;
try {
File f = new File(MEMO_INFO);
fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr, 8 * 1024);
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("MemTotal")) {
String[] parts = line.split(":");
String part1 = parts[1].trim();
Long memory = Long.valueOf(part1.replaceAll("(.*)\\ kB", "$1"));
memory = memory / 1024;
capacity = String.valueOf(memory);
}
}
br.close();
} catch (IOException e) {
InventoryLog.e(e.getMessage());
} finally {
if (fr != null) {
fr.close();
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.MEMORY_CAPACITY, ex.getMessage()));
}
return capacity;
}
private void getRamInfo() {
try {
String infoCat = Utils.getCatInfo("/sys/bus/platform/drivers/ddr_type/ddr_type");
if (!infoCat.equals("")) {
splitRamInfo(infoCat);
} else {
String infoProp = getRamProp();
if (infoProp != null) {
splitRamInfo(infoProp);
} else {
ramInfo[0] = "N/A";
ramInfo[1] = "N/A";
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.MEMORY_RAM_INFO, ex.getMessage()));
}
}
private void splitRamInfo(String info) {
try {
if (info.contains("_")) {
String[] partRam = info.split("_", 2);
ramInfo[0] = partRam[0];
ramInfo[1] = partRam[1];
} else {
ramInfo[0] = info;
ramInfo[1] = "N/A";
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.MEMORY_SPLIT_RAM_INFO, ex.getMessage()));
}
}
private String getRamProp() {
try {
String a = Utils.getSystemProperty("ro.boot.hardware.ddr");
if (!(a == null || a.isEmpty())) {
int indexOf = a.indexOf("LPDDR");
if (indexOf > 0) {
return a.substring(indexOf);
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.MEMORY_RAM_PROP, ex.getMessage()));
}
return null;
}
public String getType() {
String value = "N/A";
try {
value = ramInfo[0];
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.MEMORY_TYPE, ex.getMessage()));
}
return value;
}
public String getSpeed() {
String value = "N/A";
try {
value = ramInfo[1];
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.MEMORY_SPEED, ex.getMessage()));
}
return value;
}
}
| 6,922 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Envs.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Envs.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import org.flyve.inventory.InventoryLog;
import java.util.Map;
/**
* This class get all the information of the Environment
*/
public class Envs extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = -6210390594988309754L;
/**
* This constructor load the context and the Environment information
* @param xCtx Context where this class work
*/
public Envs(Context xCtx) {
super(xCtx);
try {
//get all envs vars
Map<String, String> envs = System.getenv();
for (Map.Entry<String, String> entry : envs.entrySet()) {
Category c = new Category("ENVS", "envs");
c.put("KEY", new CategoryValue(entry.getKey(), "KEY", "key"));
c.put("VAL", new CategoryValue(envs.get(entry.getKey()), "VAL", "Value"));
this.add(c);
}
} catch (Exception ex) {
InventoryLog.e(ex.getMessage());
}
}
}
| 2,865 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Networks.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Networks.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.app.Service;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import org.flyve.inventory.Utils;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
/**
* This class get all the information of the Network
*/
public class Networks extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 6829495385432791427L;
// Properties of this component
private static final String TYPE = "WIFI";
private static final String NO_DECSRIPTION_PROVIDED = "No description found";
private DhcpInfo dhcp;
private WifiInfo wifi;
private final Context context;
/**
* Indicates whether some other object is "equal to" this one
* @param obj Object the reference object with which to compare
* @return boolean true if the object is the same as the one given in argument
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return (!super.equals(obj));
}
/**
* Returns a hash code value for the object
* @return int a hash code value for the object
*/
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 89 * hash + (this.dhcp != null ? this.dhcp.hashCode() : 0);
hash = 89 * hash + (this.wifi != null ? this.wifi.hashCode() : 0);
return hash;
}
/**
* This constructor load the context and the Networks information
* @param xCtx Context where this class work
*/
public Networks(Context xCtx) {
super(xCtx);
context = xCtx;
try {
WifiManager pWM = (WifiManager) context.getApplicationContext().getSystemService(Service.WIFI_SERVICE);
boolean wasWifiEnabled = pWM.isWifiEnabled();
// Enable Wifi State if not
if (!wasWifiEnabled) {
pWM.setWifiEnabled(true);
}
Category c = new Category("NETWORKS", "networks");
dhcp = pWM.getDhcpInfo();
wifi = pWM.getConnectionInfo();
InventoryLog.d("<===WIFI DHCP===>");
InventoryLog.d("dns1=" + StringUtils.intToIp(dhcp.dns1));
InventoryLog.d("dns2=" + StringUtils.intToIp(dhcp.dns2));
InventoryLog.d("leaseDuration=" + dhcp.leaseDuration);
c.put("DESCRIPTION", new CategoryValue(getDescription(), "DESCRIPTION", "description", true, false));
c.put("DRIVER", new CategoryValue(TYPE, "DRIVER", "driver", true, false));
c.put("IPADDRESS", new CategoryValue(getIpAddress(), "IPADDRESS", "ipAddress", true, false));
c.put("IPADDRESS6", new CategoryValue(getAddressIpV6(), "IPADDRESS6", "ipaddress6", true, false));
c.put("IPDHCP", new CategoryValue(getIpDhCp(), "IPDHCP", "ipDhcp", true, false));
c.put("IPGATEWAY", new CategoryValue(getIpgateway(), "IPGATEWAY", "ipGateway"));
c.put("IPMASK", new CategoryValue(getIpMask(), "IPMASK", "ipMask", true, false));
c.put("IPMASK6", new CategoryValue(getMaskIpV6(), "IPMASK6", "ipMask6", true, false));
c.put("IPSUBNET", new CategoryValue(getIpSubnet(), "IPSUBNET", "ipSubnet", true, false));
c.put("IPSUBNET6", new CategoryValue(getSubnetIpV6(), "IPSUBNET6", "ipSubnet6", true, false));
c.put("MACADDR", new CategoryValue(getMacAddress(), "MACADDR", "macAddress"));
c.put("SPEED", new CategoryValue(getSpeed(), "SPEED", "speed"));
c.put("STATUS", new CategoryValue(getStatus(), "STATUS", "status", true, false));
c.put("TYPE", new CategoryValue(TYPE, "TYPE", "type"));
c.put("WIFI_BSSID", new CategoryValue(getSSID(), "WIFI_BSSID", "wifiBssid"));
c.put("WIFI_SSID", new CategoryValue(getBSSID(), "WIFI_SSID", "wifiSsid"));
this.add(c);
// Restore Wifi State
if (!wasWifiEnabled) {
pWM.setWifiEnabled(false);
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.NETWORKS, ex.getMessage()));
}
}
/**
* Get the Media Access Control address
* @return string the MAC address
*/
public String getMacAddress() {
String macAddress = "N/A";
try {
macAddress = wifi.getMacAddress();
// if get default mac address
if (macAddress == null || macAddress.contains("02:00:00:00:00:00")) {
macAddress = getMACAddress("wlan0");
if (macAddress.isEmpty()) {
macAddress = getMACAddress("eth0");
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.NETWORKS_MAC_ADDRESS, ex.getMessage()));
}
return macAddress;
}
private String getMACAddress(String interfaceName) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (interfaceName != null) {
if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
}
byte[] mac = intf.getHardwareAddress();
if (mac==null) return "";
StringBuilder buf = new StringBuilder();
for (byte aMac : mac) buf.append(String.format("%02X:",aMac));
if (buf.length()>0) buf.deleteCharAt(buf.length()-1);
return buf.toString();
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.NETWORKS_MAC_ADDRESS_VALUE, ex.getMessage()));
}
return "N/A";
}
/**
* Get the speed of the Wifi connection
* @return string the current speed in Mbps
*/
public String getSpeed() {
String value = "N/A";
try {
value = String.valueOf(wifi.getLinkSpeed());
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.NETWORKS_SPEED, ex.getMessage()));
}
return value;
}
/**
* Get the Basic Service Set Identifier (BSSID)
* @return string the BSSID of the current access point
*/
public String getBSSID() {
String value = "N/A";
try {
value = String.valueOf(wifi.getBSSID());
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.NETWORKS_BSS_ID, ex.getMessage()));
}
return value;
}
/**
* Get the Service Set Identifier (SSID)
* @return string the SSID of the current network
*
*/
public String getSSID() {
String value = "N/A";
try {
value = String.valueOf(wifi.getSSID());
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.NETWORKS_SS_ID, ex.getMessage()));
}
//remove char ex: <unknown ssid>
value = value.replace("<","");
value = value.replace(">","");
return value;
}
/**
* Get the IP address of the gateway
* @return string the gateway IP address
*/
public String getIpgateway() {
String value = "N/A";
try {
value = StringUtils.intToIp(dhcp.gateway);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.NETWORKS_IP_GATEWAY, ex.getMessage()));
}
return value;
}
/**
* Get the IP address
* @return string the current IP address
*/
public String getIpAddress() {
String value = "N/A";
try {
value = StringUtils.intToIp(dhcp.ipAddress);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.NETWORKS_IP_ADDRESS, ex.getMessage()));
}
return value;
}
/**
* Get the IP address of the netmask
* @return string the netmask
*/
public String getIpMask() {
String value = "N/A";
try {
value = StringUtils.intToIp(dhcp.netmask);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.NETWORKS_IP_MASK, ex.getMessage()));
}
return value;
}
/**
* Get the IP address of the DHCP
* @return string the server address
*/
public String getIpDhCp() {
String value = "N/A";
try {
value = StringUtils.intToIp(dhcp.serverAddress);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.NETWORKS_IP_DH_CP, ex.getMessage()));
}
return value;
}
/**
* Get the IP Subnet of the wifi connection info
* @return string the IP Subnet
*/
public String getIpSubnet() {
String value = "N/A";
try {
value = StringUtils.getSubNet(wifi.getIpAddress());
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.NETWORKS_IP_SUBNET, ex.getMessage()));
}
return value;
}
/**
* Get the IP Subnet of the wifi connection info
* @return string the IP Subnet
*/
public String getStatus() {
String value = "N/A";
try {
value = Utils.getCatInfo("/sys/class/net/wlan0/operstate");
}catch (Exception ex){
InventoryLog.d(InventoryLog.getMessage(context, CommonErrorType.NETWORKS_STATUS, "Unable to get WIFI status from /sys/class/net/wlan0/operstate try with API"));
}
if(value.trim().isEmpty() || value.equalsIgnoreCase("N/A")){
if(isConnectedToWifi()){
value = "up";
}else{
value = "down";
}
}
return value;
}
/**
* Try to know if device is connected to WIFI
* @return true or false
*/
private boolean isConnectedToWifi() {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) {
return false;
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
Network network = connectivityManager.getActiveNetwork();
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
if (capabilities == null) {
return false;
}
return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
} else {
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (networkInfo == null) {
return false;
}
return networkInfo.isConnected();
}
}
/**
* Get description network
* @return string description
*/
public String getDescription() {
String name = "N/A";
try {
String ipadressString = Utils.getIPAddress(true);
InetAddress address = InetAddress.getByName(ipadressString);
NetworkInterface netInterface = NetworkInterface.getByInetAddress(address);
if (netInterface != null ) {
name = netInterface.getDisplayName();
return name;
}
} catch (UnknownHostException ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.NETWORKS_DESCRIPTION, ex.getMessage()));
} catch (SocketException ex){
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.NETWORKS_DESCRIPTION, ex.getMessage()));
} catch(Exception ex){
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.NETWORKS_DESCRIPTION, ex.getMessage()));
}
//change name
name = NO_DECSRIPTION_PROVIDED;
return name;
}
/**
* Get the address IpV6
* @return string the address IpV6
*/
public String getAddressIpV6() {
InterfaceAddress interfaceIPV6 = getInterfaceByType("IPV6");
if (interfaceIPV6 != null) {
String address = interfaceIPV6.getAddress().getHostAddress();
return address.contains("%") ? address.split("%", 2)[0] : "N/A";
} else {
return "N/A";
}
}
/**
* Get mask IpV6
* @return string the mask IpV6
*/
public String getMaskIpV6() {
InterfaceAddress interfaceIPV6 = getInterfaceByType("IPV6");
if (interfaceIPV6 != null) {
short prefixLength = interfaceIPV6.getNetworkPrefixLength();
return getMaskConvert(prefixLength);
} else {
return "N/A";
}
}
private String getMaskConvert(short prefixLength) {
/* Get Binary */
int resident = prefixLength % 4;
StringBuilder maskTemp = new StringBuilder();
StringBuilder maskHexadecimal = new StringBuilder();
ArrayList<String> maskBinaryList = new ArrayList<>();
for (int i = 1; i < prefixLength + 1; i++) {
maskTemp.append("1");
if (i % 4 == 0) {
maskBinaryList.add(maskTemp.toString());
maskTemp.delete(0, 4);
continue;
}
if (i == prefixLength) {
if (resident != 0) {
char[] repeat = new char[4 - resident];
Arrays.fill(repeat, '0');
maskTemp.append(new String(repeat));
maskBinaryList.add(maskTemp.toString());
}
}
}
/* Convert to Hexadecimal */
resident = maskBinaryList.size() % 4;
for (int i = 1; i < maskBinaryList.size() + 1; i++) {
int decimal = Integer.parseInt(maskBinaryList.get(i - 1), 2);
if (i % 4 == 0) {
maskHexadecimal.append(Integer.toString(decimal, 16)).append(":");
} else {
maskHexadecimal.append(Integer.toString(decimal, 16));
}
if (i == maskBinaryList.size()) {
if (resident != 0) {
char[] repeat = new char[4 - resident];
Arrays.fill(repeat, '0');
maskHexadecimal.append(new String(repeat));
}
}
}
return maskHexadecimal.append(":").toString();
}
/** Get interface address
* @param type IPV6 or IPV4
* @return interface address
*/
private InterfaceAddress getInterfaceByType(String type) {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface anInterface = en.nextElement();
for (InterfaceAddress interfaceAddress : anInterface.getInterfaceAddresses()) {
if ("IPV6".equals(type) && interfaceAddress.getAddress() instanceof Inet6Address) {
return interfaceAddress;
} else if ("IPV4".equals(type) && interfaceAddress.getAddress() instanceof Inet4Address)
return interfaceAddress;
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.NETWORKS_LOCAL_IPV6, ex.getMessage()));
}
return null;
}
/**
* Get the Subnet IpV6
* @return string Subnet IpV6
*/
public String getSubnetIpV6() {
String value = "N/A";
String addressIpV6 = getAddressIpV6();
if (addressIpV6.contains("::")) {
value = addressIpV6.split("::", 2)[0] + "::";
}
return value;
}
}
| 15,993 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Videos.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Videos.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.app.Service;
import android.content.Context;
import android.graphics.Point;
import android.view.WindowManager;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
/**
* This class get all the information of the Video
*/
public class Videos extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 6953895287405000489L;
private Context context;
/**
* Indicates whether some other object is "equal to" this one
* @param obj Object the reference object with which to compare
* @return boolean true if the object is the same as the one given in argument
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return (!super.equals(obj));
}
/**
* Returns a hash code value for the object
* @return int a hash code value for the object
*/
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 89 * hash + (this.context != null ? this.context.hashCode() : 0);
return hash;
}
/**
* This constructor load the context and the Video information
* @param xCtx Context where this class work
*/
public Videos(Context xCtx) {
super(xCtx);
this.context = xCtx;
try {
Category c = new Category("VIDEOS", "videos");
c.put("RESOLUTION", new CategoryValue(getResolution(), "RESOLUTION", "resolution"));
this.add(c);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.VIDEOS, ex.getMessage()));
}
}
/**
* Get the video resolutions
* @return string the width and height
*/
public String getResolution() {
String value = "N/A";
try {
WindowManager lWinMgr = (WindowManager) context.getSystemService(Service.WINDOW_SERVICE);
Point size = new Point();
lWinMgr.getDefaultDisplay().getSize(size);
int width = size.x;
int height = size.y;
value = String.format("%dx%d", width, height);
return value;
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.VIDEOS_RESOLUTION, ex.getMessage()));
}
return value;
}
}
| 4,328 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Sensors.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Sensors.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import java.util.List;
/**
* This class get all the information of the Sensor Devices
*/
public class Sensors extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 4846706700566208666L;
private final Context context;
/**
* This constructor load the context and the Sensors information
* @param xCtx Context where this class work
*/
public Sensors(Context xCtx) {
super(xCtx);
context = xCtx;
try {
SensorManager sensorManager = (SensorManager) xCtx.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor s : sensors) {
Category c = new Category("SENSORS", "sensors");
c.put("NAME", new CategoryValue(getName(s), "NAME", "name"));
c.put("MANUFACTURER", new CategoryValue(getManufacturer(s), "MANUFACTURER", "manufacturer"));
c.put("TYPE", new CategoryValue(getType(s), "TYPE", "type"));
c.put("POWER", new CategoryValue(getPower(s), "POWER", "power"));
c.put("VERSION", new CategoryValue(getVersion(s), "VERSION", "version"));
this.add(c);
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SENSORS, ex.getMessage()));
}
}
/**
* Get the name of the sensor
* @param s Sensor
* @return string the sensor name
*/
public String getName(Sensor s) {
String value = "N/A";
try {
value = s.getName();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SENSORS_NAME, ex.getMessage()));
}
return value;
}
/**
* Get the Manufacturer of the sensor
* @param s Sensor
* @return string the vendor of the sensor
*/
public String getManufacturer(Sensor s) {
String value = "N/A";
try {
value = s.getVendor();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SENSORS_MANUFACTURER, ex.getMessage()));
}
return value;
}
/**
* Get the type of the sensor
* @param s Sensor
* @return string the sensor type
*/
public String getType(Sensor s) {
String valueType = "N/A";
try {
int type = s.getType();
switch (type) {
case Sensor.TYPE_ACCELEROMETER:
valueType = "ACCELEROMETER";
break;
case Sensor.TYPE_GRAVITY:
valueType = "GRAVITY";
break;
case Sensor.TYPE_GYROSCOPE:
valueType = "GYROSCOPE";
break;
case Sensor.TYPE_LINEAR_ACCELERATION:
valueType = "LINEAR ACCELERATION";
break;
case Sensor.TYPE_MAGNETIC_FIELD:
valueType = "MAGNETIC FIELD";
break;
case Sensor.TYPE_PRESSURE:
valueType = "PRESSURE";
break;
case Sensor.TYPE_PROXIMITY:
valueType = "PROXIMITY";
break;
case Sensor.TYPE_ROTATION_VECTOR:
valueType = "ROTATION VECTOR";
break;
default:
valueType = "Unknow";
break;
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SENSORS_TYPE, ex.getMessage()));
}
return valueType;
}
/**
* Get the power of the sensor
* @param s Sensor
* @return string the power used by the sensor while in use
*/
public String getPower(Sensor s) {
String value = "N/A";
try {
value = String.valueOf(s.getPower());
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SENSORS_POWER, ex.getMessage()));
}
return value;
}
/**
* Get the version of the sensor's module
* @param s Sensor
* @return string the version
*/
public String getVersion(Sensor s) {
String value = "N/A";
try {
value = String.valueOf(s.getVersion());
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SENSORS_VERSION, ex.getMessage()));
}
return value;
}
}
| 5,795 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Battery.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Battery.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
/**
* This class get all the information of the baterry like level, voltage, temperature, status, health, technology
* The constructor of the class trigger a BroadcastReceiver with the information
*/
public class Battery extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = -4096347994131285426L;
// Properties of this component
private final Intent batteryIntent;
private final Context context;
/**
* Indicates whether some other object is "equal to" this one
* @param obj Object the reference object with which to compare.
* @return boolean true if the object is the same as the one given in argument
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return (!super.equals(obj));
}
/**
* Returns a hash code value for the object
* @return int a hash code value for the object
*/
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 89 * hash + (this.batteryIntent != null ? this.batteryIntent.hashCode() : 0);
return hash;
}
/**
* This constructor trigger BroadcastReceiver to get all the information about Battery
* @param xCtx Context where this class work
*/
public Battery(Context xCtx) {
super(xCtx);
context = xCtx;
IntentFilter batteryIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryIntent = context.registerReceiver(null, batteryIntentFilter);
try {
if (batteryIntent != null) {
if (!getLevel().equals("0%")) {
// Load the information
Category c = new Category("BATTERIES", "batteries");
c.put("CHEMISTRY", new CategoryValue(getTechnology(), "CHEMISTRY", "chemistry"));
c.put("TEMPERATURE", new CategoryValue(getTemperature(), "TEMPERATURE", "temperature"));
c.put("VOLTAGE", new CategoryValue(getVoltage(), "VOLTAGE", "voltage"));
c.put("LEVEL", new CategoryValue(getLevel(), "LEVEL", "level"));
c.put("HEALTH", new CategoryValue(getBatteryHealth(), "HEALTH", "health"));
c.put("STATUS", new CategoryValue(getBatteryStatus(), "STATUS", "status"));
c.put("CAPACITY", new CategoryValue(getCapacity(), "CAPACITY", "capacity"));
this.add(c);
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BATTERY, ex.getMessage()));
}
}
public String getTechnology() {
String technology = "N/A";
try {
batteryIntent.getStringExtra("technology");
return technology;
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BATTERY_TECHNOLOGY, ex.getMessage()));
}
return technology;
}
public String getTemperature() {
String temperature = "N/A";
try {
float extra = batteryIntent.getIntExtra("temperature", 0);
temperature = String.valueOf(extra / 10) + "c";
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BATTERY_TEMPERATURE, ex.getMessage()));
}
return temperature;
}
public String getVoltage() {
String voltage = "N/A";
try {
voltage = String.valueOf((float) batteryIntent.getIntExtra("voltage", 0) / 1000) + "V";
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BATTERY_VOLTAGE, ex.getMessage()));
}
return voltage;
}
public String getLevel() {
String level = "N/A";
try {
level = String.valueOf(batteryIntent.getIntExtra("level", 0)) + "%";
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BATTERY_LEVEL, ex.getMessage()));
}
return level;
}
public String getBatteryHealth() {
String health = "N/A";
try {
int intHealth = batteryIntent.getIntExtra("health",
BatteryManager.BATTERY_HEALTH_UNKNOWN);
if (intHealth == BatteryManager.BATTERY_HEALTH_GOOD) {
health = "Good";
} else if (intHealth == BatteryManager.BATTERY_HEALTH_OVERHEAT) {
health = "Over Heat";
} else if (intHealth == BatteryManager.BATTERY_HEALTH_DEAD) {
health = "Dead";
} else if (intHealth == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE) {
health = "Over Voltage";
} else if (intHealth == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE) {
health = "Unspecified Failure";
} else {
health = "Unknown";
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BATTERY_HEALTH, ex.getMessage()));
}
return health;
}
public String getBatteryStatus() {
String status = "N/A";
try {
int intStatus = batteryIntent.getIntExtra("status",
BatteryManager.BATTERY_STATUS_UNKNOWN);
if (intStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
status = "Charging";
} else if (intStatus == BatteryManager.BATTERY_STATUS_DISCHARGING) {
status = "Dis-charging";
} else if (intStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
status = "Not charging";
} else if (intStatus == BatteryManager.BATTERY_STATUS_FULL) {
status = "Full";
} else {
status = "Unknown";
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BATTERY_STATUS, ex.getMessage()));
}
return status;
}
public String getCapacity() {
String capacityValue = "N/A";
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
BatteryManager mBatteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
assert mBatteryManager != null;
Integer capacity = mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
if (capacity == Integer.MIN_VALUE)
return String.valueOf(0);
capacityValue = String.valueOf(capacity);
} else {
Object mPowerProfile;
double batteryCapacity = 0;
final String POWER_PROFILE_CLASS = "com.android.internal.os.PowerProfile";
try {
mPowerProfile = Class.forName(POWER_PROFILE_CLASS)
.getConstructor(Context.class)
.newInstance(context);
batteryCapacity = (double) Class
.forName(POWER_PROFILE_CLASS)
.getMethod("getBatteryCapacity")
.invoke(mPowerProfile);
} catch (Exception e) {
e.printStackTrace();
}
capacityValue = String.valueOf(batteryCapacity);
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BATTERY_CAPACITY, ex.getMessage()));
}
return capacityValue;
}
}
| 8,516 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Modems.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Modems.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import android.os.Build;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* This class get all the information of the Controllers
*/
public class Modems extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 6791259866128400637L;
private final Context context;
/**
* This constructor trigger get all the information about Controllers
* @param xCtx Context where this class work
*/
public Modems(Context xCtx) {
super(xCtx);
context = xCtx;
try {
ArrayList<String> imeiList;
imeiList = getIMEI();
for (String imei :imeiList) {
if(imei != null && !imei.equalsIgnoreCase("N/A")){
Category c = new Category("MODEMS", "modems");
c.put("IMEI", new CategoryValue(imei, "IMEI", "imei"));
this.add(c);
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.MODEMS, ex.getMessage()));
}
}
/**
* Get the imei
* @return list of the IMEI to Simcard
*/
public ArrayList<String> getIMEI() {
ArrayList<String> imeiList = new ArrayList<>();
try {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
SubscriptionManager subscriptionManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
assert subscriptionManager != null;
List<SubscriptionInfo> multipleSim = subscriptionManager.getActiveSubscriptionInfoList();
if (multipleSim != null && multipleSim.size() > 0) {
for (int i = 0; i < multipleSim.size(); i++) {
if (telephonyManager != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(telephonyManager.getDeviceId(i) != null){
imeiList.add(telephonyManager.getDeviceId(i));
}
}
}
} else {
imeiList.add("N/A");
}
} else {
String imei = telephonyManager.getDeviceId();
imeiList.add(imei != null ? imei : "N/A");
}
} catch (Exception ex) {
imeiList.add("N/A");
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.MODEMS_IMEI, ex.getMessage()));
}
return imeiList;
}
}
| 4,848 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Processes.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Processes.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
public class Processes
extends Category {
public Processes(String xType, String tagName) {
super(xType, tagName);
// TODO review how to get all the processes
}
/**
*
*/
private static final long serialVersionUID = 5399654900099889897L;
}
| 1,494 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
PhoneStatus.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/PhoneStatus.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
/**
* This class get all the information of the Network
*/
public class PhoneStatus extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 872718741270132229L;
/**
* This constructor load the context and the PhoneStatus information
* @param xCtx Context where this class work
*/
public PhoneStatus(Context xCtx) {
super(xCtx);
//TODO Solved the problem Thread inside other Thread to make PhoenStatus works
// The problem here is with a the PhoneStateListener and the
// AsyncTask we got a Thread inside other Thread
try {
final Category c = new Category("PHONE_STATUS", "phoneStatus");
TelephonyManager telMng = (TelephonyManager)xCtx.getSystemService(Context.TELEPHONY_SERVICE);
telMng.listen(new PhoneStateListener() {
@Override
public void onServiceStateChanged(ServiceState serviceState) {
super.onServiceStateChanged(serviceState);
String phoneState;
switch (serviceState.getState()) {
case ServiceState.STATE_EMERGENCY_ONLY:
phoneState = "STATE_EMERGENCY_ONLY";
break;
case ServiceState.STATE_IN_SERVICE:
phoneState = "STATE_IN_SERVICE";
break;
case ServiceState.STATE_OUT_OF_SERVICE:
phoneState = "STATE_OUT_OF_SERVICE";
break;
case ServiceState.STATE_POWER_OFF:
phoneState = "STATE_POWER_OFF";
break;
default:
phoneState = "Unknown";
break;
}
c.put("STATE", new CategoryValue(phoneState, "STATE", "state"));
c.put("OPERATOR_ALPHA", new CategoryValue(serviceState.getOperatorAlphaLong(), "OPERATOR_ALPHA", "operatorAlpha"));
c.put("OPERATOR_NUMERIC", new CategoryValue(serviceState.getOperatorNumeric(), "OPERATOR_NUMERIC", "operatorNumeric"));
c.put("ROAMING", new CategoryValue(Boolean.valueOf(serviceState.getRoaming()).toString(), "ROAMING", "roaming"));
c.put("NETWORK_SELECTION", new CategoryValue(serviceState.getIsManualSelection() ? "NETWORK_SELECTION" : "AUTO", "NETWORK_SELECTION", "networkSelection"));
PhoneStatus.this.add(c);
}
}, PhoneStateListener.LISTEN_SERVICE_STATE);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(xCtx, CommonErrorType.PHONE_STATUS, ex.getMessage()));
}
}
}
| 4,936 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Storage.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Storage.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* This class get all the information of the Environment
*/
public class Storage extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 3528873342443549732L;
private Properties props;
private Context context;
/**
* Indicates whether some other object is "equal to" this one
* @param obj the reference object with which to compare
* @return boolean true if the object is the same as the one given in argument
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return (!super.equals(obj));
}
/**
* Returns a hash code value for the object
* @return int a hash code value for the object
*/
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 89 * hash + (this.context != null ? this.context.hashCode() : 0);
hash = 89 * hash + (this.props != null ? this.props.hashCode() : 0);
return hash;
}
/**
* This constructor load the context and the Hardware information
* @param xCtx Context where this class work
*/
public Storage(Context xCtx) {
super(xCtx);
this.context = xCtx;
try {
props = System.getProperties();
List<List<String>> values = getPartitionInformation();
if(values!=null) {
for (int i = 0; i < values.size(); i++) {
List<String> value = values.get(i);
if(!value.isEmpty()) {
Category c = new Category("STORAGES", "storages");
c.put("DESCRIPTION", new CategoryValue("MMC", "DESCRIPTION", "description"));
c.put("DISKSIZE", new CategoryValue(value.get(2), "DISKSIZE", "disksize"));
c.put("NAME", new CategoryValue(value.get(3), "NAME", "name"));
c.put("SERIALNUMBER", new CategoryValue("", "SERIALNUMBER", "serialNumber"));
c.put("TYPE", new CategoryValue("disk", "TYPE", "type"));
this.add(c);
}
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.STORAGE, ex.getMessage()));
}
}
private List<List<String>> getPartitionInformation() {
try {
// Run the command
Process process = Runtime.getRuntime().exec("cat /proc/partitions | grep mmc");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
// Grab the results
List<List<String>> values = new ArrayList<>();
String line;
while ((line = bufferedReader.readLine()) != null) {
List<String> value = getValues(line);
if(!line.equals("") && !value.get(3).equalsIgnoreCase("name")) {
values.add(value);
}
}
return values;
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.STORAGE_PARTITION, ex.getMessage()));
}
return null;
}
private List<String> getValues(String line) {
ArrayList<String> arr = new ArrayList<>();
try {
if (!line.trim().equals("")) {
String[] arrLine = line.split(" ");
for (String anArrLine : arrLine) {
if (!anArrLine.trim().equals("")) {
arr.add(anArrLine);
}
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.STORAGE_VALUES, ex.getMessage()));
}
return arr;
}
}
| 6,080 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Bios.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Bios.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import androidx.core.content.ContextCompat;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import org.flyve.inventory.Utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.UUID;
/**
* This class get all the information of the Bios
*/
public class Bios extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = -559572118090134691L;
private static final String CPUINFO = "/proc/cpuinfo";
private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
private final Context context;
// <!ELEMENT BIOS (SMODEL, SMANUFACTURER, SSN, BDATE, BVERSION,
// BMANUFACTURER, MMANUFACTURER, MSN, MMODEL, ASSETTAG, ENCLOSURESERIAL,
// BIOSSERIAL, TYPE, SKUNUMBER)>
/**
* This constructor trigger get all the information about Bios
* @param xCtx Context where this class work
*/
public Bios(Context xCtx) {
super(xCtx);
context = xCtx;
try {
Category c = new Category("BIOS", "bios");
c.put("ASSETTAG", new CategoryValue(getAssetTag(), "ASSETTAG", "assettag"));
c.put("BDATE", new CategoryValue(getBiosDate(), "BDATE", "biosReleaseDate"));
c.put("BMANUFACTURER", new CategoryValue(getBiosManufacturer(), "BMANUFACTURER", "biosManufacturer"));
c.put("BVERSION", new CategoryValue(getBiosVersion(), "BVERSION", "biosVersion"));
c.put("MMANUFACTURER", new CategoryValue(getManufacturer(), "MMANUFACTURER", "motherBoardManufacturer"));
c.put("MMODEL", new CategoryValue(getModel(), "MMODEL", "motherBoardModel"));
c.put("MSN", new CategoryValue(getMotherBoardSerial(), "MSN", "motherBoardSerialNumber"));
c.put("SMANUFACTURER", new CategoryValue(getManufacturer(), "SMANUFACTURER", "systemManufacturer"));
c.put("SMODEL", new CategoryValue(getModel(), "SMODEL", "systemModel"));
c.put("SSN", new CategoryValue(getSystemSerialNumber(), "SSN", "systemSerialNumber"));
this.add(c);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BIOS, ex.getMessage()));
}
}
/**
* Get the Bios Date
* @return string with the date in simple format
*/
public String getBiosDate() {
String dateInfo = "N/A";
try {
dateInfo = Utils.getCatInfo("/sys/devices/virtual/dmi/id/bios_date");
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BIOS_DATE, ex.getMessage()));
}
return !dateInfo.equals("") ? dateInfo : "N/A";
}
/**
* Get the Bios Manufacturer
* @return string with the manufacturer
*/
public String getBiosManufacturer() {
String manufacturer = "N/A";
try {
manufacturer= Build.MANUFACTURER;
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BIOS_MANUFACTURER, ex.getMessage()));
}
return manufacturer;
}
/**
* Get the Bios Version
* @return string with the bootloader version
*/
public String getBiosVersion() {
String dateInfo = "N/A";
try {
dateInfo = Utils.getCatInfo("/sys/devices/virtual/dmi/id/bios_version");
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BIOS_VERSION, ex.getMessage()));
}
return !dateInfo.equals("") ? dateInfo : "N/A";
}
/**
* Get the Mother Board Manufacturer
* @return string with the manufacturer
*/
public String getManufacturer() {
String manufacturer = "N/A";
try {
manufacturer = Build.MANUFACTURER;
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BIOS_BOARD_MANUFACTURER, ex.getMessage()));
}
return manufacturer;
}
/**
* Get the Mother Board Model
* @return string with the model
*/
public String getModel() {
String model = "N/A";
try {
model = Build.MODEL;
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BIOS_MOTHER_BOARD_MODEL, ex.getMessage()));
}
return model;
}
/**
* Get the Build Tag
* @return string with the model
*/
public String getAssetTag() {
String tags = "N/A";
try {
tags = Build.TAGS;
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BIOS_TAG, ex.getMessage()));
}
return tags;
}
/**
* Get the serial mother board
* @return string with the serial mother board
*/
public String getMotherBoardSerial() {
String dateInfo = "N/A";
try {
dateInfo = Utils.getCatInfo("/sys/devices/virtual/dmi/id/board_serial");
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BIOS_MOTHER_BOARD_SERIAL, ex.getMessage()));
}
return !dateInfo.equals("") ? dateInfo : "N/A";
}
/**
* Get the System Unique Identifier
* @return string with Unique Identifier
*/
public String getSystemUniqueID() {
String uniqueID;
SharedPreferences sharedPrefs = context.getSharedPreferences(
PREF_UNIQUE_ID, Context.MODE_PRIVATE);
uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
if (uniqueID == null) {
uniqueID = UUID.randomUUID().toString().replace("-", "");
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString(PREF_UNIQUE_ID, uniqueID);
editor.apply();
}
return uniqueID;
}
/**
* Get the System serial number
* @return string with the serial number
*/
@SuppressLint("HardwareIds")
public String getSystemSerialNumber() {
String systemSerialNumber = "Unknown";
try {
//Try to get the serial by reading /proc/cpuinfo
String serial = "";
//First, use the hidden API!
//Versions < Android 7 get bad serial with Build.SERIAL
serial = getSerialFromPrivateAPI();
//Second, try to get serial number from regular API!
if (serial.equals("")) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE)
== PackageManager.PERMISSION_GRANTED) {
serial = android.os.Build.getSerial();
} else{
// Mother Board Serial Number
// Since in 2.3.3 a.k.a gingerbread
serial = Build.SERIAL;
}
//Third try to get serial number from CpuInfo
if (serial.equals("") || serial.equalsIgnoreCase(android.os.Build.UNKNOWN)) {
serial = this.getSerialNumberFromCpuInfo();
if (!serial.equals("") && !serial.equals("0000000000000000")) {
systemSerialNumber = serial;
}
}else{
systemSerialNumber = serial;
}
} else {
systemSerialNumber = serial;
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BIOS_SYSTEM_SERIAL, ex.getMessage()));
}
//serial cannot by empty
//get uuid of need
if(systemSerialNumber.equalsIgnoreCase("Unknown")
|| systemSerialNumber.equalsIgnoreCase("N/A")
|| systemSerialNumber.isEmpty()
|| systemSerialNumber.equalsIgnoreCase(android.os.Build.UNKNOWN)){
Hardware hardware = new Hardware(context);
systemSerialNumber = hardware.getUUID();
}
return systemSerialNumber;
}
/**
* This is a call to a private api to get Serial number
* @return String with a Serial Device
*/
private String getSerialFromPrivateAPI() {
String serialNumber;
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class);
get.setAccessible(true);
// (?) Lenovo Tab (https://stackoverflow.com/a/34819027/1276306)
serialNumber = (String) get.invoke(c, "gsm.sn1");
if (serialNumber.equals(""))
// Samsung Galaxy S5 (SM-G900F) : 6.0.1
// Samsung Galaxy S6 (SM-G920F) : 7.0
// Samsung Galaxy Tab 4 (SM-T530) : 5.0.2
// (?) Samsung Galaxy Tab 2 (https://gist.github.com/jgold6/f46b1c049a1ee94fdb52)
serialNumber = (String) get.invoke(c, "ril.serialnumber");
if (serialNumber.equals(""))
// Archos 133 Oxygen : 6.0.1
// Google Nexus 5 : 6.0.1
// Hannspree HANNSPAD 13.3" TITAN 2 (HSG1351) : 5.1.1
// Honor 5C (NEM-L51) : 7.0
// Honor 5X (KIW-L21) : 6.0.1
// Huawei M2 (M2-801w) : 5.1.1
// (?) HTC Nexus One : 2.3.4 (https://gist.github.com/tetsu-koba/992373)
serialNumber = (String) get.invoke(c, "ro.serialno");
if (serialNumber.equals(""))
// (?) Samsung Galaxy Tab 3 (https://stackoverflow.com/a/27274950/1276306)
serialNumber = (String) get.invoke(c, "sys.serialnumber");
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BIOS_SERIAL_PRIVATE, ex.getMessage()));
serialNumber = "";
}
return serialNumber;
}
/**
* Get the serial by reading /proc/cpuinfo
* @return String
*/
private String getSerialNumberFromCpuInfo() {
String serial = "";
try {
File f = new File(CPUINFO);
FileReader fr = null;
try {
fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr, 8 * 1024);
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("Serial")) {
InventoryLog.d(line);
String[] results = line.split(":");
serial = results[1].trim();
}
}
br.close();
fr.close();
} catch (IOException e) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BIOS_CPU_SERIAL, e.getMessage()));
} finally {
if (fr != null) {
fr.close();
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BIOS_CPU_SERIAL, ex.getMessage()));
}
return serial.trim();
}
}
| 11,512 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Hardware.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Hardware.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import android.os.Build;
import android.provider.Settings.Secure;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import org.flyve.inventory.Utils;
import org.w3c.dom.Document;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/**
* This class get all the information of the Environment
*/
public class Hardware extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 3528873342443549732L;
// <!ELEMENT HARDWARE (USERID, OSVERSION, PROCESSORN, OSCOMMENTS,
// NAME, PROCESSORS, SWAP, ETIME, TYPE, OSNAME, IPADDR,
// WORKGROUP, DESCRIPTION, MEMORY, UUID, DNS, LASTLOGGEDUSER,
// USERDOMAIN, DATELASTLOGGEDUSER, DEFAULTGATEWAY, VMSYSTEM, WINOWNER,
// WINPRODID, WINPRODKEY, WINCOMPANY, WINLANG, CHASSIS_TYPE, VMNAME,
// VMHOSTSERIAL, ARCHNAME)>
private Properties props;
private Context context;
private static final String OSNAME = "Android";
private ArrayList<String> userInfo = new ArrayList<>();
/**
* Indicates whether some other object is "equal to" this one
* @param obj Object the reference object with which to compare
* @return boolean true if the object is the same as the one given in argument
*/
@Override
public boolean equals(Object obj) {
return obj != null && getClass() == obj.getClass() && (!super.equals(obj));
}
/**
* Returns a hash code value for the object
* @return int a hash code value for the object
*/
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 89 * hash + (this.context != null ? this.context.hashCode() : 0);
hash = 89 * hash + (this.props != null ? this.props.hashCode() : 0);
hash = 89 * hash + (this.userInfo != null ? this.userInfo.hashCode() : 0);
return hash;
}
/**
* This constructor load the context and the Hardware information
* @param xCtx Context where this class work
*/
public Hardware(Context xCtx) {
super(xCtx);
this.context = xCtx;
props = System.getProperties();
try {
getUserInfo();
Category c = new Category("HARDWARE", "hardware");
c.put("DATELASTLOGGEDUSER", new CategoryValue(getDateLastLoggedUser(), "DATELASTLOGGEDUSER", "dateLastLoggedUser"));
c.put("LASTLOGGEDUSER", new CategoryValue(getLastLoggedUser(), "LASTLOGGEDUSER", "lastLoggedUser"));
c.put("NAME", new CategoryValue(getName(), "NAME", "name"));
c.put("OSNAME", new CategoryValue(OSNAME, "OSNAME", "osName"));
c.put("OSVERSION", new CategoryValue(getOsVersion(), "OSVERSION", "osVersion"));
c.put("ARCHNAME", new CategoryValue(getArchName(), "ARCHNAME", "archName"));
c.put("UUID", new CategoryValue(getUUID(), "UUID", "uuid"));
c.put("USERID", new CategoryValue(getUserId(), "USERID", "userid"));
c.put("MEMORY", new CategoryValue(new Memory(xCtx).getCapacity(), "MEMORY", "memory"));
this.add(c);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.HARDWARE, ex.getMessage()));
}
}
/**
* Get the if of the user logged
* @return string id user logged
*/
public String getUserId() {
return getUserTagValue("id");
}
/**
* Get the date of the last time the user logged
* @return string the date in simple format
*/
public String getDateLastLoggedUser() {
String value = "N/A";
try {
String lastLoggedIn = getUserTagValue("lastLoggedIn");
if (!"N/A".equals(lastLoggedIn)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss", Locale.getDefault());
Date resultDate = new Date(Long.parseLong(lastLoggedIn));
value = sdf.format(resultDate);
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.HARDWARE_DATE_LAST_LOGGED_USER, ex.getMessage()));
}
return value;
}
/**
* Get the name of the last logged user
* @return string the user name
*/
public String getLastLoggedUser() {
String value = "N/A";
try {
if (userInfo.size() > 0 && userInfo.get(2) != null) {
DocumentBuilder newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
String info = userInfo.get(2).trim();
Document parse = newDocumentBuilder.parse(new ByteArrayInputStream(info.getBytes()));
value = parse.getFirstChild().getTextContent();
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.HARDWARE_LAST_LOGGED_USER, ex.getMessage()));
}
return value;
}
/**
* Get the user tag of the last logged user
* @return string the user tag
*/
private String getUserTagValue(String tagName) {
String evaluate = "";
String value = "N/A";
try {
if (userInfo.size() > 0 && userInfo.get(1) != null) {
String removeChar = userInfo.get(1).replaceAll("[\"><]", "");
if (removeChar.contains("user ")) {
evaluate = removeChar.replaceAll(" ", ",").trim();
}
String[] splitValues = evaluate.split(",");
Map<String, String> results = new HashMap<>();
for (String a : splitValues) {
if (a.contains("=")) {
String[] keyValues = a.split("=", 2);
String key = keyValues[0];
String valueResult = keyValues[1];
results.put(key, valueResult);
}
}
return results.get(tagName) == null ? "N/A" : results.get(tagName);
} else {
return value;
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.HARDWARE_USER_TAG, ex.getMessage()));
}
return value;
}
/**
* Get user info of the last logged user from an XML
*/
private void getUserInfo() {
userInfo = new ArrayList<>();
try {
String temp;
String[] values = {"su", "cat /data/system/users/0.xml\n", "exit\n"};
BufferedReader catInfo = Utils.getBufferedSequentialCatInfo(values);
while ((temp = catInfo.readLine()) != null) {
userInfo.add(temp);
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.HARDWARE_USER_INFO, ex.getMessage()));
}
}
/**
* Get the hardware name
* @return string with the model
*/
public String getName() {
String value = "N/A";
try {
value = Utils.getSystemProperty("net.hostname");
} catch (Exception ex) {
InventoryLog.d(InventoryLog.getMessage(context, CommonErrorType.HARDWARE_NAME, "Unable to get NAME from Utils.getSystemProperty(\"net.hostname\")"));
}
//try hidden API
if(value.trim().isEmpty()
|| value.equalsIgnoreCase(android.os.Build.UNKNOWN)
|| value.equalsIgnoreCase("N/A")){
try {
Method getString = Build.class.getDeclaredMethod("getString", String.class);
getString.setAccessible(true);
value = getString.invoke(null, "net.hostname").toString();
} catch (Exception ex) {
InventoryLog.d(InventoryLog.getMessage(context, CommonErrorType.HARDWARE_NAME, "Unable to get NAME from getString invocation on net.hostname"));
}
}
//try to construct net.hostname like android
//https://android.stackexchange.com/questions/37/how-do-i-change-the-name-of-my-android-device/60425#60425
if(!getUUID().isEmpty() && !getUUID().equalsIgnoreCase(("N/A")) && getUUID() != null){
value = "android-"+getUUID();
}
//name cannot be empty (for glpi inventory)
if(value.trim().isEmpty()
|| value.equalsIgnoreCase(android.os.Build.UNKNOWN)
|| value.equalsIgnoreCase("N/A")){
value = Build.MODEL;
}
return value.trim();
}
/**
* Get the OS version
* @return string the version
*/
public String getOsVersion() {
String value = "N/A";
try {
value = Build.VERSION.RELEASE;
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.HARDWARE_VERSION, ex.getMessage()));
}
return value;
}
/**
* Get the name of the architecture
* @return string the OS architecture
*/
public String getArchName() {
String value = "N/A";
try {
value = props.getProperty("os.arch");
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.HARDWARE_ARCH_NAME, ex.getMessage()));
}
return value;
}
/**
* Get the Universal Unique Identifier (UUID)
* @return string the Android ID
*/
public String getUUID() {
String value = "N/A";
try {
value = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.HARDWARE_UUID, ex.getMessage()));
}
return value;
}
}
| 12,102 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Drives.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Drives.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
/**
* This class get all the information of the Drives
*/
public class Drives extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 6073387379988815108L;
private final Context context;
/**
* This constructor load the context and load the Drivers information
* @param xCtx Context where this class work
*/
public Drives(Context xCtx) {
super(xCtx);
context = xCtx;
this.addStorage(Environment.getRootDirectory());
this.addStorage(Environment.getExternalStorageDirectory());
this.addStorage(Environment.getDataDirectory());
this.addStorage(Environment.getDownloadCacheDirectory());
if (System.getenv("SECONDARY_STORAGE") != null) {
this.addStorage(new File(System.getenv("SECONDARY_STORAGE")));
}
}
/**
* Add a storage to inventory
* @param f the partition to inventory
*/
private void addStorage(File f) {
try {
Category c = new Category("DRIVES", "drives");
c.put("VOLUMN", new CategoryValue(getVolume(f), "VOLUMN", "path"));
c.put("TOTAL", new CategoryValue(getTotal(f), "TOTAL", "total"));
c.put("FREE", new CategoryValue(getFreeSpace(f), "FREE", "free"));
c.put("FILESYSTEM", new CategoryValue(getFileSystem(f), "FILESYSTEM", "filesystem"));
c.put("TYPE", new CategoryValue(getType(f), "TYPE", "type"));
this.add(c);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.DRIVES, ex.getMessage()));
}
}
/**
* Get the volume of the storage
* @param f file
* @return string with the volume
*/
public String getVolume(File f) {
String fileVolume = "N/A";
try {
Process mount = Runtime.getRuntime().exec("mount");
BufferedReader bufferedFileInfo = new BufferedReader(new InputStreamReader(mount.getInputStream()));
String line;
while ((line = bufferedFileInfo.readLine()) != null) {
String[] fileInfo = line.split("\\s+");
if (fileInfo[1].contentEquals(f.getAbsolutePath())) {
fileVolume = fileInfo[0];
break;
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.DRIVES_VOLUME, ex.getMessage()));
}
return fileVolume;
}
/**
* Get the total space of the drive
* @param f file
* @return string the total space
*/
public String getTotal(File f) {
String val = "N/A";
try {
Long total = f.getTotalSpace();
int toMega = 1048576;
total = total / toMega;
val = total.toString();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.DRIVES_TOTAL, ex.getMessage()));
}
return val;
}
/**
* Get the free space of the drive
* @param f file
* @return string the free space
*/
public String getFreeSpace(File f) {
String value = "N/A";
try {
StatFs stat = new StatFs(f.getPath());
long bytesAvailable;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
bytesAvailable = stat.getBlockSizeLong() * stat.getAvailableBlocksLong();
} else {
bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks();
}
long valueBytes = bytesAvailable / (1024 * 1024);
value = String.valueOf(valueBytes);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.DRIVES_FREE_SPACE, ex.getMessage()));
}
return value;
}
/**
* Get the filesystem space of the drive
* @param f file
* @return string the filesystem
*/
public String getFileSystem(File f) {
String fileSystem = "N/A";
try {
Process mount = Runtime.getRuntime().exec("mount");
BufferedReader bufferedFileInfo = new BufferedReader(new InputStreamReader(mount.getInputStream()));
String line;
while ((line = bufferedFileInfo.readLine()) != null) {
String[] fileInfo = line.split("\\s+");
if (fileInfo[1].contentEquals(f.getAbsolutePath())) {
fileSystem = fileInfo[2];
break;
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.DRIVES_FILE_SYSTEM, ex.getMessage()));
}
return fileSystem;
}
/**
* Get the filesystem mount point
* @param f file
* @return string filesystem mount point
*/
public String getType(File f) {
String pointMounted = "N/A";
try {
Process mount = Runtime.getRuntime().exec("mount");
BufferedReader bufferedFileInfo = new BufferedReader(new InputStreamReader(mount.getInputStream()));
String line;
while ((line = bufferedFileInfo.readLine()) != null) {
String[] fileInfo = line.split("\\s+");
if (fileInfo[1].contentEquals(f.getAbsolutePath())) {
pointMounted = fileInfo[1];
break;
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.DRIVES_TYPE, ex.getMessage()));
}
return pointMounted;
}
}
| 7,849 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
User.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/User.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import android.os.Build;
import android.os.UserManager;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import java.util.Properties;
/**
* This class get all the information of the Environment
*/
public class User extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 3528873342443549732L;
private Properties props;
private Context context;
/**
* Indicates whether some other object is "equal to" this one
* @param obj the reference object with which to compare
* @return boolean true if the object is the same as the one given in argument
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return (!super.equals(obj));
}
/**
* Returns a hash code value for the object
* @return int a hash code value for the object
*/
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 89 * hash + (this.context != null ? this.context.hashCode() : 0);
hash = 89 * hash + (this.props != null ? this.props.hashCode() : 0);
return hash;
}
/**
* This constructor load the context and the Hardware information
* @param xCtx Context where this class work
*/
public User(Context xCtx) {
super(xCtx);
this.context = xCtx;
try {
props = System.getProperties();
Category c = new Category("USER", "user");
c.put("LOGIN", new CategoryValue(getUserName(), "LOGIN", "login"));
this.add(c);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.USER, ex.getMessage()));
}
}
/**
* Get the user name
* @return string userName
*/
public String getUserName() {
String userName = "N/A";
try {
if (Build.VERSION.SDK_INT >= 17) {
UserManager userMgr = (UserManager) context.getSystemService(Context.USER_SERVICE);
if (userMgr != null) {
try {
// validate permission exception
userName = userMgr.getUserName();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.USER_NAME, ex.getMessage()));
userName = Build.USER;
}
} else {
userName = Build.USER;
}
} else {
userName = Build.USER;
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.USER_NAME, ex.getMessage()));
}
return userName;
}
}
| 4,800 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Usb.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Usb.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import org.flyve.inventory.usbManager.SysBusUsbDevice;
import org.flyve.inventory.usbManager.SysBusUsbManager;
import java.util.Map;
/**
* This class get all the information of the USB
*/
public class Usb extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 4846706700566208666L;
private SysBusUsbDevice usb;
private final Context context;
/**
* This constructor load the context and the Usb information
* @param xCtx Context where this class work
*/
public Usb(Context xCtx) {
super(xCtx);
context = xCtx;
//USB inventory comes with SDK level 12 !
try {
usb = getSysBusUsbDevice();
Category c = new Category("USBDEVICES", "usbDevices");
c.put("CLASS", new CategoryValue(getServiceClass(), "CLASS", "class"));
c.put("PRODUCTID", new CategoryValue(getPid(), "PRODUCTID", "productId"));
c.put("VENDORID", new CategoryValue(getVid(), "VENDORID", "vendorId"));
c.put("SUBCLASS", new CategoryValue(getDeviceSubClass(), "SUBCLASS", "subClass"));
c.put("MANUFACTURER", new CategoryValue(getReportedProductName(), "MANUFACTURER", "manufacturer"));
c.put("CAPTION", new CategoryValue(getUsbVersion(), "CAPTION", "caption"));
c.put("SERIAL", new CategoryValue(getSerialNumber(), "SERIAL", "serial"));
this.add(c);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.USB, ex.getMessage()));
}
}
private SysBusUsbDevice getSysBusUsbDevice() {
try {
SysBusUsbManager usbManager = new SysBusUsbManager("/sys/bus/usb/devices/");
Map<String, SysBusUsbDevice> devices = usbManager.getUsbDevices();
return devices.get("usb1");
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.USB_SYS_BUS, ex.getMessage()));
}
return null;
}
public String getServiceClass() {
String value = "N/A";
try {
if (usb != null) value = usb.getServiceClass();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.USB_SERVICE, ex.getMessage()));
}
return value;
}
public String getPid() {
String value = "N/A";
try {
value = usb.getPid();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.USB_PID, ex.getMessage()));
}
return value;
}
public String getVid() {
String value = "N/A";
try {
value = usb.getVid();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.USB_VID, ex.getMessage()));
}
return value;
}
public String getDeviceSubClass() {
String value = "N/A";
try {
value = usb.getDeviceSubClass();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.USB_DEVICE_SUB_CLASS, ex.getMessage()));
}
return value;
}
public String getReportedProductName() {
String value = "N/A";
try {
value = usb.getReportedProductName();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.USB_REPORTED_PRODUCT_NAME, ex.getMessage()));
}
return value;
}
public String getUsbVersion() {
String value = "N/A";
try {
value = usb.getUsbVersion();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.USB_USB_VERSION, ex.getMessage()));
}
return value;
}
public String getSerialNumber() {
String value = "N/A";
try {
value = usb.getSerialNumber();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.USB_SERIAL_NUMBER, ex.getMessage()));
}
return value;
}
}
| 5,569 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Bluetooth.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Bluetooth.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
/**
* This class get all the information of the Bluetooth
*/
public class Bluetooth extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 3252750764653173048L;
private BluetoothAdapter adapter;
private final Context context;
/**
* Indicates whether some other object is "equal to" this one
* @param obj Object the reference object with which to compare
* @return boolean true if the object is the same as the one given in argument
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return (!super.equals(obj));
}
/**
* Returns a hash code value for the object
* @return int a hash code value for the object
*/
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 89 * hash + (this.adapter != null ? this.adapter.hashCode() : 0);
return hash;
}
/**
* This constructor get all the information about Bluetooth
* @param xCtx Context where this class work
*/
public Bluetooth(Context xCtx) {
super(xCtx);
context = xCtx;
adapter = BluetoothAdapter.getDefaultAdapter();
if(adapter != null) {
try {
Category c = new Category("BLUETOOTH_ADAPTER", "bluetoothAdapter");
// The hardware address of the local Bluetooth adapter.
c.put("HMAC", new CategoryValue(getHardwareAddress(), "HMAC", "hardwareAddress"));
// This name is visible to remote Bluetooth devices.
c.put("NAME", new CategoryValue(getName(), "NAME", "name"));
this.add(c);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BLUETOOTH, ex.getMessage()));
}
}
}
/**
* Get the hardware address of the local bluetooth adapter
* @return string with the hardware address
*/
public String getHardwareAddress() {
String address = "N/A";
try {
address = adapter.getAddress();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BLUETOOTH_HARDWARE_ADDRESS, ex.getMessage()));
}
return address;
}
/**
* Get the adapter name
* @return string the name of the adapter
*/
public String getName() {
String name = "N/A";
try {
name = adapter.getName();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.BLUETOOTH_NAME, ex.getMessage()));
}
return name;
}
}
| 4,796 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Software.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Software.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import org.flyve.inventory.Utils;
import java.io.File;
import java.util.List;
/**
* This class get all the information of the Software
*/
public class Software extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 4846706700566208666L;
private static final String FROM = "Android";
private PackageManager packageManager;
private final Context context;
/**
* Indicates whether some other object is "equal to" this one
* @param obj the reference object with which to compare
* @return boolean true if the object is the same as the one given in argument
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return (!super.equals(obj));
}
/**
* Returns a hash code value for the object
* @return int a hash code value for the object
*/
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 89 * hash + (this.packageManager != null ? this.packageManager.hashCode() : 0);
return hash;
}
/**
* This constructor get the information about Software
* @param xCtx Context where this class work
*/
public Software(Context xCtx) {
super(xCtx);
context = xCtx;
try {
packageManager = xCtx.getPackageManager();
List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo p : packages) {
Category c = new Category("SOFTWARES", "softwares");
String softwareName = getName(p);
if (softwareName.isEmpty() || softwareName.equals("N/A")) {
continue; //if softwareName is empty then continue
}
c.put("NAME", new CategoryValue(softwareName, "NAME", "name"));
c.put("COMMENTS", new CategoryValue(getPackage(p), "COMMENTS", "comments"));
c.put("VERSION", new CategoryValue(getVersion(p), "VERSION", "version"));
c.put("FILESIZE", new CategoryValue(getFileSize(p), "FILESIZE", "fileSize"));
c.put("FROM", new CategoryValue(FROM, "FROM", "from"));
c.put("INSTALLDATE", new CategoryValue(getInstallDate(p), "INSTALLDATE", "installDate"));
c.put("FOLDER", new CategoryValue(getFolder(p), "FOLDER", "folder"));
c.put("NO_REMOVE", new CategoryValue(getRemovable(p), "NO_REMOVE", "no_remove"));
c.put("USERID", new CategoryValue(getUserID(p), "USERID", "userid"));
this.add(c);
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SOFTWARE, ex.getMessage()));
}
}
/**
* Get the name of the application
* @param p ApplicationInfo
* @return string the application name
*/
public String getName(ApplicationInfo p) {
String value = "N/A";
try {
value = packageManager.getApplicationLabel(p).toString();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SOFTWARE_NAME, ex.getMessage()));
}
return value;
}
public String getPackage(ApplicationInfo p) {
String value = "N/A";
try {
value = p.packageName;
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SOFTWARE_PACKAGE, ex.getMessage()));
}
return value;
}
/**
* Get the version of the application
* @param p ApplicationInfo
* @return string the application version
*/
public String getInstallDate(ApplicationInfo p) {
String mInstalled = "N/A";
try {
PackageInfo pi = packageManager.getPackageInfo(p.packageName, PackageManager.GET_META_DATA);
mInstalled = Utils.convertTime(pi.firstInstallTime, "dd/MM/yyyy");
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SOFTWARE_INSTALL_DATE, ex.getMessage()));
}
return mInstalled;
}
/**
* Get the version of the application
* @param p ApplicationInfo
* @return string the application version
*/
public String getVersion(ApplicationInfo p) {
String mVersion = "N/A";
try {
PackageInfo pi = packageManager.getPackageInfo(p.packageName, PackageManager.GET_META_DATA);
mVersion = pi.versionName;
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SOFTWARE_VERSION, ex.getMessage()));
}
return mVersion;
}
/**
* Get the size of the application
* @param p ApplicationInfo
* @return string the sum of the cache, code and data size of the application
*/
public String getFileSize(ApplicationInfo p) {
String value = "N/A";
try {
File file = new File(packageManager.getApplicationInfo(p.packageName, 0).publicSourceDir);
value = String.valueOf(file.length());
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SOFTWARE_FILE_SIZE, ex.getMessage()));
}
return value;
}
/**
* Get the folder of the application
* @param p ApplicationInfo
* @return string folder of the application
*/
public String getFolder(ApplicationInfo p) {
String value = "N/A";
try {
File file = new File(packageManager.getApplicationInfo(p.packageName, 0).publicSourceDir);
value = file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("/"));
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SOFTWARE_FOLDER, ex.getMessage()));
}
return value;
}
/**
* Get if is removable the application
* @param p ApplicationInfo
* @return string 0 the application be uninstalled or 1 the application can be uninstalled
*/
public String getRemovable(ApplicationInfo p) {
String value = "N/A";
try {
File file = new File(packageManager.getApplicationInfo(p.packageName, 0).publicSourceDir);
boolean vendor = file.getAbsolutePath().contains("/system/vendor/operator/");
boolean data = file.getAbsolutePath().contains("/data/app/");
boolean system = file.getAbsolutePath().contains("/system/app/");
boolean systemPriv = file.getAbsolutePath().contains("/system/priv-app/");
boolean framework = file.getAbsolutePath().contains("/system/framework/");
boolean plugin = file.getAbsolutePath().contains("/system/plugin/");
if (vendor || data) {
value = "1";
} else if (system || systemPriv || framework || plugin) {
value = "0";
} else {
value = "1";
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SOFTWARE_REMOVABLE, ex.getMessage()));
}
return value;
}
/**
* Get the userId of the application
* @param p ApplicationInfo
* @return string userId of the application
*/
public String getUserID(ApplicationInfo p) {
String value = "N/A";
try {
value = String.valueOf(p.uid);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SOFTWARE_USER_ID, ex.getMessage()));
}
return value;
}
}
| 9,953 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Controllers.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Controllers.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
/**
* This class get all the information of the Controllers
*/
public class Controllers extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 6791259866128400637L;
private final Context context;
/**
* This constructor trigger get all the information about Controllers
* @param xCtx Context where this class work
*/
public Controllers(Context xCtx) {
super(xCtx);
context = xCtx;
try {
ArrayList<String> drivers = getDrivers();
if (drivers.size() > 0) {
for (int i = 0; i < drivers.size(); i++) {
Category c = new Category("CONTROLLERS", "controllers");
c.put("DRIVER", new CategoryValue(drivers.get(i), "DRIVER", "driver"));
this.add(c);
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CONTROLLERS, ex.getMessage()));
}
}
/**
* Get the name Driver
* @return string name Driver
*/
public ArrayList<String> getDrivers() {
ArrayList<String> arrayList = new ArrayList<>();
try {
ArrayList<String> arrayList2 = new ArrayList<>();
File file = new File("/sys/bus/platform/drivers/");
File[] listFiles = file.listFiles();
if (listFiles != null) {
for (File file2 : listFiles) {
if (file2.isDirectory()) {
String name = file2.getName();
String a = filterEmptyFile(file2);
if (a == null || a.isEmpty()) {
arrayList2.add(name);
} else {
arrayList.add(name);
}
}
}
if (arrayList.isEmpty()) {
arrayList.addAll(arrayList2);
}
Collections.sort(arrayList);
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CONTROLLERS_DRIVERS, ex.getMessage()));
}
return arrayList;
}
private String filterEmptyFile(File file) {
String value = "N/A";
try {
File[] listFiles = file.listFiles();
if (listFiles == null) {
return value;
}
for (File file2 : listFiles) {
if (file2.isDirectory()) {
String name = file2.getName();
if (!("bind".equals(name) || "unbind".equals(name) || "uevent".equals(name))) {
value = name;
}
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CONTROLLERS_FILE, ex.getMessage()));
}
return value;
}
}
| 5,023 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Jvm.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Jvm.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import java.util.Properties;
/**
* This class get all the information of the Java Virtual Machine
*/
public class Jvm extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 3291981487537599599L;
private final Context context;
/**
* This constructor load the context and the Java Virtual Machine information
* @param xCtx Context where this class work
*/
public Jvm(Context xCtx) {
super(xCtx);
context = xCtx;
try {
Category c = new Category("JVMS", "jvms");
Properties props = System.getProperties();
c.put("NAME", new CategoryValue(getName(props), "NAME", "name"));
c.put("LANGUAGE", new CategoryValue(getLanguage(props), "LANGUAGE", "language"));
c.put("VENDOR", new CategoryValue(getVendor(props), "VENDOR", "vendor"));
c.put("RUNTIME", new CategoryValue(getRuntime(props), "RUNTIME", "runtime"));
c.put("HOME", new CategoryValue(getHome(props), "HOME", "home"));
c.put("VERSION", new CategoryValue(getVersion(props), "VERSION", "version"));
c.put("CLASSPATH", new CategoryValue(getClasspath(props), "CLASSPATH", "classPath"));
this.add(c);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.JVM, ex.getMessage()));
}
}
/**
* Get the name of the Java Virtual Machine (JVM)
* @param props Properties
* @return string the JVM implementation name
*/
public String getName(Properties props) {
String value = "N/A";
try {
value = props.getProperty("java.vm.name");
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.JVM_NAME, ex.getMessage()));
}
return value;
}
/**
* Get the vendor of the JVM
* @param props Properties
* @return string the JVM vendor
*/
public String getVendor(Properties props) {
String value = "N/A";
try {
value = props.getProperty("java.vm.vendor");
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.JVM_VENDOR, ex.getMessage()));
}
return value;
}
/**
* Get the language
* @param props Properties
* @return string the JVM locale language
*/
public String getLanguage(Properties props) {
String language = "N/A";
try {
language = props.getProperty("user.language");
language += "_";
language += props.getProperty("user.region");
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.JVM_LANGUAGE, ex.getMessage()));
}
return language;
}
/**
* Get the runtime version
* @param props Properties
* @return string the java runtime version
*/
public String getRuntime(Properties props) {
String value = "N/A";
try {
value = props.getProperty("java.runtime.version");
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.JVM_RUNTIME, ex.getMessage()));
}
return value;
}
/**
* Get the java directory
* @param props Properties
* @return string the installation directory
*/
public String getHome(Properties props) {
String value = "N/A";
try {
value = props.getProperty("java.home");
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.JVM_HOME, ex.getMessage()));
}
return value;
}
/**
* Get the JVM version
* @param props Properties
* @return string the JVM implementation version
*/
public String getVersion(Properties props) {
String value = "N/A";
try {
value = props.getProperty("java.vm.version");
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.JVM_VERSION, ex.getMessage()));
}
return value;
}
/**
* Get the java class path
* @param props Properties
* @return string the class path
*/
public String getClasspath(Properties props) {
String value = "N/A";
try {
value = props.getProperty("java.class.path");
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.JVM_CLASS_PATH, ex.getMessage()));
}
return value;
}
}
| 6,646 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Inputs.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Inputs.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import android.content.res.Configuration;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
/**
* This class get all the information of the Inputs
*/
public class Inputs extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 4846706700566208666L;
private Configuration config;
private final Context context;
/**
* Indicates whether some other object is "equal to" this one
* @param obj Object the reference object with which to compare
* @return boolean true if the object is the same as the one given in argument
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return (!super.equals(obj));
}
/**
* Returns a hash code value for the object
* @return int a hash code value for the object
*/
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 89 * hash + (this.config != null ? this.config.hashCode() : 0);
return hash;
}
/**
* This constructor load the context and the Inputs information
* @param xCtx Context where this class work
*/
public Inputs(Context xCtx) {
super(xCtx);
context = xCtx;
config = context.getResources().getConfiguration();
try {
if (getKeyboard()) {
Category c = new Category("INPUTS", "inputs");
c.put("CAPTION", new CategoryValue("Keyboard", "CAPTION", "caption"));
c.put("DESCRIPTION", new CategoryValue("Keyboard", "DESCRIPTION", "description"));
c.put("TYPE", new CategoryValue("Keyboard", "TYPE", "type"));
this.add(c);
}
Category c = new Category("INPUTS", "inputs");
c.put("CAPTION", new CategoryValue("Touch Screen", "CAPTION", "caption"));
c.put("DESCRIPTION", new CategoryValue("Touch Screen", "DESCRIPTION", "description"));
c.put("TYPE", new CategoryValue(getTouchscreen(), "TYPE", "type"));
this.add(c);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.INPUTS, ex.getMessage()));
}
}
/**
* Get the keyboard
* @return string if the device has a hardware keyboard
*/
public Boolean getKeyboard() {
Boolean val = false;
try {
switch (config.keyboard) {
case Configuration.KEYBOARD_QWERTY:
case Configuration.KEYBOARD_12KEY:
val = true;
break;
case Configuration.KEYBOARD_NOKEYS:
default:
val = false;
break;
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.INPUTS_KEY_BOARD, ex.getMessage()));
}
return val;
}
/**
* Get the touchscreen
* @return string the type of screen the device has
*/
public String getTouchscreen() {
String val = "N/A";
try {
switch (config.touchscreen) {
case Configuration.TOUCHSCREEN_STYLUS:
val = "STYLUS";
break;
case Configuration.TOUCHSCREEN_FINGER:
val = "FINGER";
break;
case Configuration.TOUCHSCREEN_NOTOUCH:
val = "NOTOUCH";
break;
default:
val = "N/A";
break;
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.INPUTS_TOUCH_SCREEN, ex.getMessage()));
}
return val;
}
}
| 5,086 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Cpus.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Cpus.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import org.flyve.inventory.Utils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Map;
/**
* This class get all the information of the Cpus
*/
public class Cpus extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 4846706700566208666L;
private static final String CPUINFO = "/proc/cpuinfo";
private static final String CPUINFO_MAX_FREQ = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq";
private String cpuFamily;
private String cpuManufacturer;
private final Context context;
/**
* This constructor trigger get all the information about Cpus
* @param xCtx Context where this class work
*/
public Cpus(Context xCtx) {
super(xCtx);
context = xCtx;
cpuFamily = Utils.loadJSONFromAsset(context, "cpu_family.json");
cpuManufacturer = Utils.loadJSONFromAsset(context, "cpu_manufacturer.json");
try {
Category c = new Category("CPUS", "cpus");
c.put("ARCH", new CategoryValue(getArch(), "ARCH", "arch"));
c.put("CORE", new CategoryValue(getCPUCore(), "CORE", "core"));
c.put("FAMILYNAME", new CategoryValue(getFamilyName(), "FAMILYNAME", "familyname"));
c.put("FAMILYNUMBER", new CategoryValue(getFamilyNumber(), "FAMILYNUMBER", "familynumber"));
c.put("MANUFACTURER", new CategoryValue(getManufacturer(), "MANUFACTURER", "manufacturer"));
c.put("MODEL", new CategoryValue(getModel(), "MODEL", "model"));
c.put("NAME", new CategoryValue(getCpuName(), "NAME", "name"));
c.put("SPEED", new CategoryValue(getCpuFrequency(), "SPEED", "cpuFrequency"));
c.put("THREAD", new CategoryValue(getCpuThread(), "THREAD", "thread"));
this.add(c);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CPU, ex.getMessage()));
}
}
/**
* Get the CPU Number Core
*
* @return String with the Cpu Core
*/
public String getCPUCore() {
int value = 0;
try {
String a = Utils.getCatInfo("/sys/devices/system/cpu/present");
if (!a.equals("")) {
if (a.contains("-")) {
value = Integer.parseInt(a.split("-")[1]);
}
return String.valueOf(++value);
} else {
return String.valueOf(Runtime.getRuntime().availableProcessors());
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CPU_CORE, ex.getMessage()));
}
return String.valueOf(value);
}
/**
* Get the CPU Architecture
*
* @return String with the Cpu Architecture
*/
public String getArch() {
String value = "N/A";
try {
value = System.getProperty("os.arch");
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CPU_ARCH, ex.getMessage()));
}
return value;
}
/**
* Get the CPU Family Name
*
* @return String with the Cpu Family Name
*/
public String getFamilyName() {
String value = "N/A";
try {
Map<String, String> cpuInfo = Utils.getCatMapInfo("/proc/cpuinfo");
String shortFamily = Utils.getValueMapInfo(cpuInfo, "CPU part");
if (!"".equals(shortFamily)) {
JSONArray jr = new JSONArray(cpuFamily);
for (int i = 0; i < jr.length(); i++) {
JSONObject c = jr.getJSONObject(i);
String id = c.getString("id");
if (id.startsWith(shortFamily)) {
value = c.getString("name");
break;
}
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CPU_FAMILY_NAME, ex.getMessage()));
}
return value;
}
/**
* Get the CPU Family Name
*
* @return String with the Cpu Family Name
*/
public String getFamilyNumber() {
String value = "N/A";
try {
Map<String, String> cpuInfo = Utils.getCatMapInfo("/proc/cpuinfo");
String cpuFamily = Utils.getValueMapInfo(cpuInfo, "cpu family").trim();
if (!"".equals(cpuFamily)) {
value = cpuFamily;
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CPU_FAMILY_NUMBER, ex.getMessage()));
}
return value;
}
/**
* Get the CPU Manufacturer
*
* @return String with the Cpu Manufacturer
*/
public String getManufacturer() {
String value = "N/A";
try {
String cpuPart = Utils.getSystemProperty("ro.board.platform").trim();
JSONArray jr = new JSONArray(cpuManufacturer);
for (int i = 0; i < jr.length(); i++) {
JSONObject c = jr.getJSONObject(i);
JSONArray ids = c.getJSONArray("id");
for (int j = 0; j < ids.length(); j++) {
String idObject = ids.getString(j);
if (cpuPart.toLowerCase().startsWith(idObject)) {
value = c.getString("name");
break;
}
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CPU_MANUFACTURER, ex.getMessage()));
}
return value;
}
/**
* Get the CPU Model
*
* @return String with the Cpu Model
*/
public String getModel() {
String value = "N/A";
try {
Map<String, String> cpuInfo = Utils.getCatMapInfo("/proc/cpuinfo");
String hardware = Utils.getValueMapInfo(cpuInfo, "Hardware").trim();
if (!"".equals(hardware)){
value = hardware;
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CPU_MODEL, ex.getMessage()));
}
return value;
}
/**
* Get the CPU Name
* @return String with the name
*/
public String getCpuName() {
String value = "N/A";
try {
Map<String, String> cpuInfo = Utils.getCatMapInfo("/proc/cpuinfo");
String cpuName = Utils.getValueMapCase(cpuInfo, "Processor").trim();
if (!"".equals(cpuName)){
value = cpuName;
} else {
cpuName = Utils.getValueMapCase(cpuInfo, "model name").trim();
if (!"".equals(cpuName)){
value = cpuName;
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CPU_NAME, ex.getMessage()));
}
return value;
}
/**
* Get the CPU Frequency
* @return String with the Cpu Frequency
*/
public String getCpuFrequency() {
String cpuFrequency = "N/A";
try {
RandomAccessFile reader = null;
try {
reader = new RandomAccessFile(CPUINFO_MAX_FREQ, "r");
cpuFrequency = String.valueOf(Integer.valueOf(reader.readLine()) / 1000);
reader.close();
} catch (IOException e) {
InventoryLog.e(e.getMessage());
} finally {
if (reader != null) {
reader.close();
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CPU_FREQUENCY, ex.getMessage()));
}
return cpuFrequency;
}
/**
* Gets the number of threads available in this device.é
* @return The number of threads
*/
public String getCpuThread() {
String value = "N/A";
try {
value = String.valueOf(Runtime.getRuntime().availableProcessors());
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CPU_THREAD, ex.getMessage()));
}
return value;
}
}
| 10,396 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Category.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Category.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.os.Build;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* This class create a node of the XML
*/
public class Category extends LinkedHashMap<String, CategoryValue> {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 6443019125036309325L;
private String mType;
private String mtagName;
/**
* Indicates whether some other object is "equal to" this one.
* @param obj Object the reference object with which to compare.
* @return boolean True or false
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return (!super.equals(obj));
}
/**
* Returns a hash code value for the object.
* @return int a hash code value for this object.
*/
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 89 * hash + (this.mType != null ? this.mType.hashCode() : 0);
return hash;
}
/**
* This constructor load the Context of the instance and the name of the node in XML
* @param xType String name of the node
* @param tagName String name of the tag
*/
public Category(String xType, String tagName) {
mType = xType;
mtagName = tagName;
}
/**
* Return the type of category
* @return String with the category
*/
public String getType() {
return mType;
}
/**
* Return the name that will appear on json node
* @return String with the category
*/
public String getTagName() {
return mtagName;
}
/**
* Put a key, value on a LinkedHashMap object
*
* @param key key String
* @param value value String
* @return String
*/
public CategoryValue put(String key, CategoryValue value) {
//Do not add value if it's null, blank or "unknow"
if (value != null) {
if (value.getCategory() == null) {
String s = value.getValue();
if (s != null && !s.equals(Build.UNKNOWN)){
if(s.equalsIgnoreCase("N/A") || s.equalsIgnoreCase("N\\/A")){
value.setValue("");
}
return super.put(key, value);
} else if (value.getValues() != null && value.getValues().size() > 0) {
return super.put(key, value);
} else {
return null;
}
} else {
return super.put(key, value);
}
} else {
return null;
}
}
/**
* This is a public function that create a XML node with a XmlSerializer object
* @param serializer object
*/
public void toXML(XmlSerializer serializer) {
try {
serializer.startTag(null, mType);
for (Map.Entry<String, CategoryValue> entry : this.entrySet()) {
setXMLValues(serializer, entry);
}
serializer.endTag(null, mType);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(String.valueOf(CommonErrorType.CATEGORY_TO_XML), ex.getMessage()));
}
}
public void toXMLWithoutPrivateData(XmlSerializer serializer) {
try {
serializer.startTag(null, mType);
for (Map.Entry<String, CategoryValue> entry : this.entrySet()) {
if(this.get(entry.getKey()).isPrivate() != null
&& !this.get(entry.getKey()).isPrivate()) {
setXMLValues(serializer, entry);
}
}
serializer.endTag(null, mType);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(String.valueOf(CommonErrorType.CATEGORY_TO_XML_WITHOUT_PRIVATE), ex.getMessage()));
}
}
private void setXMLValues(XmlSerializer serializer, Map.Entry<String, CategoryValue> data) throws IOException {
CategoryValue categoryValue = this.get(data.getKey());
if (categoryValue.getCategory() == null) {
/* If is a normal value */
if (categoryValue.getValues() == null || categoryValue.getValues().size() <= 0) {
String xmlName = categoryValue.getXmlName();
String value = categoryValue.getValue();
Boolean hasCDATA = categoryValue.hasCDATA();
setChildXMLValue(serializer, xmlName, value, hasCDATA);
/* If is a list of values */
} else {
for (String value : categoryValue.getValues()) {
String xmlName = categoryValue.getXmlName();
Boolean hasCDATA = categoryValue.hasCDATA();
setChildXMLValue(serializer, xmlName, value, hasCDATA);
}
}
/* If is a Category embed */
} else {
Category category = categoryValue.getCategory();
serializer.startTag(null, category.getType());
if (categoryValue.getValues() != null && categoryValue.getValues().size() > 0) {
for (Entry<String, CategoryValue> entries : category.entrySet()) {
String xmlName = entries.getKey();
for (String value : category.get(xmlName).getValues()) {
setChildXMLValue(serializer, xmlName, value, false);
}
}
} else {
for (Entry<String, CategoryValue> entries : category.entrySet()) {
String xmlName = entries.getKey();
String value = category.get(xmlName).getValue();
setChildXMLValue(serializer, xmlName, value, false);
}
}
serializer.endTag(null, category.getType());
}
}
private void setChildXMLValue(XmlSerializer serializer, String xmlName, String xmlValue, boolean hasCData) throws IOException {
serializer.startTag(null, xmlName);
String textValue;
textValue = hasCData ? "<![CDATA[" + String.valueOf(xmlValue) + "]]>" : String.valueOf(xmlValue);
serializer.text(textValue);
serializer.endTag(null, xmlName);
}
/**
* This is a public function that create a JSON
* @return JSONObject
*/
public JSONObject toJSON() {
try {
JSONObject jsonCategories = new JSONObject();
for (Map.Entry<String,CategoryValue> entry : this.entrySet()) {
setJSONValues(jsonCategories, entry);
}
return jsonCategories;
} catch ( Exception ex ) {
InventoryLog.e(InventoryLog.getMessage(String.valueOf(CommonErrorType.CATEGORY_TO_JSON), ex.getMessage()));
return new JSONObject();
}
}
public JSONObject toJSONWithoutPrivateData() {
try {
JSONObject jsonCategories = new JSONObject();
for (Map.Entry<String,CategoryValue> entry : this.entrySet()) {
if(this.get(entry.getKey()).isPrivate() != null
&& !this.get(entry.getKey()).isPrivate()) {
setJSONValues(jsonCategories, entry);
}
}
return jsonCategories;
} catch ( Exception ex ) {
InventoryLog.e(InventoryLog.getMessage(String.valueOf(CommonErrorType.CATEGORY_TO_JSON_WITHOUT_PRIVATE), ex.getMessage()));
return new JSONObject();
}
}
private void setJSONValues(JSONObject jsonCategories, Map.Entry<String, CategoryValue> data) throws JSONException {
CategoryValue categoryValue = this.get(data.getKey());
if (data.getValue().getCategory() == null) {
if (data.getValue().getValues() == null) {
jsonCategories.put(categoryValue.getJsonName(), categoryValue.getValue());
} else {
jsonCategories.put(categoryValue.getJsonName(), categoryValue.getValues());
}
} else {
Category category = categoryValue.getCategory();
JSONObject newCategory = new JSONObject();
for (CategoryValue value : category.values()) {
if (data.getValue().getValues() == null) {
newCategory.put(value.getJsonName(), value.getValue());
} else {
newCategory.put(value.getJsonName(), value.getValues());
}
}
jsonCategories.put(category.getType(), newCategory);
}
}
}
| 10,701 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Cameras.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Cameras.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.os.Build;
import android.util.Size;
import android.util.SizeF;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import org.flyve.inventory.Utils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* This class get all the information of the Cameras
*/
public class Cameras
extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 6791259866128400637L;
private final String cameraVendors;
private final Context context;
/**
* This constructor trigger get all the information about Cameras
* @param xCtx Context where this class work
*/
public Cameras(Context xCtx) {
super(xCtx);
context = xCtx;
cameraVendors = Utils.loadJSONFromAsset(xCtx, "camera_vendors.json");
// Get resolutions of the camera
// Work on Android SDK Version >= 5
try {
int count = Camera.getNumberOfCameras();
if (count > 0) {
for (int index = 0; index < count; index++) {
Category c = new Category("CAMERAS", "cameras");
CameraCharacteristics chars = getCharacteristics(xCtx, index);
c.put("DESIGNATION", new CategoryValue("Camera "+Integer.toString(index), "DESIGNATION", "designation"));
if (chars != null) {
c.put("RESOLUTION", new CategoryValue(getResolution(chars), "RESOLUTION", "resolution"));
c.put("LENSFACING", new CategoryValue(getFacingState(chars), "LENSFACING", "lensfacing"));
c.put("FLASHUNIT", new CategoryValue(getFlashUnit(chars), "FLASHUNIT", "flashunit"));
c.put("IMAGEFORMATS", new CategoryValue(getImageFormat(chars), "IMAGEFORMATS", "imageformats"));
c.put("ORIENTATION", new CategoryValue(getOrientation(chars), "ORIENTATION", "orientation"));
c.put("FOCALLENGTH", new CategoryValue(getFocalLength(chars), "FOCALLENGTH", "focallength"));
c.put("SENSORSIZE", new CategoryValue(getSensorSize(chars), "SENSORSIZE", "sensorsize"));
}
if (!"".equals(cameraVendors)) {
c.put("MANUFACTURER", new CategoryValue(getManufacturer(index), "MANUFACTURER", "manufacturer"));
}
c.put("RESOLUTIONVIDEO", new CategoryValue(getVideoResolution(index), "RESOLUTIONVIDEO", "resolutionvideo"));
c.put("SUPPORTS", new CategoryValue("N/A", "SUPPORTS", "supports"));
c.put("MODEL", new CategoryValue(getModel(index), "MODEL", "model"));
this.add(c);
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA, ex.getMessage()));
}
}
public int getCountCamera(Context xCtx) {
int value = 0;
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CameraManager manager = (CameraManager) xCtx.getApplicationContext().getSystemService(Context.CAMERA_SERVICE);
try {
assert manager != null;
value = manager.getCameraIdList().length;
} catch (CameraAccessException e) {
InventoryLog.e(e.getMessage());
} catch (NullPointerException e) {
InventoryLog.e(e.getMessage());
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA_COUNT, ex.getMessage()));
}
return value;
}
/**
* Get info characteristics of the camera
* @param xCtx Context
* @param index number of the camera
* @return CameraCharacteristics type object
*/
public CameraCharacteristics getCharacteristics(Context xCtx, int index) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CameraManager manager = (CameraManager) xCtx.getApplicationContext().getSystemService(Context.CAMERA_SERVICE);
try {
assert manager != null;
String cameraId = manager.getCameraIdList()[index];
return manager.getCameraCharacteristics(cameraId);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA_CHARACTERISTICS, ex.getMessage()));
}
}
return null;
}
/**
* Get resolution from the camera
* @param characteristics CameraCharacteristics
* @return String resolution camera
*/
public ArrayList<String> getResolution(CameraCharacteristics characteristics) {
ArrayList<String> resolutions = new ArrayList<>();
String value = "N/A";
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
int width = 0, height = 0;
StreamConfigurationMap sizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (sizes != null) {
Size[] outputSizes = sizes.getOutputSizes(256);
if (outputSizes == null || outputSizes.length <= 0) {
Rect rect = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
if (rect != null) {
width = rect.width();
height = rect.height();
value = width + "x" + height;
resolutions.add(value);
}
} else {
for (int i = 0; i <outputSizes.length; i++ ) {
Size size = outputSizes[i];
width = size.getWidth();
height = size.getHeight();
value = width + "x" + height;
resolutions.add(value);
}
}
} else {
return resolutions;
}
} else {
return resolutions;
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA_RESOLUTION, ex.getMessage()));
}
return resolutions;
}
/**
* Get direction the camera faces relative to device screen
* @param characteristics CameraCharacteristics
* @return String The camera device faces the same direction as the device's screen
*/
public String getFacingState(CameraCharacteristics characteristics) {
String value = "N/A";
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
if (facing != null) {
switch (facing) {
case 0:
value = "FRONT";
break;
case 1:
value = "BACK";
break;
case 2:
value = "EXTERNAL";
break;
}
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA_FACING_STATE, ex.getMessage()));
}
return value;
}
/**
* Whether this camera device has a flash unit.
* @param characteristics CameraCharacteristics
* @return String 0 no available, 1 is available
*/
public String getFlashUnit(CameraCharacteristics characteristics) {
String value = "0";
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
Boolean bool = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
return bool != null ? bool ? "1" : "0" : "0";
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA_FLASH_UNIT, ex.getMessage()));
}
return value;
}
/**
* Get image format camera
* @param characteristics CameraCharacteristics
* @return String image format camera
*/
public ArrayList<String> getImageFormat(CameraCharacteristics characteristics) {
ArrayList<String> types = new ArrayList<>();
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
StreamConfigurationMap configurationMap = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (configurationMap != null) {
int[] outputFormats = configurationMap.getOutputFormats();
if (outputFormats != null) {
for (int value : outputFormats) {
String type = typeFormat(value);
if(!type.isEmpty()){
types.add(type.replaceAll("[<>]", ""));
}
}
}
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA_IMAGE_FORMAT, ex.getMessage()));
}
return types;
}
private String typeFormat(int i) {
switch (i) {
case 0:
return "UNKNOWN";
case 4:
return "RGB_565";
case 16:
return "NV16";
case 17:
return "NV21";
case 20:
return "YUY2";
case 32:
return "RAW_SENSOR";
case 34:
return "PRIVATE";
case 35:
return "YUV_420_888";
case 36:
return "RAW_PRIVATE";
case 37:
return "RAW10";
case 38:
return "RAW12";
case 39:
return "YUV_422_888";
case 40:
return "YUV_444_888";
case 41:
return "FLEX_RGB_888";
case 42:
return "FLEX_RGBA_8888";
case 256:
return "JPEG";
case 257:
return "DEPTH_POINT_CLOUD";
case 842094169:
return "YV12";
case 1144402265:
return "DEPTH16";
case 1212500294:
return "HEIC";
case 1768253795:
return "DEPTH_JPEG";
case 538982489:
return "Y8";
default:
return "";
}
}
/**
* Get orientation camera
* @param characteristics CameraCharacteristics
* @return String orientation camera
*/
public String getOrientation(CameraCharacteristics characteristics) {
String value = "N/A";
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
return String.valueOf(characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION));
} else {
return value;
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA_ORIENTATION, ex.getMessage()));
}
return value;
}
/**
* Get video resolution camera
* @param index number of camera
* @return String video resolution camera
*/
public ArrayList<String> getVideoResolution(int index) {
ArrayList<String> resolutions = new ArrayList<>();
String value;
try {
Camera open = Camera.open(index);
Camera.Parameters parameters = open.getParameters();
List<Camera.Size> supportedVideoSizes = parameters.getSupportedVideoSizes();
if (supportedVideoSizes != null) {
for (int i = 0; i <supportedVideoSizes.size(); i++ ){
Camera.Size infoSize = supportedVideoSizes.get(i);
int width = infoSize.width;
int height = infoSize.height;
value = width + "x" + height;
resolutions.add(value);
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA_VIDEO_RESOLUTION, ex.getMessage()));
}
return resolutions;
}
/**
* Get focal length camera
* @param characteristics CameraCharacteristics
* @return String focal length camera
*/
public String getFocalLength(CameraCharacteristics characteristics) {
String value = "N/A";
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
float[] fArr = characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS);
if (fArr == null) {
return null;
}
StringBuilder str = new StringBuilder();
for (float f : fArr) {
str.append(f);
}
return str.toString().trim();
} else {
return value;
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA_FOCAL_LENGTH, ex.getMessage()));
}
return value;
}
/**
* Get sensor size camera
* @param characteristics CameraCharacteristics
* @return String sensor size camera
*/
public String getSensorSize(CameraCharacteristics characteristics) {
String value = "N/A";
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
SizeF sizeF = characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE);
if (sizeF != null) {
double width = (double) sizeF.getWidth();
double height = (double) sizeF.getHeight();
if (width > 0.0d && height > 0.0d) {
return Math.round(width * 100) / 100.0d + "x" + Math.round(height * 100) / 100.0d;
}
}
}
return value;
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA_SENSOR_SIZE, ex.getMessage()));
}
return value;
}
/**
* Get manufacturer camera
* @param index number of the camera
* @return String manufacturer camera
*/
public String getManufacturer(int index) {
String value = "N/A";
try {
String infoModel = Utils.getCatInfoMultiple("/proc/hw_info/camera_info");
if ("".equals(infoModel)) {
infoModel = Utils.getCatInfoMultiple("/proc/driver/camera_info");
}
if (!"".equals(infoModel) && infoModel.contains(";")) {
String infoName = infoModel.split(";", 2)[index];
if (infoName.contains(":")) {
String infoValue = infoName.split(":", 2)[1].trim();
if (!"".equals(infoValue)) {
JSONArray jr = new JSONArray(cameraVendors);
for (int i = 0; i < jr.length(); i++) {
JSONObject c = jr.getJSONObject(i);
String id = c.getString("id");
if (infoValue.startsWith(id)) {
value = c.getString("name");
break;
}
}
}
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA_MANUFACTURER, ex.getMessage()));
}
return value;
}
/**
* Get model camera
* @param index number of the camera
* @return String model camera
*/
public String getModel(int index) {
String value = "N/A";
try {
String infoModel = Utils.getCatInfoMultiple("/proc/driver/camera_info");
if ("".equals(infoModel)) {
infoModel = Utils.getCatInfoMultiple("/proc/hw_info/camera_info");
}
if (!"".equals(infoModel)) {
infoModel = infoModel.split(";", 2)[index];
if (infoModel.contains(":"))
value = infoModel.split(":", 2)[1];
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA_MODEL, ex.getMessage()));
}
return value;
}
/**
* Get support camera
* @return String support camera
*/
public ArrayList<String> getSupportValue() {
ArrayList<String> arrayList = new ArrayList<>();
for (String s : getCatInfoCamera("/system/lib/libcameracustom.so", "SENSOR_DRVNAME_", 100)) {
arrayList.add(s.toLowerCase(Locale.US));
}
return arrayList;
}
private ArrayList<String> getCatInfoCamera(String str, String str2, int i) {
InputStream bufferedInputStream;
Throwable th;
ArrayList<String> arrayList = new ArrayList<>();
try {
File file = new File(str);
try {
byte[] bytes = str2.getBytes();
bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
try {
byte[] bArr = new byte[1];
int i2 = 0;
int i3 = 0;
int i5 = 0;
while (true) {
int read = bufferedInputStream.read(bArr);
if (read == -1) {
break;
}
int i6;
i5 += read;
byte b = bArr[0];
if (i3 == str2.length()) {
arrayList.add(((char) b) + getValueString(getListBytes(bufferedInputStream, (byte) 0)));
i3 = i5;
i2 = 0;
} else {
i6 = i2;
i2 = i3;
i3 = i6;
}
i2 = b == bytes[i2] ? i2 + 1 : 0;
if (i3 > 0 && i5 - i3 > i) {
break;
}
i6 = i3;
i3 = i2;
i2 = i6;
}
bufferedInputStream.close();
return arrayList;
} catch (Throwable th2) {
th = th2;
bufferedInputStream.close();
throw th;
}
} catch (Throwable th3) {
InventoryLog.e(th3.getMessage());
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA_BUFFERED, ex.getMessage()));
}
return arrayList;
}
private String getValueString(List<Byte> list) {
try {
if (list.size() <= 0) {
return "";
}
byte[] bArr = new byte[list.size()];
int i = 0;
for (Byte byteValue : list) {
bArr[i] = byteValue;
i++;
}
if (Build.VERSION.SDK_INT >= 19) {
return new String(bArr, StandardCharsets.UTF_8);
} else {
return new String(bArr, Charset.forName("UTF-8"));
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA_VALUE_STRING, ex.getMessage()));
}
return "";
}
private List<Byte> getListBytes(InputStream inputStream, byte b) {
byte[] bArr = new byte[1];
List<Byte> arrayList = new ArrayList<>();
try {
while (true) {
try {
int read = inputStream.read(bArr);
if (read == -1) {
break;
}
byte b2 = bArr[0];
if (b2 == b) {
break;
}
arrayList.add(b2);
} catch (IOException e) {
InventoryLog.e(e.getMessage());
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.CAMERA_LIST_BYTES, ex.getMessage()));
}
return arrayList;
}
}
| 23,781 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Simcards.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Simcards.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import java.lang.reflect.Method;
import java.util.List;
/**
* This class get all the information of the Simcards Devices
*/
public class Simcards extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = -5532129156981574844L;
private TelephonyManager mTM;
private final Context context;
/**
* Indicates whether some other object is "equal to" this one
* @param obj the reference object with which to compare
* @return boolean true if the object is the same as the one given in argument
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return (!super.equals(obj));
}
/**
* Returns a hash code value for the object
* @return int a hash code value for the object
*/
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 89 * hash + (this.mTM != null ? this.mTM.hashCode() : 0);
return hash;
}
/**
* This constructor load the context and the Simcards information
* @param xCtx Context where this class work
*/
public Simcards(Context xCtx) {
super(xCtx);
context = xCtx;
try {
/*
* Starting SimCards information retrieval
*/
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
List<SubscriptionInfo> multipleSim = getMultipleSim(xCtx);
if (multipleSim != null && multipleSim.size() > 0) {
for (SubscriptionInfo info : multipleSim) {
Category c = new Category("SIMCARDS", "simcards");
c.put("COUNTRY", new CategoryValue(info.getCountryIso(), "COUNTRY", "country"));
String operatorCode = info.getMcc() + "" + info.getMnc();
c.put("OPERATOR_CODE", new CategoryValue(operatorCode, "OPERATOR_CODE", "operatorCode"));
c.put("OPERATOR_NAME", new CategoryValue(info.getCarrierName().toString(), "OPERATOR_NAME", "operatorName"));
c.put("SERIAL", new CategoryValue(info.getIccId(), "SERIAL", "serial"));
c.put("STATE", new CategoryValue(getState(xCtx, info.getSimSlotIndex()), "STATE", "state"));
c.put("LINE_NUMBER", new CategoryValue(info.getNumber(), "LINE_NUMBER", "lineNumber"));
String subscriberId = String.valueOf(info.getSubscriptionId());
c.put("SUBSCRIBER_ID", new CategoryValue(subscriberId, "SUBSCRIBER_ID", "subscriberId"));
this.add(c);
}
}
} else {
mTM = (TelephonyManager) xCtx.getSystemService(Context.TELEPHONY_SERVICE);
assert mTM != null;
if (getState(xCtx, 0).equals("SIM_STATE_READY")) {
Category c = new Category("SIMCARDS", "simcards");
c.put("COUNTRY", new CategoryValue(getCountry(), "COUNTRY", "country"));
c.put("OPERATOR_CODE", new CategoryValue(getOperatorCode(), "OPERATOR_CODE", "operatorCode"));
c.put("OPERATOR_NAME", new CategoryValue(getOperatorName(), "OPERATOR_NAME", "operatorName"));
c.put("SERIAL", new CategoryValue(getSerial(), "SERIAL", "serial"));
c.put("STATE", new CategoryValue(getState(xCtx, 0), "STATE", "state"));
c.put("LINE_NUMBER", new CategoryValue(getLineNumber(), "LINE_NUMBER", "lineNumber"));
c.put("SUBSCRIBER_ID", new CategoryValue(getSubscriberId(), "SUBSCRIBER_ID", "subscriberId"));
this.add(c);
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SIM_CARDS, ex.getMessage()));
}
}
/**
* Get list sim card only for API equal or sup 22
* @param xCtx Context
* @return true
*/
public List<SubscriptionInfo> getMultipleSim(Context xCtx) {
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
SubscriptionManager subscriptionManager = (SubscriptionManager) xCtx.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
assert subscriptionManager != null;
return subscriptionManager.getActiveSubscriptionInfoList();
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SIM_CARDS_MULTIPLE, ex.getMessage()));
}
return null;
}
/**
* Get the state Sim by slot
* @return string the Simcard state
*/
private int getSIMStateBySlot(Context context, int slotID) {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Method getSimState = telephonyClass.getMethod("getSimState", parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotID;
Object obPhone = getSimState.invoke(telephony, obParameter);
if (obPhone != null) {
return Integer.parseInt(obPhone.toString());
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SIM_CARDS_STATE_BY_SLOT, ex.getMessage()));
}
return 0;
}
/**
* Get the country
* @return string the ISO country code
*/
public String getCountry() {
String value = "N/A";
try {
value = mTM.getSimCountryIso();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SIM_CARDS_COUNTRY, ex.getMessage()));
}
return value;
}
/**
* Get the operator code
* @return the Mobile Country Code and Mobile Network Code of the provider of the sim
*/
public String getOperatorCode() {
String value = "N/A";
try {
value = mTM.getSimOperator();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SIM_CARDS_OPERATOR_CODE, ex.getMessage()));
}
return value;
}
/**
* Get the operator name
* @return string the Service Provider Name
*/
public String getOperatorName() {
String value = "N/A";
try {
value = mTM.getSimOperatorName();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SIM_CARDS_OPERATOR_NAME, ex.getMessage()));
}
return value;
}
/**
* Get the serial number of the Sim
* @return string the serial number
*/
public String getSerial() {
String value = "N/A";
try {
value = mTM.getSimSerialNumber();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SIM_CARDS_SERIAL, ex.getMessage()));
}
return value;
}
/**
* Get state of the Simcard
* @param xCtx Context
* @param slotId int
* @return string the Simcard state
*/
public String getState(Context xCtx, int slotId) {
String mState = "N/A";
try {
int simState = mTM != null ? mTM.getSimState() : getSIMStateBySlot(xCtx, slotId);
switch (simState) {
case TelephonyManager.SIM_STATE_ABSENT:
mState = "SIM_STATE_ABSENT";
break;
case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
mState = "SIM_STATE_NETWORK_LOCKED";
break;
case TelephonyManager.SIM_STATE_PIN_REQUIRED:
mState = "SIM_STATE_PIN_REQUIRED";
break;
case TelephonyManager.SIM_STATE_PUK_REQUIRED:
mState = "SIM_STATE_PUK_REQUIRED";
break;
case TelephonyManager.SIM_STATE_READY:
mState = "SIM_STATE_READY";
break;
case TelephonyManager.SIM_STATE_UNKNOWN:
mState = "SIM_STATE_UNKNOWN";
break;
default:
mState = "SIM_STATE_UNKNOWN";
break;
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SIM_CARDS_STATE, ex.getMessage()));
}
return mState;
}
/**
* Get the line number
* @return string the phone number for line 1
*/
public String getLineNumber() {
String value = "N/A";
try {
value = mTM.getLine1Number();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SIM_CARDS_LINE_NUMBER, ex.getMessage()));
}
return value;
}
/**
* Get the subscriber ID
* @return string the unique subscriber ID
*/
public String getSubscriberId() {
String value = "N/A";
try {
value = mTM.getSubscriberId();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.SIM_CARDS_SUBSCRIBER_ID, ex.getMessage()));
}
return value;
}
}
| 11,899 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
LocationProviders.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/LocationProviders.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.app.Service;
import android.content.Context;
import android.location.LocationManager;
import android.location.LocationProvider;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import java.util.List;
/**
* This class get all the information of the Location Providers
*/
public class LocationProviders extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 6066226866162586918L;
private final Context context;
/**
* This constructor load the context and the Location Providers information
* @param xCtx Context where this class work
*/
public LocationProviders(Context xCtx) {
super(xCtx);
context = xCtx;
try {
LocationManager lLocationMgr = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE);
if (lLocationMgr != null) {
List<String> lProvidersName = lLocationMgr.getAllProviders();
for (String p : lProvidersName) {
Category c = new Category("LOCATION_PROVIDERS", "locationProviders");
LocationProvider lProvider = lLocationMgr.getProvider(p);
c.put("NAME", new CategoryValue(getName(lProvider), "NAME", "name"));
this.add(c);
}
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.LOCATION, ex.getMessage()));
}
}
/**
* Get the provider name
* @param lProvider LocationProvider
* @return string the name of the provider
*/
public String getName(LocationProvider lProvider) {
String value = "N/A";
try {
value = lProvider.getName();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.LOCATION_NAME, ex.getMessage()));
}
return value;
}
}
| 3,821 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
OperatingSystem.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/OperatingSystem.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import android.os.Build;
import android.os.SystemClock;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.CryptoUtil;
import org.flyve.inventory.InventoryLog;
import org.flyve.inventory.Utils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;
/**
* This class get all the information of the Environment
*/
public class OperatingSystem extends Categories {
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 3528873342443549732L;
private Properties props;
private Context context;
/**
* Indicates whether some other object is "equal to" this one
*
* @param obj the reference object with which to compare
* @return boolean true if the object is the same as the one given in argument
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return (!super.equals(obj));
}
/**
* Returns a hash code value for the object
*
* @return int a hash code value for the object
*/
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 89 * hash + (this.context != null ? this.context.hashCode() : 0);
hash = 89 * hash + (this.props != null ? this.props.hashCode() : 0);
return hash;
}
/**
* This constructor load the context and the Hardware information
*
* @param xCtx Context where this class work
*/
public OperatingSystem(Context xCtx) {
super(xCtx);
this.context = xCtx;
try {
props = System.getProperties();
Category c = new Category("OPERATINGSYSTEM", "operatingSystem");
String architecture = "";
String hostId = "";
ArrayList<HashMap<String, String>> arr = Utils.getDeviceProperties();
for (int i = 0; i < arr.size(); i++) {
HashMap<String, String> map = arr.get(i);
if (map.get("ro.product.cpu.abilist")!=null) {
if(architecture.trim().isEmpty()) {
architecture = map.get("ro.product.cpu.abilist");
}
}
if (map.get("ro.product.cpu.abilist64")!=null) {
if(architecture.trim().isEmpty()) {
architecture = map.get("ro.product.cpu.abilist64");
}
}
if (map.get("net.hostname") != null) {
if (architecture.trim().isEmpty()) {
hostId = map.get("net.hostname");
}
}
}
c.put("ARCH", new CategoryValue(architecture.trim(), "ARCH", "architecture"));
// review SystemClock.elapsedRealtime()
c.put("BOOT_TIME", new CategoryValue(getBootTime(), "BOOT_TIME", "bootTime"));
c.put("DNS_DOMAIN", new CategoryValue(" ", "DNS_DOMAIN", "dnsDomain"));
c.put("FQDN", new CategoryValue(" ", "FQDN", "FQDN"));
String fullName = getAndroidVersion(Build.VERSION.SDK_INT) + " api " + Build.VERSION.SDK_INT;
c.put("FULL_NAME", new CategoryValue(fullName, "FULL_NAME", "fullName"));
c.put("HOSTID", new CategoryValue(hostId, "HOSTID", "hostId"));
c.put("KERNEL_NAME", new CategoryValue("linux", "KERNEL_NAME", "kernelName"));
c.put("KERNEL_VERSION", new CategoryValue(getKernelVersion(), "KERNEL_VERSION", "kernelVersion"));
c.put("NAME", new CategoryValue(getAndroidVersion(Build.VERSION.SDK_INT), "NAME", "Name"));
c.put("SSH_KEY", new CategoryValue(getSSHKey(), "SSH_KEY", "sshKey"));
c.put("VERSION", new CategoryValue(String.valueOf(Build.VERSION.SDK_INT), "VERSION", "Version"));
Category category = new Category("TIMEZONE", "timezone");
category.put("NAME", new CategoryValue( getTimeZoneShortName(), "NAME", "name"));
category.put("OFFSET", new CategoryValue(getCurrentTimezoneOffset(), "OFFSET", "offset"));
c.put("TIMEZONE", new CategoryValue(category));
this.add(c);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.OPERATING_SYSTEM, ex.getMessage()));
}
}
public String getSSHKey() {
String encryptedMessage = "";
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Map keyPair = CryptoUtil.generateKeyPair();
String publicKey = (String) keyPair.get("publicKey");
encryptedMessage = CryptoUtil.encrypt("Test message...", publicKey);
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.OPERATING_SYSTEM_SSH_KEY, ex.getMessage()));
}
return "ssh-rsa " + encryptedMessage;
}
public String getBootTime() {
String value = "N/A";
try {
long milliSeconds = System.currentTimeMillis() - SystemClock.elapsedRealtime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss", Locale.getDefault());
Date resultDate = new Date(milliSeconds);
value = sdf.format(resultDate);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.OPERATING_SYSTEM_BOOT_TIME, ex.getMessage()));
}
return value;
}
public String getKernelVersion() {
String value = "N/A";
try {
Process p = Runtime.getRuntime().exec("uname -a");
InputStream is;
if (p.waitFor() == 0) {
is = p.getInputStream();
} else {
return value;
}
BufferedReader br = new BufferedReader(new InputStreamReader(is),
64);
String line = br.readLine();
br.close();
value = line;
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.OPERATING_SYSTEM_KERNEL, ex.getMessage()));
}
return value;
}
public String getTimeZoneShortName() {
String value = "N/A";
try {
TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);
InventoryLog.i("Time zone: " + timeZone.getID());
InventoryLog.i("default time zone: " + TimeZone.getDefault().getID());
InventoryLog.i("UTC: " + simpleDateFormat.format(calendar.getTime()));
InventoryLog.i("Default: " + calendar.getTime());
value = timeZone.getDisplayName();
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.OPERATING_SYSTEM_TIME_ZONE, ex.getMessage()));
}
return value;
}
public String getCurrentTimezoneOffset() {
String value = "N/A";
try {
TimeZone tz = TimeZone.getDefault();
Calendar cal = GregorianCalendar.getInstance(tz);
int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
int abs = Math.abs(offsetInMillis / 3600000);
int abs1 = Math.abs((offsetInMillis / 60000) % 60);
/*String offset = String.format(Locale.getDefault(), "%02d:%02d", abs, abs1);*/
String offset = abs + "" + abs1;
offset = (offsetInMillis >= 0 ? "+" : "-") + offset;
value = offset;
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(context, CommonErrorType.OPERATING_SYSTEM_CURRENT, ex.getMessage()));
}
return value;
}
private String getAndroidVersion(final int sdk) {
String version = "N/A";
try
{
SDK sdkEnum = SDK.values()[ sdk - 1 ];
version = sdkEnum.toString();
}
finally
{
return version;
}
}
private static enum SDK{
SDK1("","1.0"),
SDK2(NameOS.PETIT_FOUR,"1.1"),
SDK3(NameOS.CUPCAKE,"1.5"),
SDK4(NameOS.DONUT,"1.6"),
SDK5(NameOS.ECLAIR,"2.0"),
SDK6(NameOS.ECLAIR,"2.0.1"),
SDK7(NameOS.ECLAIR,"2.1"),
SDK8(NameOS.FROYO,"2.2"),
SDK9(NameOS.GINGERBREAD,"2.3"),
SDK10(NameOS.GINGERBREAD,"2.3.3"),
SDK11(NameOS.HONEYCOMB,"3.0"),
SDK12(NameOS.HONEYCOMB,"3.1"),
SDK13(NameOS.HONEYCOMB,"3.2"),
SDK14(NameOS.ICE_CREAM_SANDWICH,"4.0"),
SDK15(NameOS.ICE_CREAM_SANDWICH,"4.0.3"),
SDK16(NameOS.JELLY_BEAN,"4.1"),
SDK17(NameOS.JELLY_BEAN,"4.2"),
SDK18(NameOS.JELLY_BEAN,"4.3"),
SDK19(NameOS.KITKAT,"4.4"),
SDK20(NameOS.KITKAT_WATCH,"4.4"),
SDK21(NameOS.LOLLIPOP,"5.0"),
SDK22(NameOS.LOLLIPOP,"5.1"),
SDK23(NameOS.MARSHMALLOW,"6.0"),
SDK24(NameOS.NOUGAT,"7.0"),
SDK25(NameOS.NOUGAT,"7.1.1"),
SDK26(NameOS.OREO,"8.0"),
SDK27(NameOS.OREO,"8.1"),
SDK28(NameOS.PIE,"9.0"),
SDK29(NameOS.Q,"10.0"),
SDK30(NameOS.RED_VELVET_CAKE, "11.0"),
SDK31(NameOS.SNOW_CONE, "12.0"),
SDK32(NameOS.SNOW_CONE_V2, "12L"),
SDK33(NameOS.TIRAMISU, "13.0");
private final String name;
private final String version;
private static final String ANDROID="Android";
SDK( final String name,final String version){
this.name=name;
this.version=version;
}
@Override
public String toString() {
return (name+" "+ANDROID+" "+version).trim();
}
private static final class NameOS{
public static final String PETIT_FOUR="Petit Four";
public static final String CUPCAKE="Cupcake";
public static final String DONUT="Donut";
public static final String ECLAIR = "Eclair";
public static final String FROYO="Froyo";
public static final String GINGERBREAD="Gingerbread";
public static final String HONEYCOMB="Honeycomb";
public static final String ICE_CREAM_SANDWICH="Ice Cream Sandwich";
public static final String JELLY_BEAN="Jelly Bean";
public static final String KITKAT="KitKat";
public static final String KITKAT_WATCH="KitKat Watch";
public static final String LOLLIPOP = "Lollipop";
public static final String MARSHMALLOW="Marshmallow";
public static final String NOUGAT="Nougat";
public static final String OREO="Oreo";
public static final String PIE="Pie";
public static final String Q="Q";
public static final String RED_VELVET_CAKE="Red Velvet Cake";
public static final String SNOW_CONE="Snow Cone";
public static final String SNOW_CONE_V2="Snow Cone";
public static final String TIRAMISU="Tiramisu";
}
}
} | 13,494 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
StringUtils.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/StringUtils.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* This is a Utility class for String management
*/
public class StringUtils {
private StringUtils() {
}
/**
* This method can join a Collection of String in a single String separated by delimiter character,
* can be forward or reversed
*
* @param collection Collection of String
* @param delimiter This is the character that join the String
* @param reversed Indicate if is forward or reversed the join of the String
* @return Joined String
*/
public static String join(Collection<String> collection, String delimiter, boolean reversed) {
if (collection != null) {
StringBuilder buffer = new StringBuilder();
Iterator<String> iter = collection.iterator();
while (iter.hasNext()) {
if (!reversed) {
buffer.append(iter.next());
if (iter.hasNext()) {
buffer.append(delimiter);
}
} else {
buffer.insert(0, iter.next());
if (iter.hasNext()) {
buffer.insert(0, delimiter);
}
}
}
return buffer.toString();
} else {
return null;
}
}
/**
* This method can join a Collection of String in a single String separated by delimiter character
* @param collection Collection of String
* @param delimiter This is the character that join the String
* @return Joined String
*/
public static String join(Collection<String> collection, String delimiter) {
return StringUtils.join(collection, delimiter, false);
}
/**
* Convert int value to byte[]
* @param value Integer value to convert
* @return byte[]
*/
public static byte[] intToByte(int value) {
return new byte[] { (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value };
}
/**
* Convert int to IP
* @param value Integer value
* @return String
*/
public static String intToIp(int value) {
byte[] b = intToByte(value);
ArrayList<String> stack = new ArrayList<String>();
for (byte c : b) {
stack.add(String.valueOf(0xFF & c));
}
return (StringUtils.join(stack, ".", true));
}
/**
* Convert ipAddress int to SubNetMask
* @param ipAddress Integer value
* @return String
*/
public static String getSubNet(int ipAddress) {
return ((ipAddress & 0xFF) + "." +
((ipAddress >>>= 8) & 0xFF) + "." +
((ipAddress >>>= 8) & 0xFF) + "." +
((ipAddress >>>= 8) & 0xFF));
}
} | 4,047 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Categories.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/categories/Categories.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.categories;
import android.content.Context;
import org.flyve.inventory.CommonErrorType;
import org.flyve.inventory.InventoryLog;
import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlSerializer;
import java.util.ArrayList;
public class Categories extends ArrayList<Category>{
/*
* The serialization runtime associates with each serializable class a version number,
* called a serialVersionUID, which is used during deserialization to verify that the sender
* and receiver of a serialized object have loaded classes for that object that are compatible
* with respect to serialization. If the receiver has loaded a class for the object that has a
* different serialVersionUID than that of the corresponding sender's class, then deserialization
* will result in an InvalidClassException
*
* from: https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it
*/
private static final long serialVersionUID = 2278660715848751766L;
private Context mCtx;
/**
* Indicates whether some other object is "equal to" this one
* @param obj the reference object with which to compare
* @return boolean true if the object is the same as the one given in argument
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return (!super.equals(obj));
}
/**
* Returns a hash code value for the object
* @return int a hash code value for the object
*/
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 89 * hash + (this.mCtx != null ? this.mCtx.hashCode() : 0);
return hash;
}
/**
* This constructor load the Context of the instance
* @param xCtx Context where this class work
*/
public Categories(Context xCtx) {
mCtx = xCtx;
}
/**
* Create a XML object
* @param xSerializer object to create XML
*/
public void toXML(XmlSerializer xSerializer) {
try {
for( Category c : this) {
c.toXML(xSerializer);
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(String.valueOf(CommonErrorType.CATEGORIES_TO_XML), ex.getMessage()));
}
}
/**
* Create a XML object
* @param xSerializer object to create XML
*/
public void toXMLWithoutPrivateData(XmlSerializer xSerializer) {
try {
for( Category c : this) {
c.toXMLWithoutPrivateData(xSerializer);
}
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(String.valueOf(CommonErrorType.CATEGORIES_TO_XML_WITHOUT_PRIVATE), ex.getMessage()));
}
}
public void toJSON(JSONObject json) {
JSONArray jsonArr = new JSONArray();
String mType = "";
try {
for( Category c : this) {
mType = c.getTagName();
jsonArr.put(c.toJSON());
}
json.put(mType, jsonArr);
} catch (Exception ex) {
InventoryLog.e(CommonErrorType.CATEGORIES_TO_JSON + " " + ex.getMessage());
}
}
public void toJSONWithoutPrivateData(JSONObject json) {
JSONArray jsonArr = new JSONArray();
String mType = "";
try {
for( Category c : this) {
mType = c.getTagName();
jsonArr.put(c.toJSONWithoutPrivateData());
}
json.put(mType, jsonArr);
} catch (Exception ex) {
InventoryLog.e(InventoryLog.getMessage(String.valueOf(CommonErrorType.CATEGORIES_TO_JSON_WITHOUT_PRIVATE), ex.getMessage()));
}
}
}
| 5,057 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
UsbProperty.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/usbManager/UsbProperty.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.usbManager;
public enum UsbProperty {
PID("idProduct"),
VID("idVendor"),
MANUFACTURER("manufacturer"),
PRODUCT("product"),
VERSION("version"),
DEVICE_CLASS("bDeviceClass"),
DEVICE_SUBCLASS("bDeviceSubClass"),
DEVICE_NUMBER("devnum"),
DEVICE_PROTOCOL("bDeviceProtocol"),
MAX_POWER("bMaxPower"),
BUS_NUMBER("busnum"),
SERIAL("serial"),
SPEED("speed"),
SUPPORTS_AUTOSUSPEND("supports_autosuspend"),
AUTHORIZED("authorized"),
MODALIAS("modalias"),
ALTERNATIVE_SETTING("bAlternateSetting"),
NUM_INTERFACES("bNumInterfaces"),
NUM_ENDPOINTS("bNumEndpoints"),
INTERFACE("interface"),
INTERFACE_CLASS("bInterfaceClass"),
INTERFACE_NUMBER("bInterfaceNumber"),
INTERFACE_PROTOCOL("bInterfaceProtocol"),
INTERFACE_SUBCLASS("bInterfaceSubClass");
private final String fileName;
private UsbProperty(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return this.fileName;
}
}
| 2,213 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Validation.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/usbManager/Validation.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.usbManager;
import java.io.File;
class Validation {
Validation() {
}
public boolean isValidUsbDeviceCandidate(File file) {
if (!file.exists()) {
return false;
}
if (!file.isDirectory()) {
return false;
}
if (".".equals(file.getName()) || "..".equals(file.getName())) {
return false;
}
return true;
}
public File[] getListOfChildren( File path) {
if (path.exists() && path.isDirectory() && path.listFiles() != null) {
return path.listFiles();
}
return new File[0];
}
}
| 1,809 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
SysBusUsbDevice.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/usbManager/SysBusUsbDevice.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.usbManager;
import java.io.Serializable;
public final class SysBusUsbDevice implements Serializable {
private final String busNumber;
private final String deviceNumber;
private final String devicePath;
private final String deviceProtocol;
private final String deviceSubClass;
private final String maxPower;
private final String pid;
private final String reportedProductName;
private final String reportedVendorName;
private final String serialNumber;
private final String serviceClass;
private final String speed;
private final String usbVersion;
private final String vid;
public static final class Builder {
private String busNumber;
private String deviceNumber;
private String devicePath;
private String deviceProtocol;
private String deviceSubClass;
private String maxPower;
private String pid;
private String reportedProductName;
private String reportedVendorName;
private String serialNumber;
private String serviceClass;
private String speed;
private String usbVersion;
private String vid;
public Builder withVid(String val) {
this.vid = val;
return this;
}
public Builder withPid(String val) {
this.pid = val;
return this;
}
public Builder withReportedProductName(String val) {
this.reportedProductName = val;
return this;
}
public Builder withReportedVendorName(String val) {
this.reportedVendorName = val;
return this;
}
public Builder withSerialNumber(String val) {
this.serialNumber = val;
return this;
}
public Builder withSpeed(String val) {
this.speed = val;
return this;
}
public Builder withServiceClass(String val) {
this.serviceClass = val;
return this;
}
public Builder withDeviceProtocol(String val) {
this.deviceProtocol = val;
return this;
}
public Builder withMaxPower(String val) {
this.maxPower = val;
return this;
}
public Builder withDeviceSubClass(String val) {
this.deviceSubClass = val;
return this;
}
public Builder withBusNumber(String val) {
this.busNumber = val;
return this;
}
public Builder withDeviceNumber(String val) {
this.deviceNumber = val;
return this;
}
public Builder withUsbVersion(String val) {
this.usbVersion = val;
return this;
}
public Builder withDevicePath(String val) {
this.devicePath = val;
return this;
}
public SysBusUsbDevice build() {
return new SysBusUsbDevice(this);
}
}
private SysBusUsbDevice(Builder builder) {
this.vid = builder.vid;
this.pid = builder.pid;
this.reportedProductName = builder.reportedProductName;
this.reportedVendorName = builder.reportedVendorName;
this.serialNumber = builder.serialNumber;
this.speed = builder.speed;
this.serviceClass = builder.serviceClass;
this.deviceProtocol = builder.deviceProtocol;
this.maxPower = builder.maxPower;
this.deviceSubClass = builder.deviceSubClass;
this.busNumber = builder.busNumber;
this.deviceNumber = builder.deviceNumber;
this.usbVersion = builder.usbVersion;
this.devicePath = builder.devicePath;
}
public String getBusNumber() {
return this.busNumber;
}
public String getServiceClass() {
return this.serviceClass;
}
public String getDeviceNumber() {
return this.deviceNumber;
}
public String getDevicePath() {
return this.devicePath;
}
public String getDeviceProtocol() {
return this.deviceProtocol;
}
public String getDeviceSubClass() {
return this.deviceSubClass;
}
public String getMaxPower() {
return this.maxPower;
}
public String getPid() {
return this.pid;
}
public String getReportedProductName() {
return this.reportedProductName;
}
public String getReportedVendorName() {
return this.reportedVendorName;
}
public String getSerialNumber() {
return this.serialNumber;
}
public String getSpeed() {
return this.speed;
}
public String getUsbVersion() {
return this.usbVersion;
}
public String getVid() {
return this.vid;
}
}
| 6,121 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
SysBusUsbDeviceFactory.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/usbManager/SysBusUsbDeviceFactory.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.usbManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class SysBusUsbDeviceFactory {
private static class ContentsReader {
private final String basePath;
ContentsReader(String basePath) {
this.basePath = basePath;
}
private String read(UsbProperty property) {
IOException e;
FileNotFoundException e2;
Throwable th;
File file = new File(this.basePath + property.getFileName());
StringBuilder fileContents = new StringBuilder(1000);
if (file.exists() && !file.isDirectory()) {
BufferedReader reader = null;
try {
BufferedReader reader2 = new BufferedReader(new FileReader(file));
try {
char[] buf = new char[1024];
while (true) {
int numRead = reader2.read(buf);
if (numRead == -1) {
break;
}
fileContents.append(String.valueOf(buf, 0, numRead));
buf = new char[1024];
}
if (reader2 != null) {
try {
reader2.close();
} catch (IOException e3) {
e3.printStackTrace();
}
}
} catch (FileNotFoundException e4) {
e2 = e4;
reader = reader2;
try {
fileContents.setLength(0);
e2.printStackTrace();
if (reader != null) {
try {
reader.close();
} catch (IOException e32) {
e32.printStackTrace();
}
}
return fileContents.toString().trim();
} catch (Throwable th2) {
if (reader != null) {
try {
reader.close();
} catch (IOException e322) {
e322.printStackTrace();
}
}
throw th2;
}
} catch (IOException e5) {
reader = reader2;
fileContents.setLength(0);
e5.printStackTrace();
if (reader != null) {
try {
reader.close();
} catch (IOException e3222) {
e3222.printStackTrace();
}
}
return fileContents.toString().trim();
} catch (Throwable th3) {
reader = reader2;
if (reader != null) {
reader.close();
}
throw th3;
}
} catch (FileNotFoundException e6) {
e2 = e6;
fileContents.setLength(0);
e2.printStackTrace();
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return fileContents.toString().trim();
} catch (IOException e7) {
fileContents.setLength(0);
e7.printStackTrace();
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return fileContents.toString().trim();
}
}
return fileContents.toString().trim();
}
}
SysBusUsbDeviceFactory() {
}
public SysBusUsbDevice create(File usbDeviceDir) {
String devicePath = usbDeviceDir.getAbsolutePath() + File.separator;
ContentsReader reader = new ContentsReader(devicePath);
String busNumber = reader.read(UsbProperty.BUS_NUMBER);
String deviceNumber = reader.read(UsbProperty.DEVICE_NUMBER);
if (busNumber.isEmpty() || deviceNumber.isEmpty()) {
return null;
}
return new SysBusUsbDevice.Builder().withDevicePath(devicePath)
.withBusNumber(busNumber)
.withDeviceNumber(deviceNumber)
.withServiceClass(reader.read(UsbProperty.DEVICE_CLASS))
.withDeviceProtocol(reader.read(UsbProperty.DEVICE_PROTOCOL))
.withDeviceSubClass(reader.read(UsbProperty.DEVICE_SUBCLASS))
.withMaxPower(reader.read(UsbProperty.MAX_POWER))
.withPid(reader.read(UsbProperty.PID))
.withReportedProductName(reader.read(UsbProperty.PRODUCT))
.withReportedVendorName(reader.read(UsbProperty.MANUFACTURER))
.withSerialNumber(reader.read(UsbProperty.SERIAL))
.withSpeed(reader.read(UsbProperty.SPEED))
.withVid(reader.read(UsbProperty.VID))
.withUsbVersion(reader.read(UsbProperty.VERSION))
.build();
}
}
| 7,161 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
SysBusUsbManager.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/main/java/org/flyve/inventory/usbManager/SysBusUsbManager.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory.usbManager;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class SysBusUsbManager {
private final HashMap<String, SysBusUsbDevice> myUsbDevices;
private final SysBusUsbDeviceFactory sysBusUsbDeviceFactory;
private final String usbSysPath;
private final Validation validation;
public SysBusUsbManager() {
this("/sys/bus/usb/devices/");
}
public SysBusUsbManager(String usbSysPath) {
this.usbSysPath = usbSysPath;
this.myUsbDevices = new HashMap<>();
this.sysBusUsbDeviceFactory = new SysBusUsbDeviceFactory();
this.validation = new Validation();
}
public Map<String, SysBusUsbDevice> getUsbDevices() {
populateList(this.usbSysPath);
return Collections.unmodifiableMap(this.myUsbDevices);
}
private void populateList(String path) {
this.myUsbDevices.clear();
for (File child : this.validation.getListOfChildren(new File(path))) {
if (this.validation.isValidUsbDeviceCandidate(child)) {
SysBusUsbDevice usb = this.sysBusUsbDeviceFactory.create(child.getAbsoluteFile());
if (usb != null) {
this.myUsbDevices.put(child.getName(), usb);
}
}
}
}
}
| 2,511 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
OperatingSystemTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/OperatingSystemTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.OperatingSystem;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertNotEquals;
@RunWith(AndroidJUnit4.class)
public class OperatingSystemTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getBootTime() {
assertNotEquals("", new OperatingSystem(appContext).getBootTime());
}
@Test
public void getKernelVersion() {
assertNotEquals("", new OperatingSystem(appContext).getKernelVersion());
}
@Test
public void getTimeZoneShortName() {
assertNotEquals("", new OperatingSystem(appContext).getTimeZoneShortName());
}
@Test
public void getCurrentTimezoneOffset() {
assertNotEquals("", new OperatingSystem(appContext).getCurrentTimezoneOffset());
}
@Test
public void getSSHKey() {
assertNotEquals("", new OperatingSystem(appContext).getSSHKey());
}
} | 2,280 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
MemoryTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/MemoryTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Memory;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertNotEquals;
@RunWith(AndroidJUnit4.class)
public class MemoryTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getCapacity() throws Exception {
Memory memory = new Memory(appContext);
assertNotEquals("", memory.getCapacity());
}
@Test
public void getType() throws Exception {
Memory memory = new Memory(appContext);
assertNotEquals("", memory.getType());
}
@Test
public void getSpeed() throws Exception {
Memory memory = new Memory(appContext);
assertNotEquals("", memory.getSpeed());
}
} | 2,070 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
InventoryTaskTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/InventoryTaskTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import android.util.Log;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
@RunWith(AndroidJUnit4.class)
public class InventoryTaskTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getJSONTest() throws Exception {
InventoryTask task = new InventoryTask(appContext, "test", true);
task.getJSON(new InventoryTask.OnTaskCompleted() {
@Override
public void onTaskSuccess(String data) {
Log.d("Success Library JSON: ", data);
assertNotEquals("", data);
}
@Override
public void onTaskError(Throwable error) {
assertTrue(true);
}
});
}
@Test
public void getXMLTest() throws Exception {
InventoryTask task = new InventoryTask(appContext, "test", true);
task.getXML(new InventoryTask.OnTaskCompleted() {
@Override
public void onTaskSuccess(String data) {
Log.d("Success Library XML: ", data);
assertNotEquals("", data);
}
@Override
public void onTaskError(Throwable error) {
assertTrue(true);
}
});
}
@Test
public void getJSONsyncTest() throws Exception {
InventoryTask task = new InventoryTask(appContext, "test", true);
String data = task.getJSONSync();
assertNotEquals("", data);
}
@Test
public void getXMLsyncTest() throws Exception {
InventoryTask task = new InventoryTask(appContext, "test", true);
String data = task.getXMLSyn();
Log.d("Success Library XML: ", data);
assertNotEquals("", data);
}
}
| 3,146 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
BluetoothTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/BluetoothTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Bluetooth;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
@RunWith(AndroidJUnit4.class)
public class BluetoothTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getHardware_address() throws Exception {
if(!Utils.isEmulator()) {
Bluetooth bluetooth = new Bluetooth(appContext);
assertNotEquals("", bluetooth.getHardwareAddress());
} else {
assertTrue(true);
}
}
@Test
public void getName() throws Exception {
if(!Utils.isEmulator()) {
Bluetooth bluetooth = new Bluetooth(appContext);
assertNotEquals("", bluetooth.getName());
} else {
assertTrue(true);
}
}
} | 2,199 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
CamerasTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/CamerasTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.camera2.CameraCharacteristics;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Cameras;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import static org.junit.Assert.assertNotEquals;
@RunWith(AndroidJUnit4.class)
public class CamerasTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getResolutions() {
Cameras cameras = new Cameras(appContext);
for (int index = 0; index < cameras.getCountCamera(appContext); index++) {
CameraCharacteristics chars = cameras.getCharacteristics(appContext, index);
if (chars != null) {
assertNotEquals("", cameras.getResolution(chars));
}
}
}
@Test
public void getFacingState() {
Cameras cameras = new Cameras(appContext);
for (int index = 0; index < cameras.getCountCamera(appContext); index++) {
CameraCharacteristics chars = cameras.getCharacteristics(appContext, index);
if (chars != null) {
assertNotEquals("", cameras.getFacingState(chars));
}
}
}
@Test
public void getCategoryImageFormat() {
Cameras cameras = new Cameras(appContext);
for (int index = 0; index < cameras.getCountCamera(appContext); index++) {
CameraCharacteristics chars = cameras.getCharacteristics(appContext, index);
if (chars != null) {
ArrayList<String> imageFormat = cameras.getImageFormat(chars);
for (String image : imageFormat) {
assertNotEquals("", image);
}
}
}
}
@Test
public void getFlashUnit() {
Cameras cameras = new Cameras(appContext);
for (int index = 0; index < cameras.getCountCamera(appContext); index++) {
CameraCharacteristics chars = cameras.getCharacteristics(appContext, index);
if (chars != null) {
assertNotEquals("", cameras.getFlashUnit(chars));
}
}
}
@Test
public void getOrientation() {
Cameras cameras = new Cameras(appContext);
for (int index = 0; index < cameras.getCountCamera(appContext); index++) {
CameraCharacteristics chars = cameras.getCharacteristics(appContext, index);
if (chars != null) {
assertNotEquals("", cameras.getOrientation(chars));
}
}
}
@Test
public void getVideoResolution() {
int count = Camera.getNumberOfCameras();
Cameras cameras = new Cameras(appContext);
for (int index = 0; index < count; index++) {
assertNotEquals("", cameras.getVideoResolution(0));
}
}
@Test
public void getFocalLength() {
Cameras cameras = new Cameras(appContext);
for (int index = 0; index < cameras.getCountCamera(appContext); index++) {
CameraCharacteristics chars = cameras.getCharacteristics(appContext, index);
if (chars != null) {
assertNotEquals("", cameras.getFocalLength(chars));
}
}
}
@Test
public void getSensorSize() {
Cameras cameras = new Cameras(appContext);
for (int index = 0; index < cameras.getCountCamera(appContext); index++) {
CameraCharacteristics chars = cameras.getCharacteristics(appContext, index);
if (chars != null) {
assertNotEquals("", cameras.getSensorSize(chars));
}
}
}
@Test
public void getManufacturer() {
Cameras cameras = new Cameras(appContext);
for (int index = 0; index < cameras.getCountCamera(appContext); index++) {
assertNotEquals("", cameras.getManufacturer(index));
}
}
@Test
public void getModel() {
Cameras cameras = new Cameras(appContext);
for (int index = 0; index < cameras.getCountCamera(appContext); index++) {
assertNotEquals("", cameras.getModel(index));
}
}
@Test
public void getSupportValue() {
Cameras cameras = new Cameras(appContext);
assertNotEquals("", cameras.getSupportValue());
}
} | 5,590 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
BiosTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/BiosTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Bios;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
@RunWith(AndroidJUnit4.class)
public class BiosTest {
private Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getAssesTag() {
Bios bios = new Bios(appContext);
assertNotEquals("", bios.getAssetTag() );
}
@Test
public void getBiosDate() {
Bios bios = new Bios(appContext);
assertNotEquals("", bios.getBiosDate());
}
@Test
public void getBiosManufacturer() {
Bios bios = new Bios(appContext);
assertNotEquals("", bios.getBiosManufacturer());
}
@Test
public void getBiosVersion() {
Bios bios = new Bios(appContext);
assertNotEquals("", bios.getBiosVersion());
}
@Test
public void getMotherBoardManufacturer() {
Bios bios = new Bios(appContext);
assertNotEquals("", bios.getManufacturer() );
}
@Test
public void getMotherBoardModel() {
Bios bios = new Bios(appContext);
assertNotEquals("", bios.getModel() );
}
@Test
public void getMotherBoardSerialNumber() {
Bios bios = new Bios(appContext);
assertNotEquals("", bios.getMotherBoardSerial() );
}
@Test
public void getSystemManufacturer() {
Bios bios = new Bios(appContext);
assertNotEquals("", bios.getManufacturer() );
}
@Test
public void getSystemModel() {
Bios bios = new Bios(appContext);
assertNotEquals("", bios.getModel() );
}
@Test
public void getSystemSerialNumber() {
Bios bios = new Bios(appContext);
assertNotEquals("", bios.getSystemSerialNumber() );
}
} | 3,090 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
DrivesTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/DrivesTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import android.os.Environment;
import androidx.test.InstrumentationRegistry;
import org.flyve.inventory.categories.Drives;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.assertNotEquals;
public class DrivesTest {
Context appContext = InstrumentationRegistry.getTargetContext();
File froot = Environment.getRootDirectory();
File fexternal = Environment.getExternalStorageDirectory();
File fdata = Environment.getDataDirectory();
File fcache = Environment.getDownloadCacheDirectory();
@Test
public void getVolumn() throws Exception {
Drives drives = new Drives(appContext);
assertNotEquals("", drives.getVolume(froot));
assertNotEquals("", drives.getVolume(fexternal));
assertNotEquals("", drives.getVolume(fdata));
String secondaryStorage = System.getenv("SECONDARY_STORAGE");
if (secondaryStorage != null) {
assertNotEquals("", drives.getVolume(new File(secondaryStorage)));
}
}
@Test
public void getTotal() throws Exception {
Drives drives = new Drives(appContext);
assertNotEquals("", drives.getTotal(froot));
assertNotEquals("", drives.getTotal(fexternal));
assertNotEquals("", drives.getTotal(fdata));
assertNotEquals("", drives.getTotal(fcache));
String secondaryStorage = System.getenv("SECONDARY_STORAGE");
if (secondaryStorage != null) {
assertNotEquals("", drives.getTotal(new File(secondaryStorage)));
}
}
@Test
public void getFree() throws Exception {
Drives drives = new Drives(appContext);
assertNotEquals("", drives.getFreeSpace(froot));
assertNotEquals("", drives.getFreeSpace(fexternal));
assertNotEquals("", drives.getFreeSpace(fdata));
assertNotEquals("", drives.getFreeSpace(fcache));
String secondaryStorage = System.getenv("SECONDARY_STORAGE");
if (secondaryStorage != null) {
assertNotEquals("", drives.getFreeSpace(new File(secondaryStorage)));
}
}
@Test
public void getFileSystem() throws Exception {
Drives drives = new Drives(appContext);
assertNotEquals("", drives.getFileSystem(froot));
assertNotEquals("", drives.getFileSystem(fexternal));
assertNotEquals("", drives.getFileSystem(fdata));
assertNotEquals("", drives.getFileSystem(fcache));
String secondaryStorage = System.getenv("SECONDARY_STORAGE");
if (secondaryStorage != null) {
assertNotEquals("", drives.getFileSystem(new File(secondaryStorage)));
}
}
@Test
public void getType() throws Exception {
Drives drives = new Drives(appContext);
assertNotEquals("", drives.getType(froot));
assertNotEquals("", drives.getType(fexternal));
assertNotEquals("", drives.getType(fdata));
assertNotEquals("", drives.getType(fcache));
String secondaryStorage = System.getenv("SECONDARY_STORAGE");
if (secondaryStorage != null) {
assertNotEquals("", drives.getType(new File(secondaryStorage)));
}
}
} | 4,386 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
UserTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/UserTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertNotEquals;
@RunWith(AndroidJUnit4.class)
public class UserTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getClassTest() {
User user = new User(appContext);
assertNotEquals("", user.getUserName());
}
} | 1,725 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
ControllersTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/ControllersTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Controllers;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import static org.junit.Assert.assertNotEquals;
@RunWith(AndroidJUnit4.class)
public class ControllersTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getDriver() {
ArrayList<String> drivers = new Controllers(appContext).getDrivers();
for (String driver : drivers) {
assertNotEquals("", driver);
}
}
} | 1,842 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
InputsTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/InputsTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Inputs;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(AndroidJUnit4.class)
public class InputsTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getKeyboard() throws Exception {
Inputs inputs = new Inputs(appContext);
assertNotNull(inputs.getKeyboard());
}
@Test
public void getTouchscreen() throws Exception {
Inputs inputs = new Inputs(appContext);
assertNotEquals("", inputs.getTouchscreen());
}
} | 1,964 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
NetworksTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/NetworksTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Networks;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertNotEquals;
@RunWith(AndroidJUnit4.class)
public class NetworksTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getMacaddr() {
Networks networks = new Networks(appContext);
assertNotEquals("", networks.getMacAddress());
}
@Test
public void getSpeed() {
Networks networks = new Networks(appContext);
assertNotEquals("", networks.getSpeed());
}
@Test
public void getBSSID() {
Networks networks = new Networks(appContext);
assertNotEquals("", networks.getBSSID());
}
@Test
public void getSSID() {
Networks networks = new Networks(appContext);
assertNotEquals("", networks.getSSID());
}
@Test
public void getIpgateway() {
Networks networks = new Networks(appContext);
assertNotEquals("", networks.getIpgateway());
}
@Test
public void getIpaddress() {
Networks networks = new Networks(appContext);
assertNotEquals("", networks.getIpAddress());
}
@Test
public void getIpmask() {
Networks networks = new Networks(appContext);
assertNotEquals("", networks.getIpMask());
}
@Test
public void getIpdhcp() {
Networks networks = new Networks(appContext);
assertNotEquals("", networks.getIpDhCp());
}
@Test
public void getIpSubnet() {
Networks networks = new Networks(appContext);
assertNotEquals("", networks.getIpSubnet());
}
@Test
public void getStatus() {
Networks networks = new Networks(appContext);
assertNotEquals("", networks.getStatus());
}
@Test
public void getDescription() {
Networks networks = new Networks(appContext);
assertNotEquals("", networks.getDescription());
}
@Test
public void getAddressIpV6() {
Networks networks = new Networks(appContext);
assertNotEquals("", networks.getAddressIpV6());
}
@Test
public void getMaskIpV6() {
Networks networks = new Networks(appContext);
assertNotEquals("", networks.getMaskIpV6());
}
@Test
public void getSubnetIpV6() {
Networks networks = new Networks(appContext);
assertNotEquals("", networks.getSubnetIpV6());
}
} | 3,765 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
CpusTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/CpusTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Cpus;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
@RunWith(AndroidJUnit4.class)
public class CpusTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getArch() throws Exception {
Cpus cpus = new Cpus(appContext);
assertNotEquals("", cpus.getArch());
}
@Test
public void getCPUCore() throws Exception {
Cpus cpus = new Cpus(appContext);
assertNotEquals("", cpus.getCPUCore());
}
@Test
public void getFamilyName() throws Exception {
Cpus cpus = new Cpus(appContext);
assertNotEquals("", cpus.getFamilyName());
}
@Test
public void getFamilyNumber() throws Exception {
Cpus cpus = new Cpus(appContext);
assertNotEquals("", cpus.getFamilyNumber());
}
@Test
public void getManufacturer() throws Exception {
Cpus cpus = new Cpus(appContext);
assertNotEquals("", cpus.getManufacturer());
}
@Test
public void getModel() throws Exception {
Cpus cpus = new Cpus(appContext);
assertNotEquals("", cpus.getModel());
}
@Test
public void getCpuName() throws Exception {
Cpus cpus = new Cpus(appContext);
assertNotEquals("", cpus.getCpuName());
}
@Test
public void getCpuThread() throws Exception {
Cpus cpus = new Cpus(appContext);
assertNotEquals("", cpus.getCpuThread());
}
@Test
public void getCpuFrequency() throws Exception {
// work on real device
if(!Utils.isEmulator()) {
Cpus cpus = new Cpus(appContext);
assertNotEquals("", cpus.getCpuFrequency());
} else {
assertTrue(true);
}
}
} | 3,182 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
ModemsTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/ModemsTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Modems;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertNotEquals;
@RunWith(AndroidJUnit4.class)
public class ModemsTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getDriver() {
for (String imei : new Modems(appContext).getIMEI()) {
assertNotEquals("", imei);
}
}
} | 1,745 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
UsbTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/UsbTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Usb;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertNotEquals;
@RunWith(AndroidJUnit4.class)
public class UsbTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getClassTest() {
Usb usb = new Usb(appContext);
assertNotEquals("", usb.getServiceClass());
}
@Test
public void getProductid() {
Usb usb = new Usb(appContext);
assertNotEquals("", usb.getPid());
}
@Test
public void getVendorid() {
Usb usb = new Usb(appContext);
assertNotEquals("", usb.getVid());
}
@Test
public void getSubclass() {
Usb usb = new Usb(appContext);
assertNotEquals("", usb.getDeviceSubClass());
}
@Test
public void getManufacturer() {
Usb usb = new Usb(appContext);
assertNotEquals("", usb.getReportedProductName());
}
@Test
public void getCaption() {
Usb usb = new Usb(appContext);
assertNotEquals("", usb.getUsbVersion());
}
@Test
public void getSerialNumber() {
Usb usb = new Usb(appContext);
assertNotEquals("", usb.getSerialNumber());
}
} | 2,560 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
CreateFileTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/CreateFileTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Categories;
import org.flyve.inventory.categories.Category;
import org.flyve.inventory.categories.CategoryValue;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import static org.junit.Assert.assertTrue;
@RunWith(AndroidJUnit4.class)
public class CreateFileTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void createXMLTest() throws Exception {
ArrayList<Categories> mContent = new ArrayList<Categories>();
Category category = new Category("CAMERAS", "cameras");
category.put("RESOLUTION", new CategoryValue("3264x2448", "RESOLUTION", "resolution"));
Categories categories = new Categories(appContext);
categories.add(category);
mContent.add(categories);
try {
String xml = Utils.createXML(appContext, mContent, "Agent", false, "test-tag", "Computer");
assertTrue(true);
} catch (Exception ex) {
assertTrue(false);
}
}
@Test
public void createJSONTest() throws Exception {
ArrayList<Categories> mContent = new ArrayList<Categories>();
Category category = new Category("CAMERAS", "cameras");
category.put("RESOLUTION", new CategoryValue("3264x2448", "RESOLUTION", "resolution"));
Categories categories = new Categories(appContext);
categories.add(category);
mContent.add(categories);
String json = Utils.createJSON(appContext, mContent, "Agent", false, "test-tag", "Computer");
try {
JSONObject objJson = new JSONObject(json);
assertTrue(true);
} catch (Exception ex) {
assertTrue(false);
}
}
} | 3,107 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
SimcardsTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/SimcardsTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import android.telephony.SubscriptionInfo;
import org.flyve.inventory.categories.Simcards;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import static org.junit.Assert.assertNotEquals;
@RunWith(AndroidJUnit4.class)
public class SimcardsTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getCountry() throws Exception {
Simcards simcards = new Simcards(appContext);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
List<SubscriptionInfo> multipleSim = simcards.getMultipleSim(appContext);
if (multipleSim != null && multipleSim.size() > 0) {
for (SubscriptionInfo info : multipleSim)
assertNotEquals("", info.getCountryIso());
}
} else {
assertNotEquals("", simcards.getCountry());
}
}
@Test
public void getOperator_code() throws Exception {
Simcards simcards = new Simcards(appContext);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
List<SubscriptionInfo> multipleSim = simcards.getMultipleSim(appContext);
if (multipleSim != null && multipleSim.size() > 0) {
for (SubscriptionInfo info : multipleSim) {
String operatorCode = info.getMcc() + "" + info.getMnc();
assertNotEquals("", operatorCode);
}
}
} else {
assertNotEquals("", simcards.getOperatorCode());
}
}
@Test
public void getOperator_name() throws Exception {
Simcards simcards = new Simcards(appContext);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
List<SubscriptionInfo> multipleSim = simcards.getMultipleSim(appContext);
if (multipleSim != null && multipleSim.size() > 0) {
for (SubscriptionInfo info : multipleSim)
assertNotEquals("", info.getCarrierName().toString());
}
} else {
assertNotEquals("", simcards.getOperatorName());
}
}
@Test
public void getSerial() throws Exception {
Simcards simcards = new Simcards(appContext);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
List<SubscriptionInfo> multipleSim = simcards.getMultipleSim(appContext);
if (multipleSim != null && multipleSim.size() > 0) {
for (SubscriptionInfo info : multipleSim)
assertNotEquals("", info.getIccId());
}
} else {
assertNotEquals("", simcards.getSerial());
}
}
@Test
public void getState() throws Exception {
Simcards simcards = new Simcards(appContext);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
List<SubscriptionInfo> multipleSim = simcards.getMultipleSim(appContext);
if (multipleSim != null && multipleSim.size() > 0) {
for (SubscriptionInfo info : multipleSim)
assertNotEquals("", simcards.getState(appContext, info.getSimSlotIndex()));
}
} else {
assertNotEquals("", simcards.getState(appContext, 0));
}
}
@Test
public void getLine_number() throws Exception {
Simcards simcards = new Simcards(appContext);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
List<SubscriptionInfo> multipleSim = simcards.getMultipleSim(appContext);
if (multipleSim != null && multipleSim.size() > 0) {
for (SubscriptionInfo info : multipleSim)
assertNotEquals("", info.getNumber());
}
} else {
assertNotEquals("", simcards.getLineNumber());
}
}
@Test
public void getSubscriber_id() throws Exception {
Simcards simcards = new Simcards(appContext);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
List<SubscriptionInfo> multipleSim = simcards.getMultipleSim(appContext);
if (multipleSim != null && multipleSim.size() > 0) {
for (SubscriptionInfo info : multipleSim)
assertNotEquals("", String.valueOf(info.getSubscriptionId()));
}
} else {
assertNotEquals("", simcards.getSubscriberId());
}
}
} | 5,933 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
SoftwareTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/SoftwareTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Software;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import static org.junit.Assert.assertNotEquals;
@RunWith(AndroidJUnit4.class)
public class SoftwareTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getName() {
Software software = new Software(appContext);
PackageManager packageManager = appContext.getPackageManager();
List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo p : packages) {
assertNotEquals("", software.getName(p));
}
}
@Test
public void getVersion() {
Software software = new Software(appContext);
PackageManager packageManager = appContext.getPackageManager();
List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo p : packages) {
assertNotEquals("", software.getVersion(p));
}
}
@Test
public void getFileSize() {
Software software = new Software(appContext);
PackageManager packageManager = appContext.getPackageManager();
List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo p : packages) {
assertNotEquals("", software.getFileSize(p));
}
}
@Test
public void getFolder() {
Software software = new Software(appContext);
PackageManager packageManager = appContext.getPackageManager();
List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo p : packages) {
assertNotEquals("", software.getFolder(p));
}
}
@Test
public void getRemovable() {
Software software = new Software(appContext);
PackageManager packageManager = appContext.getPackageManager();
List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo p : packages) {
assertNotEquals("", software.getRemovable(p));
}
}
@Test
public void getUserID() {
Software software = new Software(appContext);
PackageManager packageManager = appContext.getPackageManager();
List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo p : packages) {
assertNotEquals("", software.getUserID(p));
}
}
@Test
public void getPackage() {
Software software = new Software(appContext);
PackageManager packageManager = appContext.getPackageManager();
List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo p : packages) {
assertNotEquals("", software.getPackage(p));
}
}
@Test
public void getInstallDate() {
Software software = new Software(appContext);
PackageManager packageManager = appContext.getPackageManager();
List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo p : packages) {
assertNotEquals("", software.getInstallDate(p));
}
}
} | 4,906 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
HardwareTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/HardwareTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Hardware;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertNotEquals;
@RunWith(AndroidJUnit4.class)
public class HardwareTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getDatelastloggeduser() throws Exception {
Hardware hardware = new Hardware(appContext);
assertNotEquals("", hardware.getDateLastLoggedUser());
}
@Test
public void getLastloggeduser() throws Exception {
Hardware hardware = new Hardware(appContext);
assertNotEquals("", hardware.getLastLoggedUser());
}
@Test
public void getUser() throws Exception {
Hardware hardware = new Hardware(appContext);
assertNotEquals("", hardware.getUserId());
}
@Test
public void getName() throws Exception {
Hardware hardware = new Hardware(appContext);
assertNotEquals("", hardware.getName());
}
@Test
public void getOsversion() throws Exception {
Hardware hardware = new Hardware(appContext);
assertNotEquals("", hardware.getOsVersion());
}
@Test
public void getArchname() throws Exception {
Hardware hardware = new Hardware(appContext);
assertNotEquals("", hardware.getArchName());
}
@Test
public void getUUID() throws Exception {
Hardware hardware = new Hardware(appContext);
assertNotEquals("", hardware.getUUID());
}
} | 2,817 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
BatteryTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/BatteryTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Battery;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertNotEquals;
@RunWith(AndroidJUnit4.class)
public class BatteryTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getTechnology() {
assertNotEquals("", new Battery(appContext).getTechnology());
}
@Test
public void getTemperature() {
assertNotEquals("", new Battery(appContext).getTemperature());
}
@Test
public void getVoltage() {
assertNotEquals("", new Battery(appContext).getVoltage());
}
@Test
public void getLevel() {
assertNotEquals("", new Battery(appContext).getLevel());
}
@Test
public void getBatteryHealth() {
assertNotEquals("", new Battery(appContext).getBatteryHealth());
}
@Test
public void getBatteryStatus() {
assertNotEquals("", new Battery(appContext).getBatteryStatus());
}
@Test
public void getCapacity() {
assertNotEquals("", new Battery(appContext).getCapacity());
}
} | 2,431 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
VideosTest.java | /FileExtraction/Java_unseen/glpi-project_android-inventory-library/inventory/src/androidTest/java/org/flyve/inventory/VideosTest.java | /**
* LICENSE
*
* This file is part of Flyve MDM Inventory Library for Android.
*
* Inventory Library for Android is a subproject of Flyve MDM.
* Flyve MDM is a mobile device management software.
*
* Flyve MDM is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* Flyve MDM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* ---------------------------------------------------------------------
* @copyright Copyright © 2018 Teclib. All rights reserved.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/flyve-mdm/android-inventory-library
* @link https://flyve-mdm.com
* @link http://flyve.org/android-inventory-library
* ---------------------------------------------------------------------
*/
package org.flyve.inventory;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.flyve.inventory.categories.Videos;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertNotEquals;
@RunWith(AndroidJUnit4.class)
public class VideosTest {
Context appContext = InstrumentationRegistry.getTargetContext();
@Test
public void getResolution() throws Exception {
Videos videos = new Videos(appContext);
assertNotEquals("", videos.getResolution());
}
} | 1,759 | Java | .java | glpi-project/android-inventory-library | 16 | 22 | 2 | 2017-06-19T07:14:12Z | 2024-03-14T17:22:46Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.