feat: complete reverse engineering, standard Maven structure, detailed code annotations and IoT-M platform architecture
This commit is contained in:
1 parent
e8dc09fb3c
commit
cd6a4c70e7
3045 files changed
+566733
-1
No files matched your search
@@ -0,0 +1,129 @@
|
||||
package com.mitac.cell.barcode;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.common.io.Files;
|
||||
import com.google.zxing.BarcodeFormat;
|
||||
import com.google.zxing.EncodeHintType;
|
||||
import com.google.zxing.WriterException;
|
||||
import com.google.zxing.client.j2se.MatrixToImageWriter;
|
||||
import com.google.zxing.common.BitMatrix;
|
||||
import com.google.zxing.qrcode.QRCodeWriter;
|
||||
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
public class QrCode {
|
||||
private static final int DEFAULT_WIDTH = 220;
|
||||
private static final int DEFAULT_MARGIN = 1;
|
||||
private String code;
|
||||
private int width = 220;
|
||||
private int margin = 1;
|
||||
|
||||
public QrCode() {
|
||||
}
|
||||
|
||||
public QrCode(String code, int width) {
|
||||
this.setCode(code);
|
||||
this.setWidth(width);
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return this.code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public int getWdith() {
|
||||
return this.width;
|
||||
}
|
||||
|
||||
public void setWidth(int width) {
|
||||
this.width = width;
|
||||
}
|
||||
|
||||
public int getMargin() {
|
||||
return this.margin;
|
||||
}
|
||||
|
||||
public void setMargin(int margin) {
|
||||
this.margin = margin;
|
||||
}
|
||||
|
||||
public BufferedImage toImage() {
|
||||
return toImage(this.code, this.width, this.margin);
|
||||
}
|
||||
|
||||
public byte[] toBytes(String fileFormat) {
|
||||
return toBytes(this.toImage(), fileFormat);
|
||||
}
|
||||
|
||||
public File saveAs(String filePath) {
|
||||
if (Strings.isNullOrEmpty(filePath)) {
|
||||
return null;
|
||||
} else {
|
||||
String ext = Files.getFileExtension(filePath);
|
||||
return this.saveAs(filePath, ext);
|
||||
}
|
||||
}
|
||||
|
||||
public File saveAs(String filePath, String fileFormat) {
|
||||
if (Strings.isNullOrEmpty(fileFormat)) {
|
||||
fileFormat = "png";
|
||||
}
|
||||
|
||||
try {
|
||||
File outputFile = new File(filePath);
|
||||
ImageIO.write(this.toImage(), fileFormat, outputFile);
|
||||
return outputFile;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] toBytes(BufferedImage image, String fileFormat) {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
|
||||
try {
|
||||
ImageIO.write(image, fileFormat, baos);
|
||||
return baos.toByteArray();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static BufferedImage toImage(String code, Integer size, Integer margin) {
|
||||
if (Strings.isNullOrEmpty(code)) {
|
||||
return null;
|
||||
} else {
|
||||
if (size == null || size <= 16) {
|
||||
size = 220;
|
||||
}
|
||||
|
||||
if (margin == null || margin < 0) {
|
||||
margin = 1;
|
||||
}
|
||||
|
||||
Map<EncodeHintType, Object> hints = new EnumMap(EncodeHintType.class);
|
||||
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
|
||||
hints.put(EncodeHintType.MARGIN, margin);
|
||||
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
|
||||
|
||||
try {
|
||||
BitMatrix bitMatrix = (new QRCodeWriter()).encode(code, BarcodeFormat.QR_CODE, size, size, hints);
|
||||
return MatrixToImageWriter.toBufferedImage(bitMatrix);
|
||||
} catch (WriterException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.mitac.cell.constant;
|
||||
|
||||
public class DateTimeConst {
|
||||
public static final String FORMAT_DATE_4_DIGIT_PASSWORD = "MMdd";
|
||||
public static final String FORMAT_DATE_6_DIGIT_PASSWORD = "yyMMdd";
|
||||
public static final String FORMAT_DATE_8_DIGIT_PASSWORD = "yyyyMMdd";
|
||||
public static final long ONE_MINUTES = 60000L;
|
||||
public static final long ONE_HOUR = 3600000L;
|
||||
public static final long HALF_HOUR = 1800000L;
|
||||
public static final long QUATER_HOUR = 900000L;
|
||||
public static final long ONE_DAY = 86400000L;
|
||||
public static final long ONE_WEEK = 604800000L;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.mitac.cell.constant;
|
||||
|
||||
public class GeneralConst {
|
||||
public static final String KEY_KEY = "key";
|
||||
public static final String KEY_AUTH_KEY = "auth_key";
|
||||
public static final String KEY_ID = "id";
|
||||
public static final String KEY_NAME = "name";
|
||||
public static final String KEY_THEME = "theme";
|
||||
public static final String VALUE_DEFAULT = "default";
|
||||
public static final String CATEGORY_APP = "app";
|
||||
public static final long DEFAULT_TOKEN_LIFE_CYCLE = 86400000L;
|
||||
public static final String KEY_LANGUAGE = "language";
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.mitac.cell.constant;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public class LocaleConst {
|
||||
public static final Locale DEFAULT_LOCALE;
|
||||
|
||||
static {
|
||||
DEFAULT_LOCALE = Locale.US;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.mitac.cell.constant;
|
||||
|
||||
public class LocationConst {
|
||||
public static String KEY_LAT = "lat";
|
||||
public static String KEY_LATITUDE = "latitude";
|
||||
public static String KEY_LON = "lon";
|
||||
public static String KEY_LONGITUDE = "longitude";
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.mitac.cell.constant;
|
||||
|
||||
public class MessageConst {
|
||||
public static final String ID = "id";
|
||||
public static final String FROM = "from";
|
||||
public static final String REPLY_TO = "replyto";
|
||||
public static final String TO = "to";
|
||||
public static final String CC = "cc";
|
||||
public static final String BCC = "bcc";
|
||||
public static final String TAG = "tag";
|
||||
public static final String TYPE = "type";
|
||||
public static final String WEB_URL = "web_url";
|
||||
public static final String HEADERS = "headers";
|
||||
public static final String SUBJECT = "subject";
|
||||
public static final String TEXT = "text";
|
||||
public static final String HTML = "html";
|
||||
public static final String ATTR = "attr";
|
||||
public static final String ATTACHMENT = "attachment";
|
||||
public static final String ATTACHMENT_URL = "attachment_url";
|
||||
public static final String INLINE_IMAGE = "inline_image";
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.mitac.cell.constant;
|
||||
|
||||
public class PropertyConst {
|
||||
public static final String ROLE = "role";
|
||||
public static final String ADMIN = "admin";
|
||||
public static final String ADMINISTRATOR = "Administrator";
|
||||
public static final String NAME = "name";
|
||||
public static final String FILE_NAME = "fileName";
|
||||
public static final String CONTENT_TYPE = "contentType";
|
||||
public static final String FILE_URL = "fileUrl";
|
||||
public static final String ICON_NAME = "iconName";
|
||||
public static final String ICON_URL = "iconUrl";
|
||||
public static final String ICON_ID = "iconId";
|
||||
public static final String DEVELOPER = "developer";
|
||||
public static final String DESC = "desc";
|
||||
public static final String LENGTH = "length";
|
||||
public static final String CHECKSUM = "checksum";
|
||||
public static final String LAST_MODIFIED = "lastModified";
|
||||
public static final String TYPE = "type";
|
||||
public static final String AB_UPDATE = "abUpdate";
|
||||
public static final String BUILD_DATE = "buildDate";
|
||||
public static final String BUILD_TIME = "buildTime";
|
||||
public static final String POST_BUILD_DATE = "postBuildDate";
|
||||
public static final String PRODUCT_ID = "productId";
|
||||
public static final String TARGET_PRODUCT = "targetProduct";
|
||||
public static final String DEVICE_ID = "deviceId";
|
||||
public static final String SKU_ID = "skuId";
|
||||
public static final String COMPATIBLE_SKU_IDS = "compatibleSkuIds";
|
||||
public static final String DISPLAY_ID = "displayId";
|
||||
public static final String PRODUCT_DISPLAY_ID = "productDisplayId";
|
||||
public static final String PRE_DISPLAY_ID = "preDisplayId";
|
||||
public static final String BUILD_TYPE = "buildType";
|
||||
public static final String BUILD_TAGS = "buildTags";
|
||||
public static final String OTA_CERT = "otaCert";
|
||||
public static final String BRAND = "brand";
|
||||
public static final String CUSTOMER = "customer";
|
||||
public static final String CUSTOMER_ID = "customerId";
|
||||
public static final String PART_NO = "partNo";
|
||||
public static final String OS_VERSION = "osVersion";
|
||||
public static final String SCRIPT_VERSION = "scriptVersion";
|
||||
public static final String RELEASE_VERSION = "releaseVersion";
|
||||
public static final String MARKET_NAME_1 = "marketName1";
|
||||
public static final String MARKET_NAME_2 = "marketName2";
|
||||
public static final String SDK = "sdk";
|
||||
public static final String SECURITY_PATCH = "securityPatch";
|
||||
public static final String MODEM_SKU = "modemSku";
|
||||
public static final String MODEM_FIRMWARE_VERSION = "modemFirmwareVersion";
|
||||
public static final String MODEM_FIRMWARE_LONG_VERSION = "modemFirmwareLongVersion";
|
||||
public static final String PRE_BUILD = "preBuild";
|
||||
public static final String POST_BUILD = "postBuild";
|
||||
public static final String PACKAGE = "package";
|
||||
public static final String PACKAGE_NAME = "packageName";
|
||||
public static final String SHARED_UID = "sharedUid";
|
||||
public static final String LABEL = "label";
|
||||
public static final String VERSION = "version";
|
||||
public static final String VERSION_CODE = "versionCode";
|
||||
public static final String VERSION_NAME = "versionName";
|
||||
public static final String MIN_SDK_VERSION = "minSdkVersion";
|
||||
public static final String MAX_SDK_VERSION = "maxSdkVersion";
|
||||
public static final String TARGET_SDK_VERSION = "targetSdkVersion";
|
||||
public static final String USER_PERMISSION = "userPermission";
|
||||
public static final String CERT_MD5 = "certMd5";
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.mitac.cell.constant;
|
||||
|
||||
public class SizeConst {
|
||||
public static long SIZE_1K = 1024L;
|
||||
public static long SIZE_1M;
|
||||
public static long SIZE_1G;
|
||||
public static long SIZE_1T;
|
||||
|
||||
static {
|
||||
SIZE_1M = SIZE_1K * SIZE_1K;
|
||||
SIZE_1G = SIZE_1M * SIZE_1K;
|
||||
SIZE_1T = SIZE_1G * SIZE_1K;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.mitac.cell.data;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.zip.Deflater;
|
||||
|
||||
public class McCompress extends Deflater {
|
||||
private static int BUF_SIZE = 1024;
|
||||
|
||||
public McCompress() {
|
||||
}
|
||||
|
||||
public McCompress(byte[] source) {
|
||||
this.setInput(source);
|
||||
}
|
||||
|
||||
public McCompress(byte[] source, int level) {
|
||||
super(level);
|
||||
this.setInput(source);
|
||||
}
|
||||
|
||||
public McCompress(byte[] source, int level, boolean noHeader) {
|
||||
super(level, noHeader);
|
||||
this.setInput(source);
|
||||
}
|
||||
|
||||
public void setSource(byte[] source) {
|
||||
this.setInput(source);
|
||||
}
|
||||
|
||||
public byte[] toByteArray() {
|
||||
this.finish();
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[BUF_SIZE];
|
||||
|
||||
while(!this.finished()) {
|
||||
int count = this.deflate(buffer);
|
||||
|
||||
try {
|
||||
baos.write(buffer, 0, count);
|
||||
} catch (OutOfMemoryError e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
this.end();
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
public static byte[] compress(byte[] source, int level, boolean noHeader) {
|
||||
return (new McCompress(source, level, noHeader)).toByteArray();
|
||||
}
|
||||
|
||||
public static byte[] compress(byte[] source) {
|
||||
return compress(source, 9, true);
|
||||
}
|
||||
|
||||
public static byte[] compress(String source) {
|
||||
return compress(source.getBytes(Charsets.UTF_8), 9, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.mitac.cell.data;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.zip.DataFormatException;
|
||||
import java.util.zip.Inflater;
|
||||
|
||||
public class McDecompress extends Inflater {
|
||||
private static int BUF_SIZE = 1024;
|
||||
|
||||
public McDecompress() {
|
||||
}
|
||||
|
||||
public McDecompress(byte[] source) {
|
||||
this.setInput(source);
|
||||
}
|
||||
|
||||
public McDecompress(byte[] source, boolean noHeader) {
|
||||
super(noHeader);
|
||||
this.setInput(source);
|
||||
}
|
||||
|
||||
public McDecompress(ByteBuffer source) {
|
||||
this.setSource(source);
|
||||
}
|
||||
|
||||
public McDecompress(ByteBuffer source, boolean noHeader) {
|
||||
super(noHeader);
|
||||
this.setSource(source);
|
||||
}
|
||||
|
||||
public void setSource(ByteBuffer source) {
|
||||
byte[] bytes = new byte[source.remaining()];
|
||||
source.get(bytes, 0, bytes.length);
|
||||
this.setInput(bytes);
|
||||
}
|
||||
|
||||
public void setSource(byte[] source) {
|
||||
this.setInput(source);
|
||||
}
|
||||
|
||||
public byte[] toByteArray() {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[BUF_SIZE];
|
||||
|
||||
try {
|
||||
while(!this.needsInput()) {
|
||||
int count = this.inflate(buffer);
|
||||
baos.write(buffer, 0, count);
|
||||
}
|
||||
} catch (DataFormatException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
this.end();
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
public static byte[] decompress(byte[] source, boolean noHeader) {
|
||||
return (new McDecompress(source, noHeader)).toByteArray();
|
||||
}
|
||||
|
||||
public static byte[] decompress(byte[] source) {
|
||||
return decompress(source, true);
|
||||
}
|
||||
|
||||
public static byte[] decompress(ByteBuffer source, boolean noHeader) {
|
||||
return (new McDecompress(source, noHeader)).toByteArray();
|
||||
}
|
||||
|
||||
public static byte[] decompress(ByteBuffer source) {
|
||||
return decompress(source, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.mitac.cell.data;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Map;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
public class McXml {
|
||||
private static final String TAG_SOURCE = "src";
|
||||
private File parentDir;
|
||||
|
||||
public JsonObject load(File file) throws ParserConfigurationException, SAXException, IOException {
|
||||
if (file.exists()) {
|
||||
this.parentDir = file.getParentFile();
|
||||
InputStream is = new FileInputStream(file);
|
||||
return this.load(is);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public JsonObject load(InputStream is) throws ParserConfigurationException, SAXException, IOException {
|
||||
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
|
||||
Document doc = documentBuilder.parse(is);
|
||||
Element root = doc.getDocumentElement();
|
||||
return this.toJsonObject(root);
|
||||
}
|
||||
|
||||
private JsonObject toJsonObject(Element root) throws ParserConfigurationException, SAXException, IOException {
|
||||
JsonObject jParent = new JsonObject();
|
||||
NamedNodeMap attributes = root.getAttributes();
|
||||
if (attributes != null && attributes.getLength() > 0) {
|
||||
for(int i = 0; i < attributes.getLength(); ++i) {
|
||||
String name = attributes.item(i).getNodeName();
|
||||
String value = attributes.item(i).getNodeValue();
|
||||
if (name.equals("src")) {
|
||||
JsonObject jChild = this.load(new File(this.parentDir, value));
|
||||
|
||||
for(Map.Entry entry : jChild.entrySet()) {
|
||||
jParent.add((String)entry.getKey(), (JsonElement)entry.getValue());
|
||||
}
|
||||
} else {
|
||||
jParent.addProperty(name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
NodeList nodeList = root.getChildNodes();
|
||||
|
||||
for(int i = 0; i < nodeList.getLength(); ++i) {
|
||||
Node node = nodeList.item(i);
|
||||
if (node.getNodeType() == 1) {
|
||||
String name = node.getNodeName();
|
||||
JsonObject jChildProperties = this.toJsonObject((Element)node);
|
||||
JsonElement jChild = jParent.get(name);
|
||||
if (jChild != null && !jChild.isJsonNull()) {
|
||||
if (jChild.isJsonArray()) {
|
||||
jChild.getAsJsonArray().add(jChildProperties);
|
||||
} else if (jChild.isJsonObject()) {
|
||||
JsonArray jArray = new JsonArray();
|
||||
jArray.add(jChild);
|
||||
jArray.add(jChildProperties);
|
||||
jParent.add(name, jArray);
|
||||
}
|
||||
} else {
|
||||
jParent.add(name, jChildProperties);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return jParent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package com.mitac.cell.db;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.bson.Document;
|
||||
|
||||
public class DbObject extends Document {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public DbObject() {
|
||||
}
|
||||
|
||||
public DbObject(String key, Object value) {
|
||||
super(key, value);
|
||||
}
|
||||
|
||||
public DbObject(Map map) {
|
||||
super(map);
|
||||
}
|
||||
|
||||
public String getString(String key, String defaultValue) {
|
||||
Object value = this.get(key);
|
||||
|
||||
try {
|
||||
return value != null ? String.valueOf(value) : defaultValue;
|
||||
} catch (Exception var5) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
public Boolean getBoolean(Object key) {
|
||||
return this.getBoolean(key, false);
|
||||
}
|
||||
|
||||
public boolean getBoolean(Object key, boolean defaultValue) {
|
||||
try {
|
||||
return super.getBoolean(key, defaultValue);
|
||||
} catch (Exception var4) {
|
||||
return this.containsKey(key) && this.get(key).equals("true");
|
||||
}
|
||||
}
|
||||
|
||||
public Integer getInteger(Object key) {
|
||||
return this.getInteger(key, -1);
|
||||
}
|
||||
|
||||
public int getInteger(Object key, int defaultValue) {
|
||||
Number value = this.getNumber(key);
|
||||
return value != null ? value.intValue() : defaultValue;
|
||||
}
|
||||
|
||||
public Long getLong(Object key) {
|
||||
return this.getLong(key, -1L);
|
||||
}
|
||||
|
||||
public long getLong(Object key, long defaultValue) {
|
||||
Number value = this.getNumber(key);
|
||||
return value != null ? value.longValue() : defaultValue;
|
||||
}
|
||||
|
||||
public Float getFloat(Object key) {
|
||||
return this.getFloat(key, -1.0F);
|
||||
}
|
||||
|
||||
public float getFloat(Object key, float defaultValue) {
|
||||
Number value = this.getNumber(key);
|
||||
return value != null ? value.floatValue() : defaultValue;
|
||||
}
|
||||
|
||||
public Double getDouble(Object key) {
|
||||
return this.getDouble(key, (double)-1.0F);
|
||||
}
|
||||
|
||||
public double getDouble(Object key, double defaultValue) {
|
||||
Number value = this.getNumber(key);
|
||||
return value != null ? value.doubleValue() : defaultValue;
|
||||
}
|
||||
|
||||
private Number getNumber(Object key) {
|
||||
try {
|
||||
Object value = this.get(key);
|
||||
if (value instanceof String) {
|
||||
return Double.parseDouble((String)value);
|
||||
} else {
|
||||
return value instanceof Number ? (Number)value : null;
|
||||
}
|
||||
} catch (Exception var3) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public UUID getUuid(String key) {
|
||||
Object value = this.get(key);
|
||||
if (value == null) {
|
||||
return null;
|
||||
} else if (value instanceof UUID) {
|
||||
return (UUID)value;
|
||||
} else if (value instanceof String) {
|
||||
try {
|
||||
return UUID.fromString((String)value);
|
||||
} catch (Exception var4) {
|
||||
return null;
|
||||
}
|
||||
} else if (value instanceof byte[]) {
|
||||
try {
|
||||
byte[] bytes = (byte[])value;
|
||||
return bytes.length == 16 ? UUID.nameUUIDFromBytes((byte[])value) : null;
|
||||
} catch (Exception var5) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void convertUuid(String key) {
|
||||
Object value = this.get(key);
|
||||
if (!(value instanceof UUID)) {
|
||||
if (value instanceof String) {
|
||||
try {
|
||||
this.put(key, this.getUuid(key));
|
||||
} catch (Exception var4) {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public DbObject getDbObject(String... keys) {
|
||||
DbObject dbObject = this;
|
||||
|
||||
for(String key : keys) {
|
||||
Object value = dbObject.get(key);
|
||||
if (value == null) {
|
||||
Object var8 = new DbObject();
|
||||
dbObject.put(key, var8);
|
||||
dbObject = var8;
|
||||
} else if (value instanceof DbObject) {
|
||||
dbObject = (DbObject)value;
|
||||
} else if (value instanceof Map) {
|
||||
Object var9 = new DbObject((Map)value);
|
||||
dbObject.put(key, var9);
|
||||
dbObject = var9;
|
||||
} else {
|
||||
Object var10 = new DbObject();
|
||||
dbObject.put(key, var10);
|
||||
dbObject = var10;
|
||||
}
|
||||
}
|
||||
|
||||
return dbObject;
|
||||
}
|
||||
|
||||
public List getList(Object key, Class clazz) {
|
||||
if (clazz.equals(DbObject.class)) {
|
||||
List<Object> list = super.getList(key, Object.class);
|
||||
if (list != null) {
|
||||
List<T> listDbObject = new ArrayList();
|
||||
list.forEach((item) -> {
|
||||
if (item instanceof Map) {
|
||||
listDbObject.add(new DbObject((Map)item));
|
||||
}
|
||||
|
||||
});
|
||||
this.put((String)key, listDbObject);
|
||||
return listDbObject;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} else if (clazz.equals(UUID.class)) {
|
||||
List<Object> list = super.getList(key, Object.class);
|
||||
if (list != null) {
|
||||
List<T> listDbObject = new ArrayList();
|
||||
list.forEach((item) -> {
|
||||
if (item instanceof UUID) {
|
||||
listDbObject.add(item);
|
||||
} else if (item instanceof String) {
|
||||
listDbObject.add(UUID.fromString((String)item));
|
||||
}
|
||||
|
||||
});
|
||||
this.put((String)key, listDbObject);
|
||||
return listDbObject;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return super.getList(key, clazz);
|
||||
}
|
||||
}
|
||||
|
||||
public DbObject toPlat() {
|
||||
return toFlat((String)null, this);
|
||||
}
|
||||
|
||||
public static DbObject toFlat(String parentKey, DbObject nestedObj) {
|
||||
DbObject flatObj = new DbObject();
|
||||
String prefixKey = parentKey != null ? parentKey + "." : "";
|
||||
|
||||
for(Map.Entry entry : nestedObj.entrySet()) {
|
||||
Object value = entry.getValue();
|
||||
if (value instanceof DbObject) {
|
||||
flatObj.putAll(toFlat(prefixKey + (String)entry.getKey(), (DbObject)entry.getValue()));
|
||||
} else if (value instanceof Map) {
|
||||
flatObj.putAll(toFlat(prefixKey + (String)entry.getKey(), new DbObject((Map)entry.getValue())));
|
||||
} else {
|
||||
flatObj.put(prefixKey + (String)entry.getKey(), value);
|
||||
}
|
||||
}
|
||||
|
||||
return flatObj;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.mitac.cell.db.util;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
import com.mitac.cell.utils.McStringUtils;
|
||||
|
||||
public class JpaQuery {
|
||||
private StringBuilder sbColumns = new StringBuilder();
|
||||
private StringBuilder sbConditions = new StringBuilder();
|
||||
private String tableName;
|
||||
private String orderBy;
|
||||
|
||||
public JpaQuery(String tableName) {
|
||||
this.setTableName(tableName);
|
||||
}
|
||||
|
||||
public void setTableName(String tableName) {
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
public void setOrderBy(String orderBy) {
|
||||
this.orderBy = orderBy;
|
||||
}
|
||||
|
||||
public void addColumn(String column) {
|
||||
if (this.sbColumns.length() > 0) {
|
||||
this.sbColumns.append(", ");
|
||||
}
|
||||
|
||||
this.sbColumns.append(column);
|
||||
}
|
||||
|
||||
public void addColumn(String... column) {
|
||||
this.addColumn(Joiner.on(",").join(column));
|
||||
}
|
||||
|
||||
public void addJsonColumn(String dbColumn, String columnName) {
|
||||
String column = "CAST(COLUMN_JSON(" + dbColumn + ") AS CHAR) AS " + columnName;
|
||||
this.addColumn(column);
|
||||
}
|
||||
|
||||
public void addJsonColumn(String dbColumn, String dynamicColumn, String type, String columnName) {
|
||||
String column = "COLUMN_GET(" + dbColumn + ", " + dynamicColumn + " AS " + type + ") AS " + columnName;
|
||||
this.addColumn(column);
|
||||
}
|
||||
|
||||
public String toQuery() {
|
||||
StringBuilder sbQuery = new StringBuilder("SELECT ");
|
||||
if (this.sbColumns.length() == 0) {
|
||||
sbQuery.append(" * ");
|
||||
} else {
|
||||
sbQuery.append(this.sbColumns);
|
||||
}
|
||||
|
||||
sbQuery.append(" FROM ");
|
||||
sbQuery.append(this.tableName);
|
||||
if (this.sbConditions.length() > 0) {
|
||||
sbQuery.append(" WHERE ");
|
||||
sbQuery.append(this.sbConditions);
|
||||
}
|
||||
|
||||
if (McStringUtils.isValid(this.orderBy)) {
|
||||
sbQuery.append(" ORDER BY ");
|
||||
sbQuery.append(this.orderBy);
|
||||
}
|
||||
|
||||
return sbQuery.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.mitac.cell.db.util;
|
||||
|
||||
public class McDbUtils {
|
||||
public static int from(int page, int size) {
|
||||
return page * size;
|
||||
}
|
||||
|
||||
public static int to(int page, int size, int total) {
|
||||
++page;
|
||||
int max = page * size;
|
||||
return total - max > 0 ? max : total;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
package com.mitac.cell.db.util;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mitac.cell.utils.McJsonUtils;
|
||||
import com.mitac.cell.utils.McStringUtils;
|
||||
import com.mongodb.client.ListIndexesIterable;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoCursor;
|
||||
import com.mongodb.client.model.IndexOptions;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.LongSupplier;
|
||||
import java.util.regex.Pattern;
|
||||
import org.apache.commons.compress.utils.Sets;
|
||||
import org.bson.Document;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
import org.springframework.data.mongodb.core.MongoTemplate;
|
||||
import org.springframework.data.mongodb.core.query.Criteria;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
|
||||
public class McMongoUtils {
|
||||
public static Pageable toPageable(int page, int size, String sortBy, String direction) {
|
||||
Sort.Direction dir = toDirection(direction);
|
||||
return dir != null && !McStringUtils.isNullOrEmpty(sortBy) ? PageRequest.of(page, size, dir, new String[]{sortBy}) : PageRequest.of(page, size);
|
||||
}
|
||||
|
||||
public static Sort.Direction toDirection(String direction) {
|
||||
try {
|
||||
return Direction.valueOf(direction.trim().toUpperCase());
|
||||
} catch (Exception var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Query toQuery(JsonObject jFilter, String sortBy, Sort.Direction direction) {
|
||||
Sort sort = Strings.isNullOrEmpty(sortBy) ? null : Sort.by(direction, new String[]{sortBy});
|
||||
Query query = new Query();
|
||||
if (sort != null) {
|
||||
query.with(sort);
|
||||
}
|
||||
|
||||
if (jFilter != null && !jFilter.isJsonNull()) {
|
||||
addFilter(query, jFilter);
|
||||
return query;
|
||||
} else {
|
||||
return query;
|
||||
}
|
||||
}
|
||||
|
||||
public static void addFilter(Query query, JsonObject jFilter) {
|
||||
for(Map.Entry jElement : jFilter.entrySet()) {
|
||||
String key = (String)jElement.getKey();
|
||||
JsonElement jValue = (JsonElement)jElement.getValue();
|
||||
if (jValue.isJsonPrimitive()) {
|
||||
String value = jValue.getAsString();
|
||||
if (McStringUtils.isNullOrEmpty(value)) {
|
||||
query.addCriteria(toEmptyCriteria(key));
|
||||
} else if (key.equals("sites.siteUuid")) {
|
||||
Criteria criElem = toUuidCriteria("siteUuid", UUID.fromString(value));
|
||||
if (jFilter.has("sites.groupUuid")) {
|
||||
JsonElement jGroups = jFilter.get("sites.groupUuid");
|
||||
if (jGroups.isJsonNull()) {
|
||||
criElem.and("groupUuid").exists(false);
|
||||
} else if (jGroups.isJsonArray()) {
|
||||
criElem.andOperator(new Criteria[]{toOrCriteria("groupUuid", jGroups.getAsJsonArray())});
|
||||
}
|
||||
}
|
||||
|
||||
query.addCriteria(Criteria.where("sites").elemMatch(criElem));
|
||||
} else if (!key.equals("appInfo.versionCode") && !key.equals("appInfo.minSdkVersion") && !key.equals("appInfo.targetSdkVersion") && !key.equals("appInfo.maxSdkVersion")) {
|
||||
if (key.equals("otaInfo.skuId")) {
|
||||
query.addCriteria((new Criteria()).orOperator(new Criteria[]{toLikeCriteria(key, value), toLikeCriteria("otaInfo.customerId", value)}));
|
||||
} else if (key.contains(".")) {
|
||||
if (key.toLowerCase().endsWith("uuid")) {
|
||||
try {
|
||||
UUID uuid = UUID.fromString(value);
|
||||
query.addCriteria(toUuidCriteria(key, uuid));
|
||||
} catch (Exception var10) {
|
||||
query.addCriteria(toLikeCriteria(key, value));
|
||||
}
|
||||
} else {
|
||||
query.addCriteria(toLikeCriteria(key, value));
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
UUID uuid = UUID.fromString(value);
|
||||
query.addCriteria(toUuidCriteria(key, uuid));
|
||||
} catch (Exception var9) {
|
||||
query.addCriteria(toLikeCriteria(key, value));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
int version = Integer.parseInt(value);
|
||||
query.addCriteria(Criteria.where(key).is(version));
|
||||
} catch (Exception var11) {
|
||||
}
|
||||
}
|
||||
} else if (jValue.isJsonArray() && !key.equals("sites.groupUuid")) {
|
||||
JsonArray jItems = jValue.getAsJsonArray();
|
||||
if (jItems.size() >= 0) {
|
||||
query.addCriteria(toOrCriteria(key, jValue.getAsJsonArray()));
|
||||
} else {
|
||||
query.addCriteria(Criteria.where(key).exists(false));
|
||||
}
|
||||
} else if (jValue.isJsonNull() && !key.equals("sites.groupUuid")) {
|
||||
query.addCriteria(toEmptyCriteria(key));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static Criteria toCriteria(String jFilter) {
|
||||
return Strings.isNullOrEmpty(jFilter) ? new Criteria() : toCriteria(McJsonUtils.toJsonElement(jFilter).getAsJsonObject());
|
||||
}
|
||||
|
||||
public static Criteria toCriteria(JsonObject jFilter) {
|
||||
if (jFilter.size() == 0) {
|
||||
return new Criteria();
|
||||
} else {
|
||||
List<Criteria> criterias = new ArrayList();
|
||||
|
||||
for(Map.Entry entry : jFilter.entrySet()) {
|
||||
String key = (String)entry.getKey();
|
||||
JsonElement jValue = (JsonElement)entry.getValue();
|
||||
if (jValue.isJsonPrimitive()) {
|
||||
String value = jValue.getAsString();
|
||||
if (Strings.isNullOrEmpty(value)) {
|
||||
criterias.add(Criteria.where(key).exists(false));
|
||||
} else if (key.equals("sites.siteUuid")) {
|
||||
Criteria criElem = toUuidCriteria("siteUuid", UUID.fromString(value));
|
||||
if (jFilter.has("sites.groupUuid")) {
|
||||
JsonElement jGroups = jFilter.get("sites.groupUuid");
|
||||
if (jGroups.isJsonNull()) {
|
||||
criElem.and("groupUuid").exists(false);
|
||||
} else if (jGroups.isJsonArray()) {
|
||||
criElem.andOperator(new Criteria[]{toOrCriteria("groupUuid", jGroups.getAsJsonArray())});
|
||||
}
|
||||
}
|
||||
|
||||
criterias.add(Criteria.where("sites").elemMatch(criElem));
|
||||
} else if (!key.endsWith("versionCode") && !key.endsWith("SdkVersion")) {
|
||||
try {
|
||||
UUID uuid = UUID.fromString(value);
|
||||
criterias.add(Criteria.where(key).is(uuid));
|
||||
} catch (Exception var13) {
|
||||
criterias.add(Criteria.where(key).regex(escapedPattern(value)));
|
||||
}
|
||||
} else {
|
||||
criterias.add(Criteria.where(key).is(jValue.getAsLong()));
|
||||
}
|
||||
} else if (jValue.isJsonArray() && !key.equals("sites.groupUuid")) {
|
||||
JsonArray jItems = jValue.getAsJsonArray();
|
||||
if (jItems.size() <= 0) {
|
||||
criterias.add(Criteria.where(key).exists(false));
|
||||
} else {
|
||||
List<Criteria> subCriterias = new ArrayList();
|
||||
|
||||
for(JsonElement jItem : jItems) {
|
||||
if (!jItem.isJsonNull()) {
|
||||
String item = jItem.getAsString();
|
||||
|
||||
try {
|
||||
UUID uuid = UUID.fromString(item);
|
||||
subCriterias.add(Criteria.where(key).is(uuid));
|
||||
} catch (Exception var12) {
|
||||
subCriterias.add(Criteria.where(key).regex(escapedPattern(item)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!subCriterias.isEmpty()) {
|
||||
criterias.add((new Criteria()).orOperator((Criteria[])subCriterias.toArray(new Criteria[0])));
|
||||
}
|
||||
}
|
||||
} else if (jValue.isJsonNull() && !key.equals("sites.groupUuid")) {
|
||||
criterias.add(Criteria.where(key).exists(false));
|
||||
}
|
||||
}
|
||||
|
||||
return (new Criteria()).andOperator((Criteria[])criterias.toArray(new Criteria[0]));
|
||||
}
|
||||
}
|
||||
|
||||
public static Pattern escapedPattern(String value) {
|
||||
return Pattern.compile(Pattern.quote(value), 66);
|
||||
}
|
||||
|
||||
public static Criteria toLikeCriteria(String key, String regex) {
|
||||
return Criteria.where(key).regex(escapedPattern(regex));
|
||||
}
|
||||
|
||||
public static Criteria toOrCriteria(String key, JsonArray jArray) {
|
||||
Criteria criteria = new Criteria();
|
||||
List<Criteria> subCriterias = new ArrayList();
|
||||
|
||||
for(JsonElement jElement : jArray) {
|
||||
if (!jElement.isJsonNull()) {
|
||||
String value = jElement.getAsString();
|
||||
|
||||
try {
|
||||
UUID uuid = UUID.fromString(value);
|
||||
subCriterias.add(toUuidCriteria(key, uuid));
|
||||
} catch (Exception var8) {
|
||||
subCriterias.add(toLikeCriteria(key, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (subCriterias.size() > 0) {
|
||||
criteria.orOperator((Criteria[])subCriterias.toArray(new Criteria[0]));
|
||||
}
|
||||
|
||||
return criteria;
|
||||
}
|
||||
|
||||
public static Criteria toUuidCriteria(String key, UUID uuid) {
|
||||
return Criteria.where(key).is(uuid);
|
||||
}
|
||||
|
||||
public static Criteria toEmptyCriteria(String key) {
|
||||
return Criteria.where(key).exists(false);
|
||||
}
|
||||
|
||||
public static LongSupplier toTotalSupplier(final long total) {
|
||||
return new LongSupplier() {
|
||||
public long getAsLong() {
|
||||
return total;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static void createIndex(MongoTemplate mongoTemplate, String collectionName, Document keys, String indexName, Boolean isUnique, Long expireAfter) {
|
||||
MongoCollection<Document> collection = mongoTemplate.collectionExists(collectionName) ? mongoTemplate.getCollection(collectionName) : mongoTemplate.createCollection(collectionName);
|
||||
IndexOptions options = new IndexOptions();
|
||||
if (!Strings.isNullOrEmpty(indexName)) {
|
||||
options.name(indexName);
|
||||
}
|
||||
|
||||
if (isUnique != null) {
|
||||
options.unique(isUnique);
|
||||
}
|
||||
|
||||
if (expireAfter != null) {
|
||||
options.expireAfter(expireAfter, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
Set<String> keySet = keys.keySet();
|
||||
ListIndexesIterable<Document> indexes = collection.listIndexes();
|
||||
if (indexes != null) {
|
||||
Document curIndex = null;
|
||||
MongoCursor var11 = indexes.iterator();
|
||||
|
||||
while(var11.hasNext()) {
|
||||
Document index = (Document)var11.next();
|
||||
Document keyMap = (Document)index.get("key", Document.class);
|
||||
Set<String> sets = keyMap.keySet();
|
||||
if (sets.equals(keySet)) {
|
||||
curIndex = index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (curIndex != null) {
|
||||
boolean isSame = true;
|
||||
if (isUnique == null) {
|
||||
if (curIndex.containsKey("unique")) {
|
||||
isSame = false;
|
||||
}
|
||||
} else if (!curIndex.containsKey("unique") || !curIndex.get("unique").equals(isUnique)) {
|
||||
isSame = false;
|
||||
}
|
||||
|
||||
if (expireAfter == null) {
|
||||
if (curIndex.containsKey("expireAfterSeconds")) {
|
||||
isSame = false;
|
||||
}
|
||||
} else if (!curIndex.containsKey("expireAfterSeconds") || !curIndex.get("expireAfterSeconds").equals(expireAfter)) {
|
||||
isSame = false;
|
||||
}
|
||||
|
||||
if (isSame) {
|
||||
return;
|
||||
}
|
||||
|
||||
collection.dropIndex((String)curIndex.get("name"));
|
||||
}
|
||||
}
|
||||
|
||||
collection.createIndex(keys, options);
|
||||
}
|
||||
|
||||
public static void dropIndex(MongoTemplate mongoTemplate, String collectionName, String... fields) {
|
||||
if (mongoTemplate.collectionExists(collectionName)) {
|
||||
MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
|
||||
ListIndexesIterable<Document> indexes = collection.listIndexes();
|
||||
if (indexes != null) {
|
||||
Set<String> keySet = Sets.newHashSet(fields);
|
||||
MongoCursor var6 = indexes.iterator();
|
||||
|
||||
while(var6.hasNext()) {
|
||||
Document index = (Document)var6.next();
|
||||
Document keyMap = (Document)index.get("key", Document.class);
|
||||
if (keyMap.keySet().equals(keySet)) {
|
||||
collection.dropIndex(index.getString("name"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.mitac.cell.db.util;
|
||||
|
||||
public class McPipeLine {
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package com.mitac.cell.doc;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public class Csv {
|
||||
private final char separator;
|
||||
private final char quoteChar;
|
||||
private final char escapeChar;
|
||||
private final boolean strictQuotes;
|
||||
private boolean inToken;
|
||||
private final boolean ignoreLeadingWhiteSpace;
|
||||
public static final char DEFAULT_SEPARATOR = ',';
|
||||
public static final char DEFAULT_QUOTE_CHARACTER = '"';
|
||||
public static final char DEFAULT_ESCAPE_CHARACTER = '\\';
|
||||
public static final char NULL_CHARACTER = '\u0000';
|
||||
public static final String DEFAULT_LINE_END = "\n";
|
||||
public static final char NO_QUOTE_CHARACTER = '\u0000';
|
||||
public static final char NO_ESCAPE_CHARACTER = '\u0000';
|
||||
|
||||
public Csv() {
|
||||
this(',', '"', '\\');
|
||||
}
|
||||
|
||||
public Csv(char separator) {
|
||||
this(separator, '"', '\\');
|
||||
}
|
||||
|
||||
public Csv(char separator, char quoteChar) {
|
||||
this(separator, quoteChar, '\\');
|
||||
}
|
||||
|
||||
public Csv(char separator, char quoteChar, char escape) {
|
||||
this(separator, quoteChar, escape, false);
|
||||
}
|
||||
|
||||
public Csv(char separator, char quoteChar, char escape, boolean strictQuotes) {
|
||||
this(separator, quoteChar, escape, strictQuotes, true, "\n");
|
||||
}
|
||||
|
||||
public Csv(char separator, char quoteChar, char escape, boolean strictQuotes, boolean ignoreLeadingWhiteSpace, String lineEnd) {
|
||||
this.inToken = false;
|
||||
if (this.anyCharactersAreTheSame(separator, quoteChar, escape)) {
|
||||
throw new UnsupportedOperationException("The separator, quote character, and escape character must be different!");
|
||||
} else if (separator == 0) {
|
||||
throw new UnsupportedOperationException("The separator character can't be null!");
|
||||
} else {
|
||||
this.separator = separator;
|
||||
this.quoteChar = quoteChar;
|
||||
this.escapeChar = escape;
|
||||
this.strictQuotes = strictQuotes;
|
||||
this.ignoreLeadingWhiteSpace = ignoreLeadingWhiteSpace;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean anyCharactersAreTheSame(char separator, char quoteChar, char escape) {
|
||||
return this.isSameCharacter(separator, quoteChar) || this.isSameCharacter(separator, escape) || this.isSameCharacter(quoteChar, escape);
|
||||
}
|
||||
|
||||
private boolean isSameCharacter(char c1, char c2) {
|
||||
return c1 != 0 && c1 == c2;
|
||||
}
|
||||
|
||||
public String[] parse(String csvText) throws IOException {
|
||||
if (csvText == null) {
|
||||
return null;
|
||||
} else {
|
||||
List<String> tokenList = new ArrayList();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
boolean inQuotes = false;
|
||||
|
||||
for(int i = 0; i < csvText.length(); ++i) {
|
||||
char c = csvText.charAt(i);
|
||||
if (c == this.escapeChar) {
|
||||
if (this.isNextCharacterEscapable(csvText, inQuotes || this.inToken, i)) {
|
||||
sb.append(csvText.charAt(i + 1));
|
||||
++i;
|
||||
}
|
||||
} else if (c == this.quoteChar) {
|
||||
if (this.isNextCharacterEscapedQuote(csvText, inQuotes || this.inToken, i)) {
|
||||
sb.append(csvText.charAt(i + 1));
|
||||
++i;
|
||||
} else {
|
||||
if (!this.strictQuotes && i > 2 && csvText.charAt(i - 1) != this.separator && csvText.length() > i + 1 && csvText.charAt(i + 1) != this.separator) {
|
||||
if (this.ignoreLeadingWhiteSpace && sb.length() > 0 && this.isAllWhiteSpace(sb)) {
|
||||
sb.setLength(0);
|
||||
} else {
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
|
||||
inQuotes = !inQuotes;
|
||||
}
|
||||
|
||||
this.inToken = !this.inToken;
|
||||
} else if (c == this.separator && !inQuotes) {
|
||||
tokenList.add(sb.toString());
|
||||
sb.setLength(0);
|
||||
this.inToken = false;
|
||||
} else if (!this.strictQuotes || inQuotes) {
|
||||
sb.append(c);
|
||||
this.inToken = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (sb != null) {
|
||||
tokenList.add(sb.toString());
|
||||
}
|
||||
|
||||
return (String[])tokenList.toArray(new String[tokenList.size()]);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isNextCharacterEscapedQuote(String csvText, boolean inQuotes, int i) {
|
||||
int nextIndex = i + 1;
|
||||
return inQuotes && csvText.length() > nextIndex && csvText.charAt(nextIndex) == this.quoteChar;
|
||||
}
|
||||
|
||||
protected boolean isNextCharacterEscapable(String csvText, boolean inQuotes, int i) {
|
||||
int nextIndex = i + 1;
|
||||
char nextChar = csvText.charAt(nextIndex);
|
||||
return inQuotes && csvText.length() > nextIndex && (nextChar == this.quoteChar || csvText.charAt(nextIndex) == this.escapeChar);
|
||||
}
|
||||
|
||||
protected boolean isAllWhiteSpace(CharSequence sb) {
|
||||
boolean result = true;
|
||||
|
||||
for(int i = 0; i < sb.length(); ++i) {
|
||||
char c = sb.charAt(i);
|
||||
if (!Character.isWhitespace(c)) {
|
||||
result = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public String toString(String[] columns) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for(int i = 0; i < columns.length; ++i) {
|
||||
if (i != 0) {
|
||||
sb.append(this.separator);
|
||||
}
|
||||
|
||||
String nextElement = columns[i];
|
||||
if (nextElement != null) {
|
||||
if (this.quoteChar != 0) {
|
||||
sb.append(this.quoteChar);
|
||||
}
|
||||
|
||||
sb.append((CharSequence)(this.stringContainsSpecialCharacters(nextElement) ? this.processLine(nextElement) : nextElement));
|
||||
if (this.quoteChar != 0) {
|
||||
sb.append(this.quoteChar);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public String toString(Object[] columns) {
|
||||
List<String> list = new ArrayList();
|
||||
|
||||
for(Object obj : columns) {
|
||||
list.add(obj.toString());
|
||||
}
|
||||
|
||||
return this.toString(list);
|
||||
}
|
||||
|
||||
public String toString(ArrayList columns) {
|
||||
List<String> list = new ArrayList();
|
||||
|
||||
for(Object obj : columns) {
|
||||
list.add(obj.toString());
|
||||
}
|
||||
|
||||
return this.toString(list);
|
||||
}
|
||||
|
||||
public String toString(Set columns) {
|
||||
List<String> list = new ArrayList(columns);
|
||||
return this.toString(list);
|
||||
}
|
||||
|
||||
public String toString(List columns) {
|
||||
return this.toString((String[])columns.toArray());
|
||||
}
|
||||
|
||||
private boolean stringContainsSpecialCharacters(String line) {
|
||||
return line.indexOf(this.quoteChar) != -1 || line.indexOf(this.escapeChar) != -1;
|
||||
}
|
||||
|
||||
protected StringBuilder processLine(String nextElement) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for(int j = 0; j < nextElement.length(); ++j) {
|
||||
char nextChar = nextElement.charAt(j);
|
||||
if (this.escapeChar != 0 && nextChar == this.quoteChar) {
|
||||
sb.append(this.escapeChar).append(nextChar);
|
||||
} else if (this.escapeChar != 0 && nextChar == this.escapeChar) {
|
||||
sb.append(this.escapeChar).append(nextChar);
|
||||
} else {
|
||||
sb.append(nextChar);
|
||||
}
|
||||
}
|
||||
|
||||
return sb;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.mitac.cell.doc;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
public abstract class CsvReader {
|
||||
private BufferedReader reader;
|
||||
|
||||
public CsvReader(String path) throws FileNotFoundException {
|
||||
this(new File(path));
|
||||
}
|
||||
|
||||
public CsvReader(File file) {
|
||||
try {
|
||||
this.reader = new BufferedReader(new FileReader(file));
|
||||
} catch (FileNotFoundException var3) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public CsvReader(InputStream input) {
|
||||
this.reader = new BufferedReader(new InputStreamReader(input));
|
||||
}
|
||||
|
||||
public abstract void onNewRow(int var1, String[] var2);
|
||||
|
||||
public void onEnd() {
|
||||
}
|
||||
|
||||
public void parseAll() {
|
||||
try {
|
||||
int lineNum = 0;
|
||||
|
||||
String line;
|
||||
while((line = this.reader.readLine()) != null) {
|
||||
String[] row = (new Csv()).parse(line);
|
||||
this.onNewRow(lineNum++, row);
|
||||
}
|
||||
|
||||
this.reader.close();
|
||||
this.onEnd();
|
||||
} catch (IOException var4) {
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.mitac.cell.doc;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import com.google.common.base.Strings;
|
||||
import com.mitac.cell.utils.McNumberUtils;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.CellType;
|
||||
|
||||
public class ExcelCell {
|
||||
public int columnIndex;
|
||||
public int rowIndex;
|
||||
public String cellName;
|
||||
public String value;
|
||||
|
||||
public ExcelCell(String cellName, String value) {
|
||||
this.cellName = cellName;
|
||||
this.value = value;
|
||||
this.columnIndex = this.getColumnIndex(cellName);
|
||||
this.rowIndex = this.getRowIndex(cellName);
|
||||
}
|
||||
|
||||
public String getColumnName() {
|
||||
return CharMatcher.inRange('0', '9').removeFrom(this.cellName);
|
||||
}
|
||||
|
||||
public int getColumnIndex() {
|
||||
return this.columnIndex;
|
||||
}
|
||||
|
||||
private int getRowIndex(String cellName) {
|
||||
return Integer.parseInt(CharMatcher.inRange('0', '9').retainFrom(cellName)) - 1;
|
||||
}
|
||||
|
||||
private int getColumnIndex(String cellName) {
|
||||
String columnName = CharMatcher.inRange('0', '9').removeFrom(cellName).toUpperCase();
|
||||
String reversedName = (new StringBuffer(columnName)).reverse().toString();
|
||||
int index = 0;
|
||||
|
||||
for(int i = 0; i < reversedName.length(); ++i) {
|
||||
int n = reversedName.charAt(i) - 65;
|
||||
index += i == 0 ? n : 0 + i * 26 * (n + 1);
|
||||
}
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public int toInteger() {
|
||||
return McNumberUtils.toInt(this.value);
|
||||
}
|
||||
|
||||
public float toFloat() {
|
||||
return McNumberUtils.toFloat(this.value);
|
||||
}
|
||||
|
||||
public static boolean isEmpty(Cell cell) {
|
||||
if (cell == null) {
|
||||
return true;
|
||||
} else {
|
||||
CellType cellType = cell.getCellType();
|
||||
if (cellType != CellType._NONE && cellType != CellType.BLANK) {
|
||||
return cellType == CellType.STRING ? Strings.isNullOrEmpty(cell.getStringCellValue().trim()) : false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package com.mitac.cell.doc;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Iterator;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.parsers.SAXParserFactory;
|
||||
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
|
||||
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
|
||||
import org.apache.poi.openxml4j.opc.OPCPackage;
|
||||
import org.apache.poi.xssf.eventusermodel.XSSFReader;
|
||||
import org.apache.poi.xssf.model.SharedStrings;
|
||||
import org.xml.sax.Attributes;
|
||||
import org.xml.sax.ContentHandler;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.SAXException;
|
||||
import org.xml.sax.XMLReader;
|
||||
import org.xml.sax.helpers.DefaultHandler;
|
||||
|
||||
public abstract class ExcelReader {
|
||||
private XMLReader xmlReader;
|
||||
private XSSFReader xssfReader;
|
||||
|
||||
public ExcelReader(String path) {
|
||||
try {
|
||||
OPCPackage pkg = OPCPackage.open(path);
|
||||
this.setPackage(pkg);
|
||||
} catch (InvalidFormatException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public ExcelReader(File file) {
|
||||
try {
|
||||
OPCPackage pkg = OPCPackage.open(file);
|
||||
this.setPackage(pkg);
|
||||
} catch (InvalidFormatException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public ExcelReader(InputStream is) {
|
||||
try {
|
||||
OPCPackage pkg = OPCPackage.open(is);
|
||||
this.setPackage(pkg);
|
||||
} catch (InvalidFormatException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void setPackage(OPCPackage pkg) {
|
||||
try {
|
||||
this.xssfReader = new XSSFReader(pkg);
|
||||
SharedStrings stringsTable = this.xssfReader.getSharedStringsTable();
|
||||
this.xmlReader = this.fetchSheetParser(stringsTable);
|
||||
} catch (InvalidFormatException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (OpenXML4JException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void parceSheet(String sheetName) {
|
||||
try {
|
||||
InputStream sheetIS = this.xssfReader.getSheet(sheetName);
|
||||
InputSource sheetSource = new InputSource(sheetIS);
|
||||
this.xmlReader.parse(sheetSource);
|
||||
sheetIS.close();
|
||||
} catch (InvalidFormatException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (SAXException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void parseAll() {
|
||||
try {
|
||||
Iterator<InputStream> sheets = this.xssfReader.getSheetsData();
|
||||
|
||||
while(sheets.hasNext()) {
|
||||
InputStream is = (InputStream)sheets.next();
|
||||
InputSource sheetSource = new InputSource(is);
|
||||
this.xmlReader.parse(sheetSource);
|
||||
is.close();
|
||||
}
|
||||
} catch (InvalidFormatException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (SAXException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public XMLReader fetchSheetParser(SharedStrings stringsTable) {
|
||||
XMLReader xmlReader = this.xmlReader();
|
||||
ContentHandler handler = new SheetHandler(stringsTable);
|
||||
xmlReader.setContentHandler(handler);
|
||||
return xmlReader;
|
||||
}
|
||||
|
||||
public XMLReader xmlReader() {
|
||||
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
|
||||
|
||||
try {
|
||||
return parserFactory.newSAXParser().getXMLReader();
|
||||
} catch (SAXException | ParserConfigurationException e) {
|
||||
((Exception)e).printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public abstract void onSheetDataStart();
|
||||
|
||||
public abstract boolean onNewRow(ExcelRow var1);
|
||||
|
||||
public abstract void onSheetDataEnd();
|
||||
|
||||
private class SheetHandler extends DefaultHandler {
|
||||
private static final String CELL_NUM = "r";
|
||||
private static final String CELL_TYPE = "t";
|
||||
private SharedStrings stringsTable;
|
||||
private ExcelRow row = null;
|
||||
private String curCellName = null;
|
||||
private String curCellType = null;
|
||||
private String curCellValue;
|
||||
|
||||
private SheetHandler(SharedStrings stringsTable) {
|
||||
this.stringsTable = stringsTable;
|
||||
}
|
||||
|
||||
public void startElement(String uri, String localName, String name, Attributes attributes) {
|
||||
if (name.equals("row")) {
|
||||
this.row = new ExcelRow();
|
||||
} else if (name.equals("c")) {
|
||||
this.curCellValue = "";
|
||||
this.curCellName = attributes.getValue("r");
|
||||
this.curCellType = attributes.getValue("t");
|
||||
} else if (name.equals("sheetData")) {
|
||||
ExcelReader.this.onSheetDataStart();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void endElement(String uri, String localName, String name) {
|
||||
if (name.equals("row")) {
|
||||
ExcelReader.this.onNewRow(this.row);
|
||||
} else if (name.equals("c")) {
|
||||
if (this.isStringCell()) {
|
||||
int idx = Integer.parseInt(this.curCellValue);
|
||||
this.curCellValue = this.stringsTable.getItemAt(idx).getString();
|
||||
this.curCellType = null;
|
||||
}
|
||||
|
||||
this.row.addCell(this.curCellName, this.curCellValue);
|
||||
} else if (name.equals("sheetData")) {
|
||||
ExcelReader.this.onSheetDataEnd();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void characters(char[] ch, int start, int length) {
|
||||
String var10001 = this.curCellValue;
|
||||
this.curCellValue = var10001 + new String(ch, start, length);
|
||||
}
|
||||
|
||||
private boolean isStringCell() {
|
||||
return this.curCellType != null && this.curCellType.equals("s");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.mitac.cell.doc;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
|
||||
public class ExcelRow extends HashMap {
|
||||
private static final long serialVersionUID = -2035806587539130093L;
|
||||
|
||||
public void addCell(String cellName, String value) {
|
||||
ExcelCell cell = new ExcelCell(cellName, value);
|
||||
this.put(cell.columnIndex, cell);
|
||||
}
|
||||
|
||||
public int getRowIndex() {
|
||||
return this.size() > 0 ? ((ExcelCell)this.get(0)).rowIndex : -1;
|
||||
}
|
||||
|
||||
public String getString(int columnIndex) {
|
||||
ExcelCell cell = (ExcelCell)this.get(columnIndex);
|
||||
return cell == null ? "" : cell.toString();
|
||||
}
|
||||
|
||||
public int getInteger(int columnIndex) {
|
||||
ExcelCell cell = (ExcelCell)this.get(columnIndex);
|
||||
return cell == null ? 0 : cell.toInteger();
|
||||
}
|
||||
|
||||
public float getFloat(int columnIndex) {
|
||||
ExcelCell cell = (ExcelCell)this.get(columnIndex);
|
||||
return cell == null ? 0.0F : cell.toFloat();
|
||||
}
|
||||
|
||||
public static boolean isEmpty(Row row) {
|
||||
if (row != null && row.getPhysicalNumberOfCells() != 0) {
|
||||
Iterator<Cell> it = row.cellIterator();
|
||||
|
||||
while(it.hasNext()) {
|
||||
Cell cell = (Cell)it.next();
|
||||
if (!ExcelCell.isEmpty(cell)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,783 @@
|
||||
package com.mitac.cell.doc;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
import javax.imageio.ImageIO;
|
||||
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
|
||||
import org.apache.poi.hssf.util.HSSFColor;
|
||||
import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
|
||||
import org.apache.poi.ooxml.POIXMLProperties;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.CellStyle;
|
||||
import org.apache.poi.ss.usermodel.ClientAnchor;
|
||||
import org.apache.poi.ss.usermodel.Color;
|
||||
import org.apache.poi.ss.usermodel.ConditionalFormattingRule;
|
||||
import org.apache.poi.ss.usermodel.CreationHelper;
|
||||
import org.apache.poi.ss.usermodel.Drawing;
|
||||
import org.apache.poi.ss.usermodel.FontFormatting;
|
||||
import org.apache.poi.ss.usermodel.HorizontalAlignment;
|
||||
import org.apache.poi.ss.usermodel.PatternFormatting;
|
||||
import org.apache.poi.ss.usermodel.Picture;
|
||||
import org.apache.poi.ss.usermodel.RichTextString;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.SheetConditionalFormatting;
|
||||
import org.apache.poi.ss.usermodel.VerticalAlignment;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
|
||||
import org.apache.poi.xssf.usermodel.XSSFColor;
|
||||
import org.apache.poi.xssf.usermodel.XSSFFont;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.bouncycastle.util.encoders.Hex;
|
||||
|
||||
public class ExcelWriter {
|
||||
public static final String INTEGER_COMMA_FORMAT = "#,##0";
|
||||
public static final String FLOAT_COMMA_FORMAT = "#,##0.00";
|
||||
private XSSFWorkbook workbook;
|
||||
private POIXMLProperties properties;
|
||||
private CreationHelper createHelper;
|
||||
private Sheet activeSheet;
|
||||
Map fontMap;
|
||||
Map styleMap;
|
||||
private CellStyle tempStyle;
|
||||
|
||||
public ExcelWriter() {
|
||||
this((InputStream)null);
|
||||
}
|
||||
|
||||
public ExcelWriter(File input) throws FileNotFoundException {
|
||||
this((InputStream)(new FileInputStream(input)));
|
||||
}
|
||||
|
||||
public ExcelWriter(InputStream input) {
|
||||
this.fontMap = new HashMap();
|
||||
this.styleMap = new HashMap();
|
||||
|
||||
try {
|
||||
this.workbook = input == null ? new XSSFWorkbook() : new XSSFWorkbook(input);
|
||||
this.init();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void init() {
|
||||
this.properties = this.workbook.getProperties();
|
||||
this.createHelper = this.workbook.getCreationHelper();
|
||||
this.tempStyle = this.workbook.createCellStyle();
|
||||
this.initActiveSheet();
|
||||
}
|
||||
|
||||
public void close() {
|
||||
try {
|
||||
this.workbook.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public POIXMLProperties.CoreProperties getCoreProperty() {
|
||||
return this.properties.getCoreProperties();
|
||||
}
|
||||
|
||||
public POIXMLProperties.CustomProperties getCustomProperty() {
|
||||
return this.properties.getCustomProperties();
|
||||
}
|
||||
|
||||
public int getNumberOfSheets() {
|
||||
return this.workbook.getNumberOfSheets();
|
||||
}
|
||||
|
||||
public int getActiveSheetIndex() {
|
||||
return this.workbook.getActiveSheetIndex();
|
||||
}
|
||||
|
||||
public Sheet getSheet(int index) {
|
||||
return this.workbook.getSheetAt(index);
|
||||
}
|
||||
|
||||
public Sheet addSheet(String sheetName) {
|
||||
this.activeSheet = Strings.isNullOrEmpty(sheetName) ? this.workbook.createSheet() : this.workbook.createSheet(sheetName);
|
||||
this.setActive(this.activeSheet);
|
||||
return this.activeSheet;
|
||||
}
|
||||
|
||||
public void removeSheet(int index) {
|
||||
if (index >= 0 && index < this.getNumberOfSheets()) {
|
||||
this.workbook.removeSheetAt(index);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void removeSheet(String... sheetNames) {
|
||||
for(String sheetName : sheetNames) {
|
||||
int sheetIndex = this.workbook.getSheetIndex(sheetName);
|
||||
if (sheetIndex >= 0) {
|
||||
this.removeSheet(sheetIndex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void setColumns(String... names) {
|
||||
this.setRow(0, (Object[])names);
|
||||
this.activeSheet.createFreezePane(0, 1);
|
||||
}
|
||||
|
||||
public void setColumns(int rowNum, String... names) {
|
||||
this.setRow(rowNum, (Object[])names);
|
||||
this.activeSheet.createFreezePane(0, 1);
|
||||
}
|
||||
|
||||
public void freezeRows(int rowNum) {
|
||||
this.freeze(rowNum, 0);
|
||||
}
|
||||
|
||||
public void freeze(int rowNum, int colNum) {
|
||||
this.activeSheet.createFreezePane(colNum, rowNum);
|
||||
}
|
||||
|
||||
public void setAutoSizeColumn(int colIndex) {
|
||||
int orgWidth = this.activeSheet.getColumnWidth(colIndex);
|
||||
this.activeSheet.autoSizeColumn(colIndex);
|
||||
float newWidth = (float)this.activeSheet.getColumnWidth(colIndex);
|
||||
if (newWidth < (float)orgWidth) {
|
||||
this.activeSheet.setColumnWidth(colIndex, orgWidth);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void setAutoSizeColumns() {
|
||||
this.setAutoSizeColumns(0, this.getLastColIndex());
|
||||
}
|
||||
|
||||
public void setAutoSizeColumns(int colFrom, int colTo) {
|
||||
for(int i = colFrom; i <= colTo; ++i) {
|
||||
this.setAutoSizeColumn(i);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void setAutoSizeColumns(int... colIndexes) {
|
||||
for(int colIndex : colIndexes) {
|
||||
this.setAutoSizeColumn(colIndex);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void setColumnFormat(int colIndex, short formatNo) {
|
||||
CellStyle style = this.workbook.createCellStyle();
|
||||
style.setDataFormat(formatNo);
|
||||
this.activeSheet.setDefaultColumnStyle(colIndex, style);
|
||||
}
|
||||
|
||||
public void setColumnFormat(int colIndex, String format) {
|
||||
short formatNo = this.createHelper.createDataFormat().getFormat(format);
|
||||
this.setColumnFormat(colIndex, formatNo);
|
||||
}
|
||||
|
||||
public Row getRow(int rowNo) {
|
||||
Row row = this.activeSheet.getRow(rowNo);
|
||||
if (row == null) {
|
||||
row = this.activeSheet.createRow(rowNo);
|
||||
}
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
public Cell getCell(int rowNo, int colNo) {
|
||||
return this.getCell(this.getRow(rowNo), colNo);
|
||||
}
|
||||
|
||||
public Cell getCell(Row row, int colNo) {
|
||||
Cell cell = row.getCell(colNo);
|
||||
if (cell == null) {
|
||||
cell = row.createCell(colNo);
|
||||
}
|
||||
|
||||
return cell;
|
||||
}
|
||||
|
||||
public CellStyle getCellStyle(int rowNo, int colNo) {
|
||||
return this.getCell(rowNo, colNo).getCellStyle();
|
||||
}
|
||||
|
||||
public void setRow(int rowNo, Object... values) {
|
||||
Row row = this.getRow(rowNo);
|
||||
|
||||
for(int i = 0; i < values.length; ++i) {
|
||||
Object value = values[i];
|
||||
if (value != null) {
|
||||
this.setCell(this.getCell(row, i), value);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void initActiveSheet() {
|
||||
int index = this.getActiveSheetIndex();
|
||||
this.activeSheet = this.workbook.getSheetAt(index);
|
||||
}
|
||||
|
||||
public Sheet getActiveSheet() {
|
||||
if (this.activeSheet == null) {
|
||||
this.initActiveSheet();
|
||||
}
|
||||
|
||||
return this.activeSheet;
|
||||
}
|
||||
|
||||
public boolean setActive(int sheetIndex) {
|
||||
if (sheetIndex >= 0 && sheetIndex < this.getNumberOfSheets()) {
|
||||
this.activeSheet = this.workbook.getSheetAt(sheetIndex);
|
||||
this.workbook.setActiveSheet(sheetIndex);
|
||||
this.workbook.setSelectedTab(sheetIndex);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean setActive(String name) {
|
||||
this.activeSheet = this.workbook.getSheet(name);
|
||||
return this.setActive(this.activeSheet);
|
||||
}
|
||||
|
||||
public boolean setActive(Sheet sheet) {
|
||||
return this.setActive(this.workbook.getSheetIndex(sheet));
|
||||
}
|
||||
|
||||
public Sheet getSheet(String sheetName) {
|
||||
return this.workbook.getSheet(sheetName);
|
||||
}
|
||||
|
||||
public void changeSheet(String oldName, String newName) {
|
||||
int index = this.workbook.getSheetIndex(oldName);
|
||||
if (index >= 0) {
|
||||
this.workbook.setSheetName(index, newName);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void changeSheet(int index, String newName) {
|
||||
if (index >= 0) {
|
||||
this.workbook.setSheetName(index, newName);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void setCell(String cellId, Object value) {
|
||||
this.setCell(this.getCell(cellId), value);
|
||||
}
|
||||
|
||||
public void setCell(int rowNo, int colNo, Object value) {
|
||||
this.setCell(rowNo, colNo, value, (CellStyle)null);
|
||||
}
|
||||
|
||||
public void setCell(int rowNo, int colNo, Object value, CellStyle style) {
|
||||
Row row = this.activeSheet.getRow(rowNo);
|
||||
if (row == null) {
|
||||
row = this.activeSheet.createRow(rowNo);
|
||||
}
|
||||
|
||||
Cell cell = row.getCell(colNo);
|
||||
if (cell == null) {
|
||||
cell = row.createCell(colNo);
|
||||
}
|
||||
|
||||
this.setCell(cell, value, style);
|
||||
}
|
||||
|
||||
public CellStyle newCellStyle() {
|
||||
return this.workbook.createCellStyle();
|
||||
}
|
||||
|
||||
public CellStyle clone(CellStyle style) {
|
||||
CellStyle newStyle = this.newCellStyle();
|
||||
newStyle.cloneStyleFrom(style);
|
||||
return newStyle;
|
||||
}
|
||||
|
||||
public CreationHelper getCreationHelper() {
|
||||
return this.workbook.getCreationHelper();
|
||||
}
|
||||
|
||||
public short getCustomDataFormat(String format) {
|
||||
return this.getCreationHelper().createDataFormat().getFormat(format);
|
||||
}
|
||||
|
||||
public void setCell(Cell cell, Object value) {
|
||||
this.setCell(cell, value, (CellStyle)null);
|
||||
}
|
||||
|
||||
public void setCell(Cell cell, Object value, CellStyle style) {
|
||||
this.setCell(cell, value, style, (String)null, (String)null, (String)null, (String)null);
|
||||
}
|
||||
|
||||
public void setFileSizeCell(int rowNo, int colNo, long value, CellStyle style) {
|
||||
String format;
|
||||
float size;
|
||||
if (value > 1099511627776L) {
|
||||
size = (float)value / 1.0995116E12F;
|
||||
format = "#,##0.00\" TB\"";
|
||||
} else if (value > 1073741824L) {
|
||||
size = (float)value / 1.0737418E9F;
|
||||
format = "#,##0.00\" GB\"";
|
||||
} else if (value > 1048576L) {
|
||||
size = (float)value / 1048576.0F;
|
||||
format = "#,##0.00\" MB\"";
|
||||
} else if (value > 1024L) {
|
||||
size = (float)value / 1024.0F;
|
||||
format = "#,##0.00\" KB\"";
|
||||
} else if (value > 0L) {
|
||||
size = (float)value;
|
||||
format = "0\" bytes\"";
|
||||
} else {
|
||||
size = 0.0F;
|
||||
format = "0";
|
||||
}
|
||||
|
||||
this.setCell(this.getCell(rowNo, colNo), size, style, format, (String)null, (String)null, (String)null);
|
||||
}
|
||||
|
||||
public void setCell(int rowIndex, int colIndex, Object value, CellStyle style, String format, String hAlignment, String vAlignment, String colorName) {
|
||||
this.setCell(this.getCell(rowIndex, colIndex), value, style, format, hAlignment, vAlignment, colorName);
|
||||
}
|
||||
|
||||
public void setCell(Cell cell, Object value, CellStyle style, String format, String hAlignment, String vAlignment, String colorName) {
|
||||
if (cell != null) {
|
||||
if (style == null) {
|
||||
style = cell.getCellStyle();
|
||||
}
|
||||
|
||||
if (style != null) {
|
||||
this.tempStyle.cloneStyleFrom(style);
|
||||
}
|
||||
|
||||
if (format == null) {
|
||||
if (value instanceof Number) {
|
||||
if (!(value instanceof Integer) && !(value instanceof Long)) {
|
||||
this.tempStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));
|
||||
} else {
|
||||
this.tempStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0"));
|
||||
}
|
||||
}
|
||||
} else if (!format.isEmpty()) {
|
||||
this.tempStyle.setDataFormat(this.getCustomDataFormat(format));
|
||||
}
|
||||
|
||||
if (!Strings.isNullOrEmpty(colorName)) {
|
||||
int fontIndex = style == null ? 0 : style.getFontIndex();
|
||||
this.workbook.getFontAt(fontIndex);
|
||||
this.tempStyle.setFont(this.getFont(style, colorName));
|
||||
}
|
||||
|
||||
if (!Strings.isNullOrEmpty(hAlignment)) {
|
||||
this.tempStyle.setAlignment(HorizontalAlignment.valueOf(hAlignment.toUpperCase()));
|
||||
}
|
||||
|
||||
if (!Strings.isNullOrEmpty(vAlignment)) {
|
||||
this.tempStyle.setVerticalAlignment(VerticalAlignment.valueOf(vAlignment.toUpperCase()));
|
||||
}
|
||||
|
||||
this.setCellStyle(cell, this.tempStyle);
|
||||
if (value == null) {
|
||||
this.removeCell(cell);
|
||||
} else if (value instanceof Character) {
|
||||
cell.setCellValue(Character.toString((Character)value));
|
||||
} else if (value instanceof String) {
|
||||
if (Strings.isNullOrEmpty((String)value)) {
|
||||
this.removeCell(cell);
|
||||
} else {
|
||||
cell.setCellValue((String)value);
|
||||
}
|
||||
} else if (value instanceof Number) {
|
||||
this.tempStyle.setAlignment(HorizontalAlignment.RIGHT);
|
||||
this.setCellStyle(cell, this.tempStyle);
|
||||
cell.setCellValue(((Number)value).doubleValue());
|
||||
} else if (value instanceof Date) {
|
||||
cell.setCellValue((Date)value);
|
||||
} else if (value instanceof Boolean) {
|
||||
cell.setCellValue((Boolean)value);
|
||||
} else if (value instanceof RichTextString) {
|
||||
cell.setCellValue((RichTextString)value);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void setCellStyle(Cell cell, CellStyle style) {
|
||||
String styleId = this.cellStyleId(style);
|
||||
if (this.styleMap.containsKey(styleId)) {
|
||||
style = (CellStyle)this.styleMap.get(styleId);
|
||||
} else {
|
||||
style = this.clone(style);
|
||||
this.styleMap.put(styleId, style);
|
||||
}
|
||||
|
||||
cell.setCellStyle(style);
|
||||
}
|
||||
|
||||
public void setSell(Cell cell, Date date, CellStyle style, String dateFormat) {
|
||||
style.setDataFormat(this.getCustomDataFormat(dateFormat));
|
||||
}
|
||||
|
||||
public XSSFFont getFont(CellStyle style) {
|
||||
return this.workbook.getFontAt(style.getFontIndex());
|
||||
}
|
||||
|
||||
public XSSFFont getFont(CellStyle style, String colorName) {
|
||||
XSSFFont cellFont = this.getFont(style);
|
||||
return Strings.isNullOrEmpty(colorName) ? cellFont : this.getFont(cellFont.getFontName(), cellFont.getFontHeightInPoints(), colorName, cellFont.getBold(), cellFont.getItalic(), cellFont.getUnderline(), cellFont.getStrikeout());
|
||||
}
|
||||
|
||||
public XSSFFont getFont(CellStyle style, String colorName, boolean bold, boolean italic, byte underline, boolean strike) {
|
||||
XSSFFont cellFont = this.getFont(style);
|
||||
return this.getFont(cellFont.getFontName(), cellFont.getFontHeightInPoints(), colorName, cellFont.getBold(), cellFont.getItalic(), cellFont.getUnderline(), cellFont.getStrikeout());
|
||||
}
|
||||
|
||||
public XSSFFont getFont(String fontName, short size, String colorName, boolean bold, boolean italic, byte underline, boolean strike) {
|
||||
String key = fontName + size + colorName + bold + italic + underline + strike;
|
||||
if (this.fontMap.containsKey(key)) {
|
||||
return (XSSFFont)this.fontMap.get(key);
|
||||
} else {
|
||||
XSSFFont font = this.workbook.createFont();
|
||||
font.setFontName(fontName);
|
||||
font.setFontHeightInPoints(size);
|
||||
font.setBold(bold);
|
||||
font.setUnderline(underline);
|
||||
font.setItalic(italic);
|
||||
font.setStrikeout(strike);
|
||||
font.setColor(this.toColor(colorName));
|
||||
this.fontMap.put(key, font);
|
||||
return font;
|
||||
}
|
||||
}
|
||||
|
||||
public void setFormula(Cell cell, String formular, String format, CellStyle style, String alignment) {
|
||||
style = this.clone(style);
|
||||
style.setDataFormat(HSSFDataFormat.getBuiltinFormat(format));
|
||||
if (!Strings.isNullOrEmpty(alignment)) {
|
||||
style.setAlignment(HorizontalAlignment.valueOf(alignment.toUpperCase()));
|
||||
}
|
||||
|
||||
this.setCellStyle(cell, style);
|
||||
cell.setCellFormula(formular);
|
||||
this.evalueateFormula(cell);
|
||||
}
|
||||
|
||||
private void evalueateFormula(Cell cell) {
|
||||
this.getCreationHelper().createFormulaEvaluator().evaluateFormulaCell(cell);
|
||||
}
|
||||
|
||||
public void setSumToCells(int writeRowNum, String[] colChars, int startNum, int endNum, CellStyle style, String alignment) {
|
||||
for(String colChar : colChars) {
|
||||
int colIndex = 0;
|
||||
int power = 0;
|
||||
|
||||
for(int i = colChar.length() - 1; i >= 0; --i) {
|
||||
Character ch = colChar.charAt(i);
|
||||
if (ch < 'A' || ch > 'Z') {
|
||||
return;
|
||||
}
|
||||
|
||||
colIndex = (int)((double)colIndex + (power == 0 ? (double)ch.compareTo('A') : (double)(ch.compareTo('A') + 1) * Math.pow((double)26.0F, (double)power)));
|
||||
++power;
|
||||
}
|
||||
|
||||
Cell cell = this.getCell(writeRowNum, colIndex);
|
||||
String strFormula = String.format("SUM(%s%d:%s%d)", colChar, startNum, colChar, endNum);
|
||||
this.setFormula(cell, strFormula, "#,##0", style, alignment);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void addImage(InputStream input, int x, int y, int width, int height) {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
|
||||
try {
|
||||
BufferedImage image = ImageIO.read(input);
|
||||
ImageIO.write(image, "png", bos);
|
||||
int imageId = this.workbook.addPicture(bos.toByteArray(), 6);
|
||||
bos.close();
|
||||
Drawing<?> drawing = this.activeSheet.createDrawingPatriarch();
|
||||
ClientAnchor anchor = new XSSFClientAnchor();
|
||||
if (x > 0) {
|
||||
anchor.setDx1(x);
|
||||
}
|
||||
|
||||
if (y > 0) {
|
||||
anchor.setDy1(y);
|
||||
}
|
||||
|
||||
Picture picture = drawing.createPicture(anchor, imageId);
|
||||
if (width > 0 && height > 0) {
|
||||
double xScale = (double)(width / image.getWidth());
|
||||
double yScale = (double)(height / image.getHeight());
|
||||
picture.resize(xScale, yScale);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void fill(int rowFrom, int rowTo, int colFrom, int colTo, Object value, CellStyle cellStyle) {
|
||||
for(int i = rowFrom; i <= rowTo; ++i) {
|
||||
for(int j = colFrom; j <= colTo; ++j) {
|
||||
this.setCell(i, j, value, cellStyle);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public int merge(int rowFrom, int rowTo, int colFrom, int colTo) {
|
||||
return this.merge(rowFrom, rowTo, colFrom, colTo, (CellStyle)null);
|
||||
}
|
||||
|
||||
public int merge(int rowFrom, int rowTo, int colFrom, int colTo, CellStyle cellStyle) {
|
||||
if (rowFrom == rowTo && colFrom == colTo) {
|
||||
return -1;
|
||||
} else {
|
||||
CellRangeAddress cellRangeAddress = new CellRangeAddress(rowFrom, rowTo, colFrom, colTo);
|
||||
int regionId = this.activeSheet.addMergedRegion(cellRangeAddress);
|
||||
if (cellStyle != null) {
|
||||
for(int row = rowFrom; row <= rowTo; ++row) {
|
||||
for(int col = colFrom; col <= colTo; ++col) {
|
||||
this.setCellStyle(this.getCell(row, col), cellStyle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return regionId;
|
||||
}
|
||||
}
|
||||
|
||||
public void removeMergedRegion(int index) {
|
||||
this.activeSheet.removeMergedRegion(index);
|
||||
}
|
||||
|
||||
public void removeCell(Cell cell) {
|
||||
cell.getRow().removeCell(cell);
|
||||
}
|
||||
|
||||
public void insertColumns(int colAfter, int colNumbers) {
|
||||
this.shiftColumns(colAfter, this.getLastColIndex(), colNumbers);
|
||||
}
|
||||
|
||||
public void removeColumns(int colFrom, int colTo) {
|
||||
int mergedRegionNum = this.activeSheet.getNumMergedRegions();
|
||||
if (mergedRegionNum > 0) {
|
||||
for(int i = 0; i < mergedRegionNum; ++i) {
|
||||
CellRangeAddress range = this.activeSheet.getMergedRegion(i);
|
||||
int colFirst = range.getFirstColumn();
|
||||
int colLast = range.getLastColumn();
|
||||
if (colFirst >= colFrom && colFirst <= colTo || colLast >= colFrom && colLast <= colTo) {
|
||||
this.removeMergedRegion(i--);
|
||||
--mergedRegionNum;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for(Row row : this.activeSheet) {
|
||||
for(int i = colFrom; i <= colTo; ++i) {
|
||||
Cell cell = row.getCell(i);
|
||||
if (cell != null) {
|
||||
row.removeCell(cell);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int lastColIndex = this.getLastColIndex();
|
||||
if (lastColIndex > colTo) {
|
||||
this.shiftColumns(colTo + 1, lastColIndex, colFrom - colTo - 1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void removeRow(int rowIndex) {
|
||||
this.activeSheet.removeRow(this.getRow(rowIndex));
|
||||
}
|
||||
|
||||
public int getLastColIndex(int rowNum) {
|
||||
return this.getRow(rowNum).getLastCellNum();
|
||||
}
|
||||
|
||||
public int getLastColIndex() {
|
||||
int colNum = 0;
|
||||
|
||||
for(int i = 0; i < this.activeSheet.getLastRowNum(); ++i) {
|
||||
Row row = this.activeSheet.getRow(i);
|
||||
if (row != null) {
|
||||
short rowColNum = row.getLastCellNum();
|
||||
if (rowColNum > colNum) {
|
||||
colNum = rowColNum;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return colNum - 1;
|
||||
}
|
||||
|
||||
public void shiftColumns(int colFrom, int colTo, int colNumbers) {
|
||||
if (colFrom <= colTo && colNumbers != 0) {
|
||||
int[] widths = new int[colTo - colFrom];
|
||||
|
||||
for(int i = 0; i < widths.length; ++i) {
|
||||
widths[i] = this.activeSheet.getColumnWidth(i + colFrom);
|
||||
}
|
||||
|
||||
this.activeSheet.shiftColumns(colFrom, colTo, colNumbers);
|
||||
|
||||
for(int i = 0; i < widths.length; ++i) {
|
||||
this.activeSheet.setColumnWidth(i + colFrom + colNumbers, widths[i]);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public void addConditionalPattern(int rowFrom, int rowTo, int colFrom, int colTo, String formula, String textColor, String backgroundColor) {
|
||||
SheetConditionalFormatting formatting = this.activeSheet.getSheetConditionalFormatting();
|
||||
ConditionalFormattingRule rule = formatting.createConditionalFormattingRule(formula);
|
||||
if (!Strings.isNullOrEmpty(textColor)) {
|
||||
FontFormatting font = rule.createFontFormatting();
|
||||
Color color = this.toColor(textColor);
|
||||
font.setFontColor(color);
|
||||
}
|
||||
|
||||
if (!Strings.isNullOrEmpty(backgroundColor)) {
|
||||
PatternFormatting fill = rule.createPatternFormatting();
|
||||
Color color = this.toColor(backgroundColor);
|
||||
fill.setFillBackgroundColor(color);
|
||||
fill.setFillPattern((short)1);
|
||||
}
|
||||
|
||||
CellRangeAddress[] ranges = new CellRangeAddress[]{new CellRangeAddress(rowFrom, rowTo, colFrom, colTo)};
|
||||
ConditionalFormattingRule[] rules = new ConditionalFormattingRule[]{rule};
|
||||
formatting.addConditionalFormatting(ranges, rules);
|
||||
}
|
||||
|
||||
public byte[] getBytes() {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
|
||||
try {
|
||||
this.workbook.write(bos);
|
||||
bos.flush();
|
||||
byte[] bytes = bos.toByteArray();
|
||||
bos.close();
|
||||
return bytes;
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public void setAutoFilter(int row) {
|
||||
CellRangeAddress cellRange = new CellRangeAddress(row, row, 0, this.getLastColIndex());
|
||||
this.activeSheet.setAutoFilter(cellRange);
|
||||
}
|
||||
|
||||
public void write(OutputStream output) {
|
||||
try {
|
||||
this.workbook.write(output);
|
||||
output.flush();
|
||||
output.close();
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public Cell getCell(String cellId) {
|
||||
if (Strings.isNullOrEmpty(cellId)) {
|
||||
return null;
|
||||
} else {
|
||||
Pattern pattern = Pattern.compile("(?<=[\\w&&\\D])(?=\\d)");
|
||||
String[] tokens = pattern.split(cellId);
|
||||
if (tokens.length != 0 && tokens.length <= 2) {
|
||||
int rowNum = Integer.parseInt(tokens[1]);
|
||||
int colNum = 0;
|
||||
String colId = tokens[0].toLowerCase();
|
||||
|
||||
for(int i = 0; i < colId.length(); ++i) {
|
||||
colNum = colNum * 26 + colId.charAt(i) - 97 + 1;
|
||||
}
|
||||
|
||||
Cell var10000;
|
||||
if (rowNum >= 0 && colNum >= 0) {
|
||||
--rowNum;
|
||||
--colNum;
|
||||
var10000 = this.getCell(rowNum, colNum);
|
||||
} else {
|
||||
var10000 = null;
|
||||
}
|
||||
|
||||
return var10000;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String cellStyleId(CellStyle style) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(style.getHidden());
|
||||
sb.append(style.getLocked());
|
||||
sb.append(style.getFontIndex());
|
||||
sb.append(style.getAlignment());
|
||||
sb.append(style.getVerticalAlignment());
|
||||
sb.append(style.getWrapText());
|
||||
sb.append(style.getQuotePrefixed());
|
||||
sb.append(style.getShrinkToFit());
|
||||
sb.append(style.getDataFormat());
|
||||
sb.append(style.getDataFormatString());
|
||||
sb.append(style.getIndention());
|
||||
sb.append(style.getRotation());
|
||||
sb.append(style.getBorderBottom());
|
||||
sb.append(style.getBorderLeft());
|
||||
sb.append(style.getBorderRight());
|
||||
sb.append(style.getBorderTop());
|
||||
sb.append(style.getBottomBorderColor());
|
||||
sb.append(style.getLeftBorderColor());
|
||||
sb.append(style.getRightBorderColor());
|
||||
sb.append(style.getTopBorderColor());
|
||||
sb.append(style.getFillBackgroundColor());
|
||||
sb.append(style.getFillBackgroundColorColor());
|
||||
sb.append(style.getFillForegroundColor());
|
||||
sb.append(style.getFillForegroundColorColor());
|
||||
sb.append(style.getFillPattern());
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private XSSFColor toColor(String colorName) {
|
||||
byte[] bytes;
|
||||
if (colorName.startsWith("#")) {
|
||||
colorName = colorName.substring(1);
|
||||
bytes = Hex.decode(colorName);
|
||||
} else {
|
||||
HSSFColor.HSSFColorPredefined color = HSSFColorPredefined.valueOf(colorName.toUpperCase());
|
||||
short[] rgb = color.getTriplet();
|
||||
bytes = new byte[]{(byte)rgb[0], (byte)rgb[1], (byte)rgb[2]};
|
||||
}
|
||||
|
||||
return new XSSFColor(bytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.mitac.cell.doc;
|
||||
|
||||
import com.lowagie.text.DocumentException;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.MalformedURLException;
|
||||
import org.xhtmlrenderer.pdf.ITextRenderer;
|
||||
|
||||
public class HtmlToPdf {
|
||||
public static void toPdf(String sourceUrl, String outputFilePath) {
|
||||
try {
|
||||
toPdf(sourceUrl, (OutputStream)(new FileOutputStream(outputFilePath)));
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void toPdf(String sourceUrl, OutputStream output) {
|
||||
try {
|
||||
ITextRenderer renderer = new ITextRenderer();
|
||||
renderer.setDocument(sourceUrl);
|
||||
renderer.layout();
|
||||
renderer.createPDF(output);
|
||||
output.close();
|
||||
} catch (FileNotFoundException e2) {
|
||||
e2.printStackTrace();
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (DocumentException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.mitac.cell.doc;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.jsoup.nodes.Element;
|
||||
import org.jsoup.select.Elements;
|
||||
|
||||
public class McHtmlDoc {
|
||||
public static final String SCHEME_HTTP = "http";
|
||||
public static final String SCHEME_HTTPS = "https";
|
||||
public static final String TAG_DIV = "div";
|
||||
public static final String TAG_META = "meta";
|
||||
public static final String TAG_H1 = "h1";
|
||||
public static final String TAG_SPAN = "span";
|
||||
public static final String TAG_IMG = "img";
|
||||
public static final String TAG_A = "a";
|
||||
public static final String ATTR_CLASS = "class";
|
||||
public static final String ATTR_HREF = "href";
|
||||
public static final String ATTR_TITLE = "title";
|
||||
public static final String ATTR_NAME = "name";
|
||||
public static final String ATTR_SRC = "src";
|
||||
public static final String ATTR_ITEMPROP = "itemprop";
|
||||
public static final String ATTR_ALT = "alt";
|
||||
public static final String ATTR_IMAGE = "image";
|
||||
public static final String ATTR_CONTENT = "content";
|
||||
public static final String ATTR_DESCRIPTION = "image";
|
||||
protected Document document;
|
||||
|
||||
public McHtmlDoc(String url) {
|
||||
if (!Strings.isNullOrEmpty(url)) {
|
||||
this.document = McHtmlUtils.loadHtml(url);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public boolean exists() {
|
||||
return this.document != null;
|
||||
}
|
||||
|
||||
public Document getDocument() {
|
||||
return this.document;
|
||||
}
|
||||
|
||||
public String html() {
|
||||
return this.document.html();
|
||||
}
|
||||
|
||||
public String getDivText(String findAttrName, String findAttrValue) {
|
||||
return this.getText("div", findAttrName, findAttrValue);
|
||||
}
|
||||
|
||||
public String getText(String tag, String findAttrName, String findAttrValue) {
|
||||
return this.getElements(tag, findAttrName, findAttrValue).text();
|
||||
}
|
||||
|
||||
public String getAttr(String tag, String findAttrName, String findAttrValue, String attr) {
|
||||
return this.getElements(tag, findAttrName, findAttrValue).attr(attr);
|
||||
}
|
||||
|
||||
public Elements getElements(String tag, String findAttrName, String findAttrValue) {
|
||||
return this.document.select(this.selectEquals(tag, findAttrName, findAttrValue));
|
||||
}
|
||||
|
||||
public String getText(Element element, String tag, String findAttrName, String findAttrValue) {
|
||||
return element.select(this.selectEquals(tag, findAttrName, findAttrValue)).text();
|
||||
}
|
||||
|
||||
public String getAttr(Element element, String tag, String findAttrName, String findAttrValue, String attr) {
|
||||
return element.select(this.selectEquals(tag, findAttrName, findAttrValue)).attr(attr);
|
||||
}
|
||||
|
||||
public String selectEquals(String tag, String findAttrName, String findAttrValue) {
|
||||
return String.format("%s[%s=%s]", tag, findAttrName, findAttrValue);
|
||||
}
|
||||
|
||||
public String selectContains(String tag, String findAttrName, String findAttrValue) {
|
||||
return String.format("%s[%s*=%s]", tag, findAttrName, findAttrValue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.mitac.cell.doc;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.jsoup.parser.Parser;
|
||||
|
||||
public class McHtmlUtils {
|
||||
public static Document loadHtml(String urlRef) {
|
||||
return load(urlRef, Parser.htmlParser());
|
||||
}
|
||||
|
||||
public static Document load(String urlRef, Parser parser) {
|
||||
try {
|
||||
return Jsoup.connect(urlRef).parser(parser).maxBodySize(0).get();
|
||||
} catch (MalformedURLException var3) {
|
||||
} catch (IOException var4) {
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Document load(URL url, Parser parser) {
|
||||
try {
|
||||
if (url == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
|
||||
conn.setConnectTimeout(10000);
|
||||
conn.setReadTimeout(5000);
|
||||
conn.setInstanceFollowRedirects(true);
|
||||
conn.connect();
|
||||
InputStream input = conn.getInputStream();
|
||||
Document doc = Jsoup.parse(input, "UTF-8", "", parser);
|
||||
input.close();
|
||||
conn.disconnect();
|
||||
return doc;
|
||||
} catch (MalformedURLException var5) {
|
||||
} catch (IOException var6) {
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package com.mitac.cell.doc;
|
||||
|
||||
import com.mitac.cell.internet.http.McHttpClient;
|
||||
import com.mitac.cell.utils.McStringUtils;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
|
||||
import org.apache.poi.openxml4j.opc.OPCPackage;
|
||||
import org.apache.poi.xwpf.usermodel.IBodyElement;
|
||||
import org.apache.poi.xwpf.usermodel.PositionInParagraph;
|
||||
import org.apache.poi.xwpf.usermodel.TextSegment;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFRun;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTable;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
|
||||
|
||||
public class WordTemplate {
|
||||
private XWPFDocument document;
|
||||
private Map model;
|
||||
|
||||
public WordTemplate(String filePath) {
|
||||
this.open(filePath);
|
||||
}
|
||||
|
||||
public void open(String filePath) {
|
||||
this.open(new File(filePath));
|
||||
}
|
||||
|
||||
public void open(File file) {
|
||||
try {
|
||||
if (file.exists()) {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
OPCPackage pkg = OPCPackage.open(file);
|
||||
pkg.save(bos);
|
||||
pkg.close();
|
||||
this.open((InputStream)(new ByteArrayInputStream(bos.toByteArray())));
|
||||
}
|
||||
} catch (InvalidFormatException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void open(InputStream is) {
|
||||
try {
|
||||
if (is != null) {
|
||||
this.document = new XWPFDocument(OPCPackage.open(is));
|
||||
}
|
||||
} catch (InvalidFormatException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void close() {
|
||||
try {
|
||||
if (this.document != null) {
|
||||
this.document.close();
|
||||
}
|
||||
} catch (IOException var2) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public Map getModel() {
|
||||
if (this.model == null) {
|
||||
this.model = new HashMap();
|
||||
}
|
||||
|
||||
return this.model;
|
||||
}
|
||||
|
||||
public void setModel(Map model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public void setModel(String key, Object value) {
|
||||
this.getModel().put(key, value);
|
||||
}
|
||||
|
||||
public void patch() {
|
||||
for(IBodyElement bodyElement : this.document.getBodyElements()) {
|
||||
switch (bodyElement.getElementType()) {
|
||||
case PARAGRAPH:
|
||||
this.patch((XWPFParagraph)bodyElement);
|
||||
break;
|
||||
case TABLE:
|
||||
this.patch((XWPFTable)bodyElement);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void write(String filePath) {
|
||||
this.write(new File(filePath));
|
||||
}
|
||||
|
||||
public void write(File file) {
|
||||
try {
|
||||
this.write((OutputStream)(new FileOutputStream(file)));
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void write(OutputStream os) {
|
||||
try {
|
||||
if (os != null) {
|
||||
this.patch();
|
||||
this.document.write(os);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void write(HttpServletResponse response, String fileName) {
|
||||
if (!McStringUtils.isNullOrEmpty(fileName)) {
|
||||
try {
|
||||
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
|
||||
response.setHeader("Content-Disposition", McHttpClient.toContentDisposition(fileName));
|
||||
this.write((OutputStream)response.getOutputStream());
|
||||
response.flushBuffer();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void patch(XWPFParagraph paragraph) {
|
||||
TextSegment segmentStart = paragraph.searchText("{{", new PositionInParagraph());
|
||||
if (segmentStart != null) {
|
||||
XWPFRun run = (XWPFRun)paragraph.getRuns().get(segmentStart.getBeginRun());
|
||||
TextSegment segmentEnd = paragraph.searchText("}}", new PositionInParagraph());
|
||||
if (segmentEnd != null) {
|
||||
TextSegment tempEnd = null;
|
||||
|
||||
do {
|
||||
tempEnd = paragraph.searchText("}}", segmentEnd.getEndPos());
|
||||
if (tempEnd != null) {
|
||||
segmentEnd = tempEnd;
|
||||
}
|
||||
} while(tempEnd != null);
|
||||
|
||||
StringBuilder sb = new StringBuilder(run.getText(0));
|
||||
int startIndex = segmentStart.getBeginRun() + 1;
|
||||
int endIndex = segmentEnd.getEndRun() + 1;
|
||||
int count = endIndex - startIndex;
|
||||
|
||||
for(int i = startIndex; i < startIndex + count; ++i) {
|
||||
sb.append(paragraph.getRuns().get(startIndex));
|
||||
paragraph.removeRun(startIndex);
|
||||
}
|
||||
|
||||
run.setText(this.parseText(sb.toString()), 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void patch(XWPFTable table) {
|
||||
for(XWPFTableRow row : table.getRows()) {
|
||||
for(XWPFTableCell cell : row.getTableCells()) {
|
||||
for(XWPFParagraph p : cell.getParagraphs()) {
|
||||
this.patch(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public String parseText(String source) {
|
||||
Pattern pattern = Pattern.compile("\\{\\{(.*?)\\}\\}");
|
||||
Matcher matcher = pattern.matcher(source);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
int startIndex;
|
||||
for(startIndex = 0; matcher.find(); startIndex = matcher.end()) {
|
||||
sb.append(source.substring(startIndex, matcher.start()));
|
||||
String group = matcher.group(1);
|
||||
int index = group.indexOf(124);
|
||||
String key = index < 0 ? group : group.substring(0, index);
|
||||
String format = index < 0 ? null : group.substring(index + 1);
|
||||
Object value = this.model.get(key);
|
||||
if (value != null) {
|
||||
if (format == null) {
|
||||
sb.append(value);
|
||||
} else if (value instanceof Date) {
|
||||
SimpleDateFormat formatter = new SimpleDateFormat(format);
|
||||
sb.append(formatter.format(value));
|
||||
} else {
|
||||
sb.append(String.format(format, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (startIndex < source.length()) {
|
||||
sb.append(source.substring(startIndex));
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.mitac.cell.gson.typeAdapter;
|
||||
|
||||
import com.google.gson.JsonDeserializationContext;
|
||||
import com.google.gson.JsonDeserializer;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.google.gson.JsonSerializationContext;
|
||||
import com.google.gson.JsonSerializer;
|
||||
import java.lang.reflect.Type;
|
||||
import javax.crypto.Cipher;
|
||||
|
||||
public class CipherTypeAdapter implements JsonSerializer, JsonDeserializer {
|
||||
public Cipher deserialize(JsonElement json, Type typeOfTarget, JsonDeserializationContext context) throws JsonParseException {
|
||||
return null;
|
||||
}
|
||||
|
||||
public JsonElement serialize(Cipher src, Type typeOfSrc, JsonSerializationContext context) {
|
||||
return new JsonPrimitive(src.getAlgorithm());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.mitac.cell.gson.typeAdapter;
|
||||
|
||||
import com.google.gson.JsonDeserializationContext;
|
||||
import com.google.gson.JsonDeserializer;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.google.gson.JsonSerializationContext;
|
||||
import com.google.gson.JsonSerializer;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class CompatibleTimeZoneTypeAdapter implements JsonSerializer, JsonDeserializer {
|
||||
public TimeZone deserialize(JsonElement json, Type typeOfTarget, JsonDeserializationContext context) throws JsonParseException {
|
||||
String timeZone = json.getAsString();
|
||||
return TimeZone.getTimeZone(timeZone);
|
||||
}
|
||||
|
||||
public JsonElement serialize(TimeZone timeZone, Type typeOfSrc, JsonSerializationContext context) {
|
||||
return new JsonPrimitive(timeZone.getID());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.mitac.cell.internet.app;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.mitac.cell.doc.McHtmlDoc;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.jsoup.select.Elements;
|
||||
|
||||
public class McPlayMarket {
|
||||
public static final String BASE_URL = "https://play.google.com";
|
||||
private static final String URL_PLAY_STORE = "https://play.google.com/store";
|
||||
private static final String URL_APP_URL = "https://play.google.com/store/apps/details?id=%s&hl=%s";
|
||||
private static final String URL_APP_SEARCH = "https://play.google.com/store/search?q=%s&hl=%s&c=apps";
|
||||
private static final String LOCALE_DEFAULT = "en-GB";
|
||||
|
||||
public static PlayApp getApkInfo(String packageName) {
|
||||
return getApkInfo(packageName, "en-GB");
|
||||
}
|
||||
|
||||
public static PlayApp getApkInfo(String packageName, String locale) {
|
||||
if (Strings.isNullOrEmpty(packageName)) {
|
||||
return null;
|
||||
} else {
|
||||
McHtmlDoc doc = new McHtmlDoc(String.format("https://play.google.com/store/apps/details?id=%s&hl=%s", packageName, locale));
|
||||
if (!doc.exists()) {
|
||||
return null;
|
||||
} else {
|
||||
PlayApp app = new PlayApp();
|
||||
app.setAppId(packageName);
|
||||
String title = doc.getText("h1", "itemprop", "name");
|
||||
app.setTitle(title);
|
||||
String developer = doc.getText("div", "class", "Vbfug auoIOc");
|
||||
app.setDeveloper(developer);
|
||||
String iconSrc = doc.getAttr("img", "itemprop", "image", "src");
|
||||
app.setIcon(iconSrc);
|
||||
String summary = doc.getAttr("meta", "itemprop", "image", "content");
|
||||
app.setSummary(summary);
|
||||
String score = doc.getText("div", "itemprop", "starRating");
|
||||
app.setScore(score);
|
||||
return app;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static List search(String keyword) {
|
||||
return search(keyword, "en-GB");
|
||||
}
|
||||
|
||||
public static List search(String keyword, String locale) {
|
||||
if (Strings.isNullOrEmpty(keyword)) {
|
||||
return null;
|
||||
} else {
|
||||
McHtmlDoc doc = new McHtmlDoc(String.format("https://play.google.com/store/search?q=%s&hl=%s&c=apps", keyword, locale));
|
||||
if (!doc.exists()) {
|
||||
return null;
|
||||
} else {
|
||||
List<PlayApp> apps = new ArrayList();
|
||||
Elements elements = doc.getElements("div", "class", "VfPpkd-aGsRMb");
|
||||
if (elements != null && !elements.isEmpty()) {
|
||||
elements.forEach((element) -> {
|
||||
String packageSrc = doc.getAttr(element, "a", "class", "Si6A0c Gy4nib", "href");
|
||||
PlayApp app = new PlayApp();
|
||||
app.setAppId(packageSrc);
|
||||
String iconSrc = doc.getAttr(element, "img", "alt", "Thumbnail image", "src");
|
||||
app.setIcon(iconSrc);
|
||||
String title = doc.getText(element, "span", "class", "DdYX5");
|
||||
app.setTitle(title);
|
||||
String developer = doc.getText(element, "span", "class", "wMUdtb");
|
||||
app.setDeveloper(developer);
|
||||
String score = doc.getText(element, "span", "class", "w2kbF");
|
||||
app.setScore(score);
|
||||
apps.add(app);
|
||||
});
|
||||
}
|
||||
|
||||
return apps;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.mitac.cell.internet.app;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
|
||||
public class PlayApp {
|
||||
private String appId;
|
||||
private String title;
|
||||
private String summary;
|
||||
private String developer;
|
||||
private String icon;
|
||||
private Float score;
|
||||
|
||||
public String getAppId() {
|
||||
return this.appId;
|
||||
}
|
||||
|
||||
public void setAppId(String appId) {
|
||||
int idIndex = appId.indexOf("id=");
|
||||
this.appId = idIndex >= 0 ? appId.substring(idIndex + 3) : appId;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return this.title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getSummary() {
|
||||
return this.summary;
|
||||
}
|
||||
|
||||
public void setSummary(String summary) {
|
||||
this.summary = summary;
|
||||
}
|
||||
|
||||
public String getDeveloper() {
|
||||
return this.developer;
|
||||
}
|
||||
|
||||
public void setDeveloper(String developer) {
|
||||
this.developer = developer;
|
||||
}
|
||||
|
||||
public String getIcon() {
|
||||
return this.icon;
|
||||
}
|
||||
|
||||
public void setIcon(String icon) {
|
||||
int indexSlash = icon.lastIndexOf("/");
|
||||
int endsIndex = icon.lastIndexOf("=");
|
||||
this.icon = indexSlash >= 0 ? icon.substring(indexSlash + 1, endsIndex > 0 ? endsIndex : icon.length()) : icon;
|
||||
}
|
||||
|
||||
public Float getScore() {
|
||||
return this.score;
|
||||
}
|
||||
|
||||
public void setScore(String score) {
|
||||
try {
|
||||
if (!Strings.isNullOrEmpty(score)) {
|
||||
this.setScore(Float.parseFloat(score));
|
||||
}
|
||||
} catch (Exception var3) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void setScore(Float score) {
|
||||
this.score = score;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.mitac.cell.internet.html;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import org.thymeleaf.TemplateEngine;
|
||||
import org.thymeleaf.context.Context;
|
||||
import org.thymeleaf.templatemode.TemplateMode;
|
||||
import org.thymeleaf.templateresolver.StringTemplateResolver;
|
||||
|
||||
public class McHtmlTemplateEngine extends TemplateEngine {
|
||||
private final Context context;
|
||||
private StringTemplateResolver templateResolver;
|
||||
|
||||
public McHtmlTemplateEngine() {
|
||||
this.context = new Context();
|
||||
this.init();
|
||||
}
|
||||
|
||||
public McHtmlTemplateEngine(String templateMode, Locale locale) {
|
||||
this();
|
||||
this.setLocale(locale);
|
||||
this.setTemplateMode(templateMode);
|
||||
}
|
||||
|
||||
public void setLocale(Locale locale) {
|
||||
this.context.setLocale(locale);
|
||||
}
|
||||
|
||||
public void setVariable(String name, Object value) {
|
||||
this.context.setVariable(name, value);
|
||||
}
|
||||
|
||||
public void setVariables(Map attrs) {
|
||||
this.context.setVariables(attrs);
|
||||
}
|
||||
|
||||
public void setTemplateMode(String templateMode) {
|
||||
this.templateResolver.setTemplateMode(templateMode);
|
||||
}
|
||||
|
||||
public String process(String htmlContent) {
|
||||
String template = null;
|
||||
this.process(htmlContent, this.context);
|
||||
return template;
|
||||
}
|
||||
|
||||
private void init() {
|
||||
this.templateResolver = new StringTemplateResolver();
|
||||
this.templateResolver.setTemplateMode(TemplateMode.HTML);
|
||||
this.setTemplateResolver(this.templateResolver);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package com.mitac.cell.internet.http;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.common.net.UrlEscapers;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.apache.tika.mime.MimeType;
|
||||
import org.apache.tika.mime.MimeTypes;
|
||||
import org.springframework.http.ContentDisposition;
|
||||
|
||||
public class McHttpClient {
|
||||
public static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition";
|
||||
public static final String HEADER_CONTENT_TYPE = "Content-Type";
|
||||
public static final String HEADER_USER_AGENT = "User-Agent";
|
||||
public static final String HEADER_ENCRPYT_STRING = "encryptString";
|
||||
public static final String CONTENT_TYPE_HTML = "text/html; utf-8";
|
||||
public static final String CONTENT_TYPE_OCTET_STREAM = "application/octet-stream";
|
||||
|
||||
public static HttpURLConnection open(String link) {
|
||||
try {
|
||||
return Strings.isNullOrEmpty(link) ? null : open(new URL(link));
|
||||
} catch (Exception var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static HttpURLConnection open(URL url) {
|
||||
try {
|
||||
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
|
||||
conn.setConnectTimeout(60000);
|
||||
conn.setReadTimeout(180000);
|
||||
conn.setRequestProperty("User-Agent", "MiDM Host");
|
||||
conn.setInstanceFollowRedirects(true);
|
||||
HttpURLConnection.setFollowRedirects(true);
|
||||
conn.connect();
|
||||
if (isRedirected(conn)) {
|
||||
conn = getRedirectedConnection(conn);
|
||||
}
|
||||
|
||||
return conn;
|
||||
} catch (IOException var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isRedirected(HttpURLConnection conn) {
|
||||
if (conn == null) {
|
||||
return false;
|
||||
} else {
|
||||
try {
|
||||
int status = conn.getResponseCode();
|
||||
return status != 200 && (status == 302 || status == 301 || status == 303);
|
||||
} catch (IOException var2) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static HttpURLConnection getRedirectedConnection(HttpURLConnection conn) {
|
||||
String newUrl = conn.getHeaderField("Location");
|
||||
|
||||
try {
|
||||
return (HttpURLConnection)(new URL(newUrl)).openConnection();
|
||||
} catch (Exception var3) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static InputStream getInputStream(String urlRef) {
|
||||
try {
|
||||
return getInputStream(new URL(urlRef));
|
||||
} catch (MalformedURLException var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static InputStream getInputStream(URL url) {
|
||||
try {
|
||||
URLConnection connection = url.openConnection();
|
||||
return connection.getInputStream();
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String getFileName(HttpURLConnection conn) {
|
||||
if (conn != null) {
|
||||
String fileName = null;
|
||||
String contentDisposition = conn.getHeaderField("Content-Disposition");
|
||||
if (!Strings.isNullOrEmpty(contentDisposition)) {
|
||||
fileName = getFileNameFromContentDisposition(contentDisposition);
|
||||
}
|
||||
|
||||
if (Strings.isNullOrEmpty(fileName)) {
|
||||
String ext = null;
|
||||
|
||||
try {
|
||||
String contentType = conn.getContentType();
|
||||
if (!Strings.isNullOrEmpty(contentType)) {
|
||||
MimeType type = MimeTypes.getDefaultMimeTypes().getRegisteredMimeType(contentType);
|
||||
if (type != null) {
|
||||
ext = type.getExtension();
|
||||
}
|
||||
}
|
||||
|
||||
String path = conn.getURL().getPath();
|
||||
path = URLDecoder.decode(path, StandardCharsets.UTF_8.name());
|
||||
if (!Strings.isNullOrEmpty(ext) && path.contains(ext)) {
|
||||
path = path.substring(0, path.indexOf(ext));
|
||||
}
|
||||
|
||||
fileName = FilenameUtils.getName(path);
|
||||
} catch (Exception var6) {
|
||||
fileName = "";
|
||||
}
|
||||
|
||||
if (!fileName.contains(".")) {
|
||||
fileName = fileName + ext;
|
||||
}
|
||||
|
||||
if (!Strings.isNullOrEmpty(fileName)) {
|
||||
return fileName;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return UUID.randomUUID().toString();
|
||||
}
|
||||
|
||||
public static String getFileNameFromContentDisposition(String headerString) {
|
||||
return ContentDisposition.parse(headerString).getFilename();
|
||||
}
|
||||
|
||||
public static String toContentDisposition(String fileName) {
|
||||
return String.format("attachment; filename=\"%s\"", UrlEscapers.urlFragmentEscaper().escape(fileName));
|
||||
}
|
||||
|
||||
public static Cookie findCookie(HttpServletRequest request, String name) {
|
||||
Cookie foundCookie = null;
|
||||
|
||||
for(Cookie cookie : request.getCookies()) {
|
||||
if (name.equals(cookie.getName())) {
|
||||
foundCookie = cookie;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return foundCookie;
|
||||
}
|
||||
|
||||
public static String getCookieValue(String cookie, String key) {
|
||||
Pattern PATTERN_JSESSIONID = Pattern.compile(String.format("\\b%s=([^;]+)", key));
|
||||
Matcher m = PATTERN_JSESSIONID.matcher(cookie);
|
||||
return m.find() ? m.group(1) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.mitac.cell.internet.http;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.common.base.Strings;
|
||||
import com.mitac.cell.utils.McStringUtils;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
public class McRequest {
|
||||
public static String getBaseUrl(HttpServletRequest request) {
|
||||
return getBaseUrl(request, (String)null);
|
||||
}
|
||||
|
||||
public static String getBaseUrl(HttpServletRequest request, String path) {
|
||||
try {
|
||||
URL url = new URL(request.getRequestURL().toString());
|
||||
String host = url.getHost();
|
||||
String scheme = url.getProtocol();
|
||||
int port = url.getPort();
|
||||
String userInfo = url.getUserInfo();
|
||||
String contextPath = request.getContextPath();
|
||||
if (!Strings.isNullOrEmpty(path)) {
|
||||
path = McStringUtils.trim(path.trim(), '/');
|
||||
}
|
||||
|
||||
if (Strings.isNullOrEmpty(path)) {
|
||||
path = contextPath;
|
||||
} else {
|
||||
path = Joiner.on('/').join(contextPath, path, new Object[0]).toString();
|
||||
}
|
||||
|
||||
URI uri = new URI(scheme, userInfo, host, port, path, (String)null, (String)null);
|
||||
return uri.toString();
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
} catch (URISyntaxException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.mitac.cell.internet.http;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.InputStreamResource;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
public class McResponse {
|
||||
public static ResponseEntity getServletResource(HttpServletRequest request, MediaType mediaType, String resourcePath) {
|
||||
ClassPathResource resource = new ClassPathResource(resourcePath);
|
||||
|
||||
try {
|
||||
InputStream is = resource.getInputStream();
|
||||
return getResponseFromStream(request, mediaType, resource.getFilename(), is);
|
||||
} catch (IOException var5) {
|
||||
return new ResponseEntity(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
public static ResponseEntity getFile(HttpServletRequest request, MediaType mediaType, String path) {
|
||||
try {
|
||||
File file = new File(path);
|
||||
return file.exists() && file.isFile() ? getResponseFromStream(request, mediaType, file.getName(), new FileInputStream(file)) : new ResponseEntity(HttpStatus.NO_CONTENT);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return new ResponseEntity(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
public static ResponseEntity getResponseFromStream(HttpServletRequest request, MediaType mediaType, String fileName, InputStream is) {
|
||||
try {
|
||||
ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
|
||||
builder.contentLength((long)is.available());
|
||||
builder.contentType(mediaType);
|
||||
builder.header("Content-Disposition", new String[]{McHttpClient.toContentDisposition(fileName)});
|
||||
return builder.body(new InputStreamResource(is));
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return new ResponseEntity(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
public static void sendError(HttpServletResponse response, int statusCode, String message) {
|
||||
try {
|
||||
response.sendError(statusCode, message);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void setCookie(HttpServletResponse response, String name, String value) {
|
||||
setCookie(response, "/", name, value);
|
||||
}
|
||||
|
||||
public static void setCookie(HttpServletResponse response, String path, String name, String value) {
|
||||
Cookie cookie = new Cookie(name, Strings.isNullOrEmpty(value) ? null : value);
|
||||
cookie.setPath(path);
|
||||
if (Strings.isNullOrEmpty(value)) {
|
||||
cookie.setMaxAge(0);
|
||||
}
|
||||
|
||||
response.addCookie(cookie);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.mitac.cell.internet.http;
|
||||
|
||||
import java.io.InputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import org.springframework.core.io.InputStreamResource;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
public class McResponseEntity {
|
||||
public static ResponseEntity get(HttpServletRequest request, MediaType mediaType, byte[] bytes) {
|
||||
ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
|
||||
builder.contentLength((long)bytes.length);
|
||||
builder.contentType(mediaType);
|
||||
return builder.body(bytes);
|
||||
}
|
||||
|
||||
public static ResponseEntity get(MediaType mediaType, InputStream is, int contentLength) {
|
||||
ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
|
||||
builder.contentLength((long)contentLength);
|
||||
builder.contentType(mediaType);
|
||||
return builder.body(new InputStreamResource(is));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.mitac.cell.internet.http;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import org.yaml.snakeyaml.LoaderOptions;
|
||||
import ua_parser.Client;
|
||||
import ua_parser.Device;
|
||||
import ua_parser.OS;
|
||||
import ua_parser.Parser;
|
||||
|
||||
public class UserAgent {
|
||||
private static final Set browsers = (Set)Arrays.stream(new String[]{"chrome", "firefox", "edge", "safari", "vivaldi", "opera"}).collect(Collectors.toSet());
|
||||
private static final Parser uaParser = new Parser(new LoaderOptions());
|
||||
private Client client;
|
||||
|
||||
public UserAgent(String source) {
|
||||
if (source.startsWith("MiDM")) {
|
||||
OS os = uaParser.parseOS(source);
|
||||
Device device = uaParser.parseDevice(source);
|
||||
String[] clientVersion = source.substring(source.lastIndexOf("/") + 1).split("\\.");
|
||||
this.client = new Client(new ua_parser.UserAgent("MiDM", clientVersion[0], clientVersion[1], clientVersion[2]), os, device);
|
||||
} else {
|
||||
this.client = uaParser.parse(source);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public OS os() {
|
||||
return this.client.os;
|
||||
}
|
||||
|
||||
public String osFamily() {
|
||||
return this.os().family;
|
||||
}
|
||||
|
||||
public Device device() {
|
||||
return this.client.device;
|
||||
}
|
||||
|
||||
public String deviceFamily() {
|
||||
return this.device().family;
|
||||
}
|
||||
|
||||
public Client client() {
|
||||
return this.client;
|
||||
}
|
||||
|
||||
public ua_parser.UserAgent agent() {
|
||||
return this.client.userAgent;
|
||||
}
|
||||
|
||||
public String agentFamily() {
|
||||
return this.agent().family;
|
||||
}
|
||||
|
||||
public boolean isBrowser() {
|
||||
return this.agentFamily() != null && browsers.contains(this.agent().family.toLowerCase());
|
||||
}
|
||||
|
||||
public boolean isDevice() {
|
||||
return this.agentFamily() != null && this.agent().family.equals("okhttp") || this.agent().family.equals("MiDM");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
package com.mitac.cell.internet.mail;
|
||||
|
||||
import com.mitac.cell.io.McFile;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import javax.mail.Address;
|
||||
import javax.mail.MessagingException;
|
||||
import javax.mail.Message.RecipientType;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.InputStreamResource;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
|
||||
public class McMailSender {
|
||||
private MimeMessageHelper mailMessage;
|
||||
private JavaMailSenderImpl mailSender;
|
||||
|
||||
public McMailSender(JavaMailSenderImpl mailSender, String senderEmail, String senderName) {
|
||||
this.mailSender = mailSender;
|
||||
|
||||
try {
|
||||
this.mailMessage = new MimeMessageHelper(mailSender.createMimeMessage(), true, "UTF-8");
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
this.setSender(senderEmail, senderName);
|
||||
}
|
||||
|
||||
public boolean setSender(String email) {
|
||||
return this.setSender(email, (String)null);
|
||||
}
|
||||
|
||||
public boolean setSender(String email, String name) {
|
||||
try {
|
||||
this.mailMessage.setFrom(email, name);
|
||||
return true;
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean addTo(String email) {
|
||||
return this.addTo(email, (String)null);
|
||||
}
|
||||
|
||||
public boolean addTo(String email, String name) {
|
||||
try {
|
||||
this.mailMessage.addTo(email, name);
|
||||
return true;
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean addTo(InternetAddress address) {
|
||||
try {
|
||||
if (address != null) {
|
||||
this.mailMessage.addTo(address);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean addTo(Collection addresses) {
|
||||
if (addresses != null && !addresses.isEmpty()) {
|
||||
addresses.forEach((address) -> this.addTo(address));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean setTo(Collection addresses) {
|
||||
if (addresses != null && !addresses.isEmpty()) {
|
||||
try {
|
||||
this.mailMessage.setTo((InternetAddress[])addresses.toArray(new InternetAddress[addresses.size()]));
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean addCc(String email) {
|
||||
return this.addCc(email, (String)null);
|
||||
}
|
||||
|
||||
public boolean addCc(String email, String name) {
|
||||
try {
|
||||
this.mailMessage.addCc(email, name);
|
||||
return true;
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean addCc(InternetAddress address) {
|
||||
try {
|
||||
if (address != null) {
|
||||
this.mailMessage.addCc(address);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean addCc(Collection addresses) {
|
||||
if (addresses != null && !addresses.isEmpty()) {
|
||||
addresses.forEach((address) -> this.addCc(address));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean addBcc(String email) {
|
||||
return this.addBcc(email, (String)null);
|
||||
}
|
||||
|
||||
public boolean addBcc(String email, String name) {
|
||||
try {
|
||||
this.mailMessage.addBcc(email, name);
|
||||
return true;
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean addBcc(InternetAddress address) {
|
||||
try {
|
||||
if (address != null) {
|
||||
this.mailMessage.addBcc(address);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean addBcc(Collection addresses) {
|
||||
if (addresses != null && !addresses.isEmpty()) {
|
||||
addresses.forEach((address) -> this.addBcc(address));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public Address[] getAllRecipients() {
|
||||
try {
|
||||
return this.mailMessage != null ? this.mailMessage.getMimeMessage().getAllRecipients() : null;
|
||||
} catch (MessagingException var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasRecipients() {
|
||||
Address[] addresses = this.getAllRecipients();
|
||||
return addresses != null && addresses.length > 0;
|
||||
}
|
||||
|
||||
public void clearTo() {
|
||||
try {
|
||||
this.mailMessage.getMimeMessage().setRecipients(RecipientType.TO, (String)null);
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void clearCc() {
|
||||
try {
|
||||
this.mailMessage.getMimeMessage().setRecipients(RecipientType.CC, (String)null);
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void clearBcc() {
|
||||
try {
|
||||
this.mailMessage.getMimeMessage().setRecipients(RecipientType.BCC, (String)null);
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void clearAllRecipients() {
|
||||
this.clearTo();
|
||||
this.clearCc();
|
||||
this.clearBcc();
|
||||
}
|
||||
|
||||
public boolean setSubject(String subject) {
|
||||
try {
|
||||
this.mailMessage.setSubject(subject);
|
||||
return true;
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean setText(String content) {
|
||||
return this.setContent(content, false);
|
||||
}
|
||||
|
||||
public boolean setHtml(String content) {
|
||||
return this.setContent(content, true);
|
||||
}
|
||||
|
||||
public boolean setContent(String content, boolean isHtml) {
|
||||
try {
|
||||
this.mailMessage.setText(content, isHtml);
|
||||
return true;
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean addAttachment(String filePath) {
|
||||
McFile file = new McFile(filePath);
|
||||
return file.exists() ? this.addAttachment((String)file.getName(), (File)file) : false;
|
||||
}
|
||||
|
||||
public boolean addAttachment(File file, String fileName) {
|
||||
return file.exists() ? this.addAttachment(fileName, file) : false;
|
||||
}
|
||||
|
||||
public boolean addAttachment(String... filePaths) {
|
||||
if (filePaths != null && filePaths.length != 0) {
|
||||
for(String filePath : filePaths) {
|
||||
if (!this.addAttachment(filePath)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean addAttachment(String fileName, File file) {
|
||||
try {
|
||||
this.mailMessage.addAttachment(fileName, file);
|
||||
return true;
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean addAttachment(String fileName, InputStream is) {
|
||||
try {
|
||||
this.mailMessage.addAttachment(fileName, new InputStreamResource(is));
|
||||
return true;
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean addAttachment(String fileName, byte[] bytes, String contentType) {
|
||||
try {
|
||||
this.mailMessage.addAttachment(fileName, new ByteArrayResource(bytes), contentType);
|
||||
return true;
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean addImage(String filePath) {
|
||||
McFile file = new McFile(filePath);
|
||||
return file.exists() ? this.addImage(file.getName(), (File)file) : false;
|
||||
}
|
||||
|
||||
public boolean addImage(String... filePaths) {
|
||||
if (filePaths != null && filePaths.length != 0) {
|
||||
for(String filePath : filePaths) {
|
||||
if (!this.addImage(filePath)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean addImage(String fileName, File file) {
|
||||
try {
|
||||
this.mailMessage.addInline(fileName, file);
|
||||
return true;
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean addImage(String fileName, InputStream is) {
|
||||
try {
|
||||
this.mailMessage.addInline(fileName, new InputStreamResource(is));
|
||||
return true;
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean addImage(String fileName, byte[] bytes, String contentType) {
|
||||
try {
|
||||
this.mailMessage.addInline(fileName, new ByteArrayResource(bytes), contentType);
|
||||
return true;
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void send() {
|
||||
if (this.hasRecipients()) {
|
||||
Runnable sendMail = new Runnable() {
|
||||
public void run() {
|
||||
try {
|
||||
McMailSender.this.mailSender.send(McMailSender.this.mailMessage.getMimeMessage());
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
};
|
||||
ExecutorService execService = Executors.newFixedThreadPool(1);
|
||||
execService.execute(sendMail);
|
||||
execService.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.mitac.cell.internet.websocket;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import org.springframework.web.socket.CloseStatus;
|
||||
|
||||
public enum SocketCloseStatus {
|
||||
NORMAL(1000),
|
||||
GOING_AWAY(1001),
|
||||
PROTOCOL_ERROR(1002),
|
||||
NOT_ACCEPTABLE(1003),
|
||||
NO_STATUS_CODE(1005),
|
||||
NO_CLOSE_FRAME(1006),
|
||||
BAD_DATA(1007),
|
||||
POLICY_VIOLATION(1008),
|
||||
TOO_BIG_TO_PROCESS(1009),
|
||||
REQUIRED_EXTENSION(1010),
|
||||
SERVER_ERROR(1011),
|
||||
SERVICE_RESTARTED(1012),
|
||||
SERVICE_OVERLOAD(1013),
|
||||
TLS_HANDSHAKE_FAILURE(1015),
|
||||
SESSION_NOT_RELIABLE(4500),
|
||||
UNKNOWN(-1);
|
||||
|
||||
private int code;
|
||||
|
||||
private SocketCloseStatus(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public static SocketCloseStatus get(int code) {
|
||||
for(SocketCloseStatus status : values()) {
|
||||
if (status.code == code) {
|
||||
return status;
|
||||
}
|
||||
}
|
||||
|
||||
return UNKNOWN;
|
||||
}
|
||||
|
||||
public static String reason(CloseStatus status) {
|
||||
String reason = status.getReason();
|
||||
if (Strings.isNullOrEmpty(reason)) {
|
||||
reason = get(status.getCode()).name();
|
||||
}
|
||||
|
||||
return reason;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.mitac.cell.io;
|
||||
|
||||
import java.security.cert.Certificate;
|
||||
import java.security.cert.CertificateEncodingException;
|
||||
|
||||
public class ApkSign {
|
||||
private String type;
|
||||
private byte[] certificate;
|
||||
private byte[] publicKey;
|
||||
private String algorithm;
|
||||
private String format;
|
||||
|
||||
public ApkSign(Certificate certificate) {
|
||||
try {
|
||||
this.setType(certificate.getType());
|
||||
this.setCertificate(certificate.getEncoded());
|
||||
this.setPublicKey(certificate.getPublicKey().getEncoded());
|
||||
this.setAlgorithm(certificate.getPublicKey().getAlgorithm());
|
||||
this.setFormat(certificate.getPublicKey().getFormat());
|
||||
} catch (CertificateEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public byte[] getCertificate() {
|
||||
return this.certificate;
|
||||
}
|
||||
|
||||
public void setCertificate(byte[] certificate) {
|
||||
this.certificate = certificate;
|
||||
}
|
||||
|
||||
public byte[] getPublicKey() {
|
||||
return this.publicKey;
|
||||
}
|
||||
|
||||
public void setPublicKey(byte[] publicKey) {
|
||||
this.publicKey = publicKey;
|
||||
}
|
||||
|
||||
public String getAlgorithm() {
|
||||
return this.algorithm;
|
||||
}
|
||||
|
||||
public void setAlgorithm(String algorithm) {
|
||||
this.algorithm = algorithm;
|
||||
}
|
||||
|
||||
public String getFormat() {
|
||||
return this.format;
|
||||
}
|
||||
|
||||
public void setFormat(String format) {
|
||||
this.format = format;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package com.mitac.cell.io;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.io.StringWriter;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.util.List;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.transform.Transformer;
|
||||
import javax.xml.transform.TransformerConfigurationException;
|
||||
import javax.xml.transform.TransformerException;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
import net.dongliu.apk.parser.ApkFile;
|
||||
import net.dongliu.apk.parser.bean.AdaptiveIcon;
|
||||
import net.dongliu.apk.parser.bean.ApkSigner;
|
||||
import net.dongliu.apk.parser.bean.CertificateMeta;
|
||||
import net.dongliu.apk.parser.bean.Icon;
|
||||
import net.dongliu.apk.parser.bean.IconFace;
|
||||
import net.dongliu.apk.parser.bean.IconPath;
|
||||
import org.apache.batik.transcoder.TranscoderInput;
|
||||
import org.apache.batik.transcoder.TranscoderOutput;
|
||||
import org.apache.batik.transcoder.image.PNGTranscoder;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
public class McApkFile extends ApkFile {
|
||||
public McApkFile(File apkFile) throws IOException {
|
||||
super(apkFile);
|
||||
}
|
||||
|
||||
public McApkFile(String apkFile) throws IOException {
|
||||
super(new File(apkFile));
|
||||
}
|
||||
|
||||
public String getCertMd5() {
|
||||
try {
|
||||
List<ApkSigner> signers = this.getApkSingers();
|
||||
if (signers != null && signers.size() > 0) {
|
||||
return ((CertificateMeta)((ApkSigner)signers.get(0)).getCertificateMetas().get(0)).getCertMd5();
|
||||
}
|
||||
} catch (CertificateException var2) {
|
||||
} catch (IOException var3) {
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public byte[] iconBytes() {
|
||||
try {
|
||||
Icon bigIcon = null;
|
||||
|
||||
for(IconFace icon : this.getAllIcons()) {
|
||||
if (icon != null) {
|
||||
if (icon instanceof Icon && icon.isFile()) {
|
||||
if (bigIcon == null || bigIcon.getDensity() < ((Icon)icon).getDensity()) {
|
||||
bigIcon = (Icon)icon;
|
||||
break;
|
||||
}
|
||||
} else if (icon instanceof AdaptiveIcon) {
|
||||
Icon foreground = ((AdaptiveIcon)icon).getForeground();
|
||||
if (foreground == null) {
|
||||
String iconPath = ((IconPath)this.getIconPaths().get(0)).getPath();
|
||||
String drawable = this.transBinaryXml(iconPath);
|
||||
String svg = this.androidVectorDrawableToSvg(drawable);
|
||||
if (!Strings.isNullOrEmpty(svg)) {
|
||||
return this.svgToPng(svg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return bigIcon != null ? bigIcon.getData() : null;
|
||||
} catch (Exception var8) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean saveIcon(String path) {
|
||||
byte[] iconBytes = this.iconBytes();
|
||||
return iconBytes != null ? (new McFile(path)).write(iconBytes) : false;
|
||||
}
|
||||
|
||||
public String androidVectorDrawableToSvg(String drawable) {
|
||||
try {
|
||||
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
|
||||
Document source = builder.parse(new InputSource(new StringReader(drawable)));
|
||||
Document target = builder.newDocument();
|
||||
target.setXmlVersion("1.0");
|
||||
Element element = source.getDocumentElement();
|
||||
Node svgElement = this.convertToSvg(target, element, (Node)null);
|
||||
target.appendChild(svgElement);
|
||||
return this.toXml(target);
|
||||
} catch (ParserConfigurationException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
} catch (SAXException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public Node convertToSvg(Document doc, Node srcNode, Node destNode) {
|
||||
String nodeName = srcNode.getNodeName();
|
||||
Element element = null;
|
||||
switch (nodeName) {
|
||||
case "vector":
|
||||
element = doc.createElement("svg");
|
||||
break;
|
||||
case "path":
|
||||
element = doc.createElement("path");
|
||||
break;
|
||||
case "group":
|
||||
element = doc.createElement("g");
|
||||
}
|
||||
|
||||
if (element == null) {
|
||||
return destNode;
|
||||
} else {
|
||||
this.setAttribute(srcNode, element);
|
||||
if (destNode == null) {
|
||||
destNode = element;
|
||||
} else {
|
||||
destNode = destNode.appendChild(element);
|
||||
}
|
||||
|
||||
NodeList children = srcNode.getChildNodes();
|
||||
|
||||
for(int i = 0; i < children.getLength(); ++i) {
|
||||
Node childNode = children.item(i);
|
||||
this.convertToSvg(doc, childNode, destNode);
|
||||
}
|
||||
|
||||
return destNode;
|
||||
}
|
||||
}
|
||||
|
||||
private void setAttribute(Node srcNode, Element destNode) {
|
||||
String nodeName = srcNode.getNodeName();
|
||||
NamedNodeMap attrs = srcNode.getAttributes();
|
||||
if (nodeName.equals("vector")) {
|
||||
destNode.setAttribute("xmlns", "http://www.w3.org/2000/svg");
|
||||
destNode.setAttribute("width", "96");
|
||||
destNode.setAttribute("height", "96");
|
||||
destNode.setAttribute("viewBox", String.format("%d %d %d %d", 0, 0, 120, 120));
|
||||
} else {
|
||||
for(int i = 0; i < attrs.getLength(); ++i) {
|
||||
Node attr = attrs.item(i);
|
||||
String name = attr.getNodeName();
|
||||
String value = attr.getNodeValue();
|
||||
switch (name) {
|
||||
case "android:name":
|
||||
case "android:height":
|
||||
case "android:width":
|
||||
case "android:viewportWidth":
|
||||
case "android:viewportHeight":
|
||||
case "android:tint":
|
||||
case "android:tintMode":
|
||||
case "android:autoMirrored":
|
||||
case "android:alpha":
|
||||
case "android:strokeAlpha":
|
||||
case "android:strokeLineCap":
|
||||
case "android:strokeLineJoin":
|
||||
case "android:strokeMiterLimit":
|
||||
case "android:strokeWidth":
|
||||
case "android:fillAlpha":
|
||||
case "android:translateX":
|
||||
case "android:translateY":
|
||||
default:
|
||||
break;
|
||||
case "android:fillColor":
|
||||
destNode.setAttribute("fill", this.colorValue(value));
|
||||
break;
|
||||
case "android:pathData":
|
||||
destNode.setAttribute("d", value);
|
||||
break;
|
||||
case "android:strokeColor":
|
||||
destNode.setAttribute("stroke", this.colorValue(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private String colorValue(String color) {
|
||||
if (color.startsWith("#")) {
|
||||
return color;
|
||||
} else {
|
||||
int length = color.length();
|
||||
if (length < 6) {
|
||||
for(int i = 0; i < 6 - length; ++i) {
|
||||
color = color + "0";
|
||||
}
|
||||
}
|
||||
|
||||
return "#" + color;
|
||||
}
|
||||
}
|
||||
|
||||
public String toXml(Document doc) {
|
||||
try {
|
||||
TransformerFactory tf = TransformerFactory.newInstance();
|
||||
Transformer transformer = tf.newTransformer();
|
||||
StringWriter writer = new StringWriter();
|
||||
transformer.transform(new DOMSource(doc), new StreamResult(writer));
|
||||
return writer.getBuffer().toString().replaceAll("\n|\r", "");
|
||||
} catch (TransformerConfigurationException e) {
|
||||
e.printStackTrace();
|
||||
} catch (TransformerException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public byte[] svgToPng(String svg) {
|
||||
try {
|
||||
ByteArrayInputStream input = new ByteArrayInputStream(svg.getBytes());
|
||||
TranscoderInput transcoderInput = new TranscoderInput(input);
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
TranscoderOutput transcoderOutput = new TranscoderOutput(output);
|
||||
PNGTranscoder pngTranscoder = new PNGTranscoder();
|
||||
pngTranscoder.transcode(transcoderInput, transcoderOutput);
|
||||
byte[] data = output.toByteArray();
|
||||
output.close();
|
||||
input.close();
|
||||
return data;
|
||||
} catch (Exception var8) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
package com.mitac.cell.io;
|
||||
|
||||
import com.mitac.cell.data.McCompress;
|
||||
import com.mitac.cell.data.McDecompress;
|
||||
import com.mitac.cell.security.McCrypto;
|
||||
import com.mitac.cell.utils.McNumberUtils;
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class McEncryptedFileDrive {
|
||||
private byte[] mKey;
|
||||
private File mFile;
|
||||
private boolean mUnclocked;
|
||||
private boolean mInstantSave;
|
||||
private McFileTable mFileTable;
|
||||
private Header mHeader;
|
||||
|
||||
public McEncryptedFileDrive(String path) {
|
||||
this(new McFile(path));
|
||||
}
|
||||
|
||||
public McEncryptedFileDrive(String path, String key) {
|
||||
this(path, key.getBytes());
|
||||
}
|
||||
|
||||
public McEncryptedFileDrive(String path, byte[] key) {
|
||||
this(path);
|
||||
this.setKey(key);
|
||||
}
|
||||
|
||||
public McEncryptedFileDrive(McFile file) {
|
||||
this.mUnclocked = false;
|
||||
this.mInstantSave = true;
|
||||
this.mHeader = new Header();
|
||||
this.mFileTable = new McFileTable();
|
||||
this.mFile = file;
|
||||
if (this.mFile.exists()) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public boolean unlock(String key) {
|
||||
return this.mUnclocked;
|
||||
}
|
||||
|
||||
public boolean isSameKey() {
|
||||
return Arrays.equals(this.mKey, this.mHeader.getKey());
|
||||
}
|
||||
|
||||
public void compressed(boolean compressed) {
|
||||
this.mHeader.compressed(compressed);
|
||||
}
|
||||
|
||||
public boolean compressed() {
|
||||
return this.mHeader.compressed();
|
||||
}
|
||||
|
||||
public void enableInstantSave(boolean enable) {
|
||||
this.mInstantSave = enable;
|
||||
}
|
||||
|
||||
public void setKey(String key) {
|
||||
this.setKey(key.getBytes());
|
||||
}
|
||||
|
||||
public void setKey(byte[] key) {
|
||||
this.mHeader.setKey(this.mKey = McCrypto.encryptMessageByHmacMd5(key));
|
||||
}
|
||||
|
||||
public void setMaxSize(long size) {
|
||||
}
|
||||
|
||||
public void length() {
|
||||
}
|
||||
|
||||
public boolean isEncrypted() {
|
||||
return this.mKey != null;
|
||||
}
|
||||
|
||||
public void setCurPath(String curPath) {
|
||||
}
|
||||
|
||||
public McJsonFile getFile(String path) {
|
||||
return this.mFileTable.getFile(path);
|
||||
}
|
||||
|
||||
public List getFiles() {
|
||||
return this.mFileTable.getFiles("/");
|
||||
}
|
||||
|
||||
public List getFiles(String path) {
|
||||
return this.mFileTable.getFiles(path);
|
||||
}
|
||||
|
||||
public boolean isDirectory(String folderPath) {
|
||||
return this.mFileTable.getFolder(folderPath) != null;
|
||||
}
|
||||
|
||||
public boolean isFile(String path) {
|
||||
return this.mFileTable.getFile(path) != null;
|
||||
}
|
||||
|
||||
public boolean exists(String path) {
|
||||
return this.isDirectory(path) || this.isFile(path);
|
||||
}
|
||||
|
||||
public void addFolder(String folderPath) {
|
||||
this.mFileTable.addFolder(folderPath);
|
||||
if (this.mInstantSave) {
|
||||
this.save();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void addFile(String filePath, byte[] data) {
|
||||
this.mFileTable.addFile(filePath, data);
|
||||
if (this.mInstantSave) {
|
||||
this.save();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void addFile(String sourcePath, String destinationPath) {
|
||||
File file = new File(sourcePath);
|
||||
if (file.exists()) {
|
||||
this.mFileTable.addFile(sourcePath, destinationPath);
|
||||
if (this.mInstantSave) {
|
||||
this.save();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public void copyTo(String orgFilePath, String destinationPath) {
|
||||
this.mFileTable.getFile(orgFilePath).extractTo(destinationPath);
|
||||
}
|
||||
|
||||
public void move(String orgfilPath, String destinatinFile) {
|
||||
}
|
||||
|
||||
public void delete(String path) {
|
||||
this.remove(path);
|
||||
}
|
||||
|
||||
public void remove(String path) {
|
||||
if (!this.mFileTable.removeFolder(path)) {
|
||||
this.mFileTable.removeFile(path);
|
||||
}
|
||||
|
||||
if (this.mInstantSave) {
|
||||
this.save();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void rename(String path, String newFileName) {
|
||||
if (this.mInstantSave) {
|
||||
this.save();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void paste(String destinationFolder) {
|
||||
if (this.mInstantSave) {
|
||||
this.save();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public String[] list(String folderName) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean load() {
|
||||
InputStream ios = null;
|
||||
ByteArrayOutputStream ous = null;
|
||||
byte[] source = null;
|
||||
|
||||
try {
|
||||
byte[] buffer = new byte[8096];
|
||||
ios = new BufferedInputStream(new FileInputStream(this.mFile));
|
||||
this.mHeader.setBytes(ios);
|
||||
ous = new ByteArrayOutputStream();
|
||||
int read = 0;
|
||||
|
||||
while((read = ios.read(buffer)) != -1) {
|
||||
ous.write(buffer, 0, read);
|
||||
}
|
||||
|
||||
source = ous.toByteArray();
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
if (ous != null) {
|
||||
ous.close();
|
||||
}
|
||||
} catch (IOException var20) {
|
||||
}
|
||||
|
||||
try {
|
||||
if (ios != null) {
|
||||
ios.close();
|
||||
}
|
||||
} catch (IOException var19) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (this.mHeader.hasKey() && !this.isSameKey()) {
|
||||
return false;
|
||||
} else {
|
||||
if (this.compressed()) {
|
||||
source = McDecompress.decompress(source);
|
||||
}
|
||||
|
||||
source = McCrypto.encryptByAES(this.mKey, source, 0);
|
||||
return this.mFileTable.setBytes(source);
|
||||
}
|
||||
}
|
||||
|
||||
public void extractFiles(String destinationPath) {
|
||||
this.mFileTable.extractFiles(destinationPath);
|
||||
}
|
||||
|
||||
public void save() {
|
||||
try {
|
||||
OutputStream os = new FileOutputStream(this.mFile);
|
||||
os.write(this.mHeader.getBytes());
|
||||
byte[] source = this.getEncryptedData();
|
||||
os.write(source);
|
||||
os.flush();
|
||||
os.close();
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private byte[] getEncryptedData() {
|
||||
int bufferSize = 65536;
|
||||
byte[] source = this.mFileTable.getBytes();
|
||||
int total = source.length;
|
||||
|
||||
for(int remains = source.length; remains > 0; remains -= bufferSize) {
|
||||
if (remains < bufferSize) {
|
||||
bufferSize = remains;
|
||||
}
|
||||
|
||||
byte[] buffer = new byte[bufferSize];
|
||||
System.arraycopy(source, total - remains, buffer, 0, bufferSize);
|
||||
byte[] encrypted = McCrypto.encryptByAES(this.mKey, buffer, 1);
|
||||
System.arraycopy(encrypted, 0, source, total - remains, bufferSize);
|
||||
}
|
||||
|
||||
if (this.compressed()) {
|
||||
return McCompress.compress(source);
|
||||
} else {
|
||||
return source;
|
||||
}
|
||||
}
|
||||
|
||||
protected final class Header {
|
||||
private final byte[] FILE_PREFIX;
|
||||
private final byte FLAG_TRASHCAN_EANABLED;
|
||||
private final byte FLAG_COMPRESSED;
|
||||
private final byte FLAG_HAS_KEY;
|
||||
private final byte[] mVersion;
|
||||
private boolean mCompressed;
|
||||
private boolean mTrashcanEnabled;
|
||||
private boolean mHasKey;
|
||||
private byte mReservedFlag;
|
||||
private byte[] mPassword;
|
||||
|
||||
public Header() {
|
||||
this(true, false, false);
|
||||
}
|
||||
|
||||
public Header(boolean compressed, boolean encrypted, boolean trashcanEnabled) {
|
||||
this.FILE_PREFIX = new byte[]{69, 70, 68, 3};
|
||||
this.FLAG_TRASHCAN_EANABLED = 1;
|
||||
this.FLAG_COMPRESSED = 16;
|
||||
this.FLAG_HAS_KEY = 32;
|
||||
this.mVersion = new byte[]{0, 3, 1, 0};
|
||||
this.mHasKey = false;
|
||||
this.mReservedFlag = -1;
|
||||
this.mCompressed = compressed;
|
||||
this.mTrashcanEnabled = trashcanEnabled;
|
||||
}
|
||||
|
||||
public final void setVersion(String version) {
|
||||
String[] data = version.split("\\.");
|
||||
|
||||
for(int i = 0; i < data.length && i < 4; ++i) {
|
||||
this.mVersion[i] = Byte.parseByte(data[i]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public final String getVersion() {
|
||||
return String.format("%d.%d.%d.%d", this.mVersion[0], this.mVersion[1], this.mVersion[2], this.mVersion[3]);
|
||||
}
|
||||
|
||||
public final void setKey(byte[] key) {
|
||||
if (key != null) {
|
||||
this.mPassword = key;
|
||||
this.mHasKey = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public byte[] getKey() {
|
||||
return this.mPassword;
|
||||
}
|
||||
|
||||
public final void compressed(boolean compressed) {
|
||||
this.mCompressed = compressed;
|
||||
}
|
||||
|
||||
public final boolean compressed() {
|
||||
return this.mCompressed;
|
||||
}
|
||||
|
||||
public final boolean hasKey() {
|
||||
return this.mHasKey;
|
||||
}
|
||||
|
||||
public final void trashcanEnabled(boolean trashcanEnabled) {
|
||||
this.mTrashcanEnabled = trashcanEnabled;
|
||||
}
|
||||
|
||||
public final boolean trashcanEnabled() {
|
||||
return this.mTrashcanEnabled;
|
||||
}
|
||||
|
||||
private final byte getFlag() {
|
||||
byte flag = 0;
|
||||
if (this.mCompressed) {
|
||||
flag = (byte)(flag | 16);
|
||||
}
|
||||
|
||||
if (this.mTrashcanEnabled) {
|
||||
flag = (byte)(flag | 1);
|
||||
}
|
||||
|
||||
if (this.mHasKey) {
|
||||
flag = (byte)(flag | 32);
|
||||
}
|
||||
|
||||
return flag;
|
||||
}
|
||||
|
||||
public final boolean setBytes(byte[] headerBytes) {
|
||||
return this.setBytes((InputStream)(new ByteArrayInputStream(headerBytes)));
|
||||
}
|
||||
|
||||
public final boolean setBytes(InputStream bis) {
|
||||
try {
|
||||
byte[] header = new byte[4];
|
||||
bis.read(header, 0, 4);
|
||||
if (!Arrays.equals(header, this.FILE_PREFIX)) {
|
||||
return false;
|
||||
} else {
|
||||
bis.read(this.mVersion, 0, 4);
|
||||
byte flag = (byte)bis.read();
|
||||
this.mCompressed = (flag & 16) > 0;
|
||||
this.mTrashcanEnabled = (flag & 1) > 0;
|
||||
this.mHasKey = (flag & 32) > 0;
|
||||
this.mReservedFlag = (byte)bis.read();
|
||||
if (this.mHasKey) {
|
||||
byte[] lenData = new byte[4];
|
||||
bis.read(lenData, 0, 4);
|
||||
int len = McNumberUtils.toInt(true, lenData);
|
||||
this.mPassword = new byte[len];
|
||||
bis.read(this.mPassword, 0, len);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public final byte[] getBytes() {
|
||||
byte[] header = null;
|
||||
|
||||
try {
|
||||
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
byteArrayOutputStream.write(this.FILE_PREFIX);
|
||||
byteArrayOutputStream.write(this.mVersion);
|
||||
byteArrayOutputStream.write(this.getFlag());
|
||||
byteArrayOutputStream.write(this.mReservedFlag);
|
||||
if (this.mHasKey) {
|
||||
int len = this.mPassword.length;
|
||||
byteArrayOutputStream.write(McNumberUtils.toBytes(4, true, len));
|
||||
byteArrayOutputStream.write(this.mPassword);
|
||||
}
|
||||
|
||||
header = byteArrayOutputStream.toByteArray();
|
||||
byteArrayOutputStream.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return header;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
package com.mitac.cell.io;
|
||||
|
||||
import com.google.common.hash.HashFunction;
|
||||
import com.google.common.hash.Hasher;
|
||||
import com.google.common.hash.Hashing;
|
||||
import com.google.common.io.BaseEncoding;
|
||||
import com.google.common.io.Files;
|
||||
import com.mitac.cell.utils.McStringUtils;
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.tika.Tika;
|
||||
|
||||
public class McFile extends File {
|
||||
public static final long KB = 1024L;
|
||||
public static final long MB = 1048576L;
|
||||
public static final long GB = 1073741824L;
|
||||
public static final long TB = 1099511627776L;
|
||||
public static String CONTENT_TYPE_XLS = "application/vnd.ms-excel";
|
||||
public static String CONTENT_TYPE_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
||||
|
||||
public McFile(String filePath) {
|
||||
super(filePath);
|
||||
}
|
||||
|
||||
public McFile(String folderPath, String fileName) {
|
||||
super(folderPath, fileName);
|
||||
}
|
||||
|
||||
public McFile(File file) {
|
||||
this(file.getPath());
|
||||
}
|
||||
|
||||
public McFile(File file, String fileName) {
|
||||
super(file, fileName);
|
||||
}
|
||||
|
||||
public McFile(McFile file, String fileName) {
|
||||
super(file, fileName);
|
||||
}
|
||||
|
||||
public boolean createParentDirs() {
|
||||
if (this.getParentFile().exists() && this.getParentFile().isDirectory()) {
|
||||
return true;
|
||||
} else {
|
||||
try {
|
||||
Files.createParentDirs(this);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean createDirs() {
|
||||
if (!this.createParentDirs()) {
|
||||
return false;
|
||||
} else if (!this.exists()) {
|
||||
return this.mkdir();
|
||||
} else {
|
||||
return this.isDirectory();
|
||||
}
|
||||
}
|
||||
|
||||
public McFile getParentFile() {
|
||||
return new McFile(this.getParent());
|
||||
}
|
||||
|
||||
public String toBase64() {
|
||||
byte[] bytes = this.toBytes();
|
||||
return bytes == null ? null : BaseEncoding.base64().encode(bytes);
|
||||
}
|
||||
|
||||
public byte[] toBytes() {
|
||||
try {
|
||||
return this.exists() ? Files.toByteArray(this) : null;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
try {
|
||||
return (new Tika()).detect(this);
|
||||
} catch (IOException var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public long getCrcChecksum() {
|
||||
return this.getCrcChecksum((Integer)null);
|
||||
}
|
||||
|
||||
public long getCrcChecksum(Integer length) {
|
||||
HashFunction hf = Hashing.crc32();
|
||||
|
||||
try {
|
||||
if (length == null) {
|
||||
return Files.asByteSource(this).hash(hf).padToLong();
|
||||
} else {
|
||||
Hasher hasher = hf.newHasher();
|
||||
BufferedInputStream bis = new BufferedInputStream(this.getInputStream());
|
||||
byte[] buffer = new byte[8388608];
|
||||
int remained = length;
|
||||
int n = 0;
|
||||
int maxLength = remained > buffer.length ? buffer.length : remained;
|
||||
|
||||
while((n = bis.read(buffer, 0, maxLength)) > 0) {
|
||||
hasher.putBytes(buffer, 0, n);
|
||||
remained -= n;
|
||||
if (remained < maxLength) {
|
||||
maxLength = remained;
|
||||
}
|
||||
}
|
||||
|
||||
return hasher.hash().padToLong();
|
||||
}
|
||||
} catch (IOException e1) {
|
||||
e1.printStackTrace();
|
||||
return -1L;
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] getMd5() {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
return md.digest(this.toBytes());
|
||||
} catch (NoSuchAlgorithmException var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String getMd5Hex() {
|
||||
return McStringUtils.toHexString(this.getMd5());
|
||||
}
|
||||
|
||||
public String getExtension() {
|
||||
return Files.getFileExtension(this.getName());
|
||||
}
|
||||
|
||||
public String getNameWithoutExtension() {
|
||||
return Files.getNameWithoutExtension(this.getName());
|
||||
}
|
||||
|
||||
public boolean write(byte[] data) {
|
||||
ByteArrayInputStream bis = new ByteArrayInputStream(data);
|
||||
return this.write((InputStream)bis);
|
||||
}
|
||||
|
||||
public boolean write(InputStream is) {
|
||||
try {
|
||||
OutputStream os = this.getOutputStream();
|
||||
if (os == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
BufferedOutputStream bos = new BufferedOutputStream(os);
|
||||
byte[] buffer = new byte[8388608];
|
||||
int count = 0;
|
||||
|
||||
while((count = is.read(buffer)) != -1) {
|
||||
bos.write(buffer, 0, count);
|
||||
}
|
||||
|
||||
bos.flush();
|
||||
bos.close();
|
||||
is.close();
|
||||
return true;
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean saveAs(String targetFileName, boolean overwrite) {
|
||||
return this.saveAs(new McFile(targetFileName), overwrite);
|
||||
}
|
||||
|
||||
public boolean saveAs(McFile target, boolean overwrite) {
|
||||
if (this.exists() && !target.isDirectory()) {
|
||||
if (target.exists() && !overwrite) {
|
||||
return false;
|
||||
} else {
|
||||
try {
|
||||
Files.copy(this, target);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean moveFrom(McFile file) {
|
||||
if (!file.exists()) {
|
||||
return false;
|
||||
} else {
|
||||
try {
|
||||
FileUtils.forceMkdirParent(this);
|
||||
return this.write(file.getInputStream()) ? file.delete() : false;
|
||||
} catch (IOException var3) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean moveFrom(File file) {
|
||||
return this.moveFrom(new McFile(file));
|
||||
}
|
||||
|
||||
public boolean moveTo(String path) {
|
||||
return (new McFile(path)).moveFrom(this);
|
||||
}
|
||||
|
||||
public boolean delete() {
|
||||
if (!this.exists()) {
|
||||
return true;
|
||||
} else if (this.isFile()) {
|
||||
return super.delete();
|
||||
} else {
|
||||
File[] files = this.listFiles();
|
||||
boolean cleared = true;
|
||||
if (files != null && files.length > 0) {
|
||||
for(File file : files) {
|
||||
if (!(new McFile(file.getPath())).delete()) {
|
||||
cleared = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (cleared) {
|
||||
super.delete();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean deleteParent() {
|
||||
try {
|
||||
FileUtils.deleteDirectory(this.getParentFile());
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public InputStream getInputStream() {
|
||||
try {
|
||||
return new FileInputStream(this);
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public OutputStream getOutputStream() {
|
||||
try {
|
||||
return new FileOutputStream(this);
|
||||
} catch (FileNotFoundException var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean exists(String path) {
|
||||
return (new McFile(path)).exists();
|
||||
}
|
||||
|
||||
public long length() {
|
||||
long total = 0L;
|
||||
if (!this.exists()) {
|
||||
return -1L;
|
||||
} else {
|
||||
if (this.isDirectory()) {
|
||||
String[] fileList = this.list();
|
||||
if (fileList != null) {
|
||||
for(String fileName : this.list()) {
|
||||
total += (new McFile(this, fileName)).length();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
total += super.length();
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package com.mitac.cell.io;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mitac.cell.net.Uri;
|
||||
import com.mitac.cell.utils.McJsonUtils;
|
||||
import com.mitac.cell.utils.McNumberUtils;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class McFileTable {
|
||||
private static final String KEY_EFD = "EFD";
|
||||
private static final String KEY_FILE = "file";
|
||||
private JsonObject mFileTable = new JsonObject();
|
||||
private JsonObject mRoot = new JsonObject();
|
||||
private final ArrayList mFileArray;
|
||||
|
||||
public McFileTable() {
|
||||
this.mFileTable.add("EFD", this.mRoot);
|
||||
this.mFileArray = new ArrayList();
|
||||
}
|
||||
|
||||
public void addFile(String sourceFilePath, String destinationPath) {
|
||||
JsonObject targetFolder = this.addFolder((new File(destinationPath)).getParent());
|
||||
JsonArray filesArray = this.getFilesArray(targetFolder);
|
||||
McJsonFile jsonFile = new McJsonFile(sourceFilePath, destinationPath);
|
||||
filesArray.add(jsonFile.toJsonObject());
|
||||
this.mFileArray.add(jsonFile);
|
||||
}
|
||||
|
||||
public void addFile(String destinationFile, byte[] data) {
|
||||
JsonObject targetFolder = this.addFolder((new File(destinationFile)).getParent());
|
||||
JsonArray filesArray = this.getFilesArray(targetFolder);
|
||||
McJsonFile jsonFile = new McJsonFile(destinationFile);
|
||||
jsonFile.setData(data);
|
||||
filesArray.add(jsonFile.toJsonObject());
|
||||
this.mFileArray.add(jsonFile);
|
||||
}
|
||||
|
||||
public boolean removeFile(String path) {
|
||||
File file = new File(path);
|
||||
JsonObject folder = this.getFolder(file.getParent());
|
||||
if (folder == null) {
|
||||
return false;
|
||||
} else {
|
||||
JsonArray files = folder.getAsJsonArray("file");
|
||||
if (files == null) {
|
||||
return false;
|
||||
} else {
|
||||
JsonArray newFiles = new JsonArray();
|
||||
String fileName = file.getName();
|
||||
|
||||
for(JsonElement jFile : files) {
|
||||
McJsonFile jsonFile = new McJsonFile(jFile.getAsJsonObject());
|
||||
if (!fileName.equals(jsonFile.getName())) {
|
||||
newFiles.add(jsonFile.toJsonObject());
|
||||
} else {
|
||||
this.mFileArray.remove(jsonFile);
|
||||
}
|
||||
}
|
||||
|
||||
folder.add("file", newFiles);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String[] getNames(JsonObject jPath) {
|
||||
String[] names = new String[jPath.size()];
|
||||
int i = 0;
|
||||
|
||||
for(Map.Entry jFile : jPath.entrySet()) {
|
||||
names[i++] = (String)jFile.getKey();
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
public ArrayList getFiles(String path) {
|
||||
JsonObject folder = this.getFolder(path);
|
||||
String[] names = this.getNames(folder);
|
||||
if (names == null) {
|
||||
return null;
|
||||
} else {
|
||||
ArrayList<McFile> fileArray = new ArrayList();
|
||||
|
||||
for(String name : names) {
|
||||
if (!name.equals("file")) {
|
||||
fileArray.add(new McFile(name));
|
||||
}
|
||||
}
|
||||
|
||||
JsonArray files = folder.getAsJsonArray("file");
|
||||
if (files != null) {
|
||||
for(JsonElement jFile : files) {
|
||||
McJsonFile jsonFile = new McJsonFile(jFile.getAsJsonObject());
|
||||
fileArray.add(new McFile(jsonFile.getName()));
|
||||
}
|
||||
}
|
||||
|
||||
return fileArray;
|
||||
}
|
||||
}
|
||||
|
||||
public McJsonFile getFile(String path) {
|
||||
File file = new File(path);
|
||||
JsonObject folder = this.getFolder(file.getParent());
|
||||
if (folder == null) {
|
||||
return null;
|
||||
} else {
|
||||
JsonArray jFiles = folder.getAsJsonArray("file");
|
||||
if (jFiles == null) {
|
||||
return null;
|
||||
} else {
|
||||
String fileName = file.getName();
|
||||
|
||||
for(JsonElement jFile : jFiles) {
|
||||
McJsonFile jsonFile = new McJsonFile(jFile.getAsJsonObject());
|
||||
if (fileName.equals(jsonFile.getName())) {
|
||||
return jsonFile;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JsonObject getFolder(String folderPath) {
|
||||
Uri uri = Uri.parse(folderPath);
|
||||
List<String> paths = uri.getPathSegments();
|
||||
return paths.size() > 0 && this.mRoot.has((String)paths.get(0)) ? this.mRoot.getAsJsonObject((String)paths.get(0)) : this.mRoot;
|
||||
}
|
||||
|
||||
private JsonArray getFilesArray(JsonObject jsonFolder) {
|
||||
JsonArray fileArray = jsonFolder.getAsJsonArray("file");
|
||||
if (fileArray == null) {
|
||||
fileArray = new JsonArray();
|
||||
jsonFolder.add("file", fileArray);
|
||||
}
|
||||
|
||||
return fileArray;
|
||||
}
|
||||
|
||||
public JsonObject addFolder(String path) {
|
||||
if (path != null && !path.isEmpty()) {
|
||||
Uri uri = Uri.parse(path);
|
||||
List<String> paths = uri.getPathSegments();
|
||||
JsonObject targetFolder = this.mRoot;
|
||||
|
||||
for(String pathSegment : paths) {
|
||||
JsonObject jFolder = targetFolder.getAsJsonObject(pathSegment);
|
||||
if (jFolder != null && jFolder.isJsonObject()) {
|
||||
targetFolder = jFolder;
|
||||
} else {
|
||||
jFolder = new JsonObject();
|
||||
targetFolder.add(pathSegment, jFolder);
|
||||
targetFolder = jFolder;
|
||||
}
|
||||
}
|
||||
|
||||
return targetFolder;
|
||||
} else {
|
||||
return this.mRoot;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean removeFolder(String path) {
|
||||
Uri uri = Uri.parse(path);
|
||||
List<String> paths = uri.getPathSegments();
|
||||
if (this.mRoot.has((String)paths.get(0))) {
|
||||
this.mRoot.remove((String)paths.get(0));
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void extractFiles(String destinationPath) {
|
||||
for(int i = 0; i < this.mFileArray.size(); ++i) {
|
||||
McJsonFile file = (McJsonFile)this.mFileArray.get(i);
|
||||
file.extract(destinationPath);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public boolean setBytes(byte[] buffer) {
|
||||
ByteArrayInputStream bos = new ByteArrayInputStream(buffer);
|
||||
byte[] data = new byte[4];
|
||||
bos.read(data, 0, 4);
|
||||
int len = McNumberUtils.toInt(true, data);
|
||||
data = new byte[len];
|
||||
bos.read(data, 0, len);
|
||||
this.mFileTable = McJsonUtils.toJson(data).getAsJsonObject();
|
||||
this.mRoot = this.mFileTable.getAsJsonObject("EFD");
|
||||
int startOffset = len + 4;
|
||||
this.dispatchFiles(buffer, this.mRoot, startOffset);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void dispatchFiles(byte[] buffer, JsonObject fileTable, int startOffset) {
|
||||
for(Map.Entry entry : fileTable.entrySet()) {
|
||||
JsonElement jPath = (JsonElement)entry.getValue();
|
||||
if (jPath.isJsonObject()) {
|
||||
this.dispatchFiles(buffer, jPath.getAsJsonObject(), startOffset);
|
||||
} else if (jPath.isJsonArray()) {
|
||||
for(JsonElement jChild : jPath.getAsJsonArray()) {
|
||||
McJsonFile jFile = new McJsonFile(jChild.getAsJsonObject());
|
||||
int offset = jFile.getOffset();
|
||||
int size = jFile.getSize();
|
||||
byte[] data = new byte[size];
|
||||
System.arraycopy(buffer, startOffset + offset, data, 0, size);
|
||||
jFile.setData(data);
|
||||
this.mFileArray.add(jFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public byte[] getBytes() {
|
||||
try {
|
||||
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
int offset = 0;
|
||||
|
||||
for(int i = 0; i < this.mFileArray.size(); ++i) {
|
||||
McJsonFile jsonFile = (McJsonFile)this.mFileArray.get(i);
|
||||
jsonFile.setOffset(offset);
|
||||
jsonFile.update();
|
||||
offset += jsonFile.getSize();
|
||||
}
|
||||
|
||||
byte[] data = this.mFileTable.toString().getBytes();
|
||||
byteArrayOutputStream.write(McNumberUtils.toBytes(4, true, data.length));
|
||||
byteArrayOutputStream.write(data);
|
||||
|
||||
for(int i = 0; i < this.mFileArray.size(); ++i) {
|
||||
byteArrayOutputStream.write(((McJsonFile)this.mFileArray.get(i)).getData());
|
||||
}
|
||||
|
||||
int n = 16 - byteArrayOutputStream.size() % 16;
|
||||
|
||||
for(int i = 0; i < n; ++i) {
|
||||
byteArrayOutputStream.write(0);
|
||||
}
|
||||
|
||||
return byteArrayOutputStream.toByteArray();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.mitac.cell.io;
|
||||
|
||||
import com.google.common.io.BaseEncoding;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
public class McInputStream {
|
||||
public static byte[] toBytes(InputStream is) {
|
||||
try {
|
||||
return ByteStreams.toByteArray(is);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String toBase64Encoded(InputStream is) {
|
||||
byte[] bytes = toBytes(is);
|
||||
return bytes == null ? null : BaseEncoding.base64().encode(bytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.mitac.cell.io;
|
||||
|
||||
import com.google.common.io.Files;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.mitac.cell.utils.McJsonUtils;
|
||||
import com.mitac.cell.utils.McStringUtils;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.sql.Date;
|
||||
|
||||
public class McJsonFile {
|
||||
private static final String KEY_NAME = "name";
|
||||
private static final String KEY_OFFSET = "offset";
|
||||
private static final String KEY_SIZE = "size";
|
||||
private static final String KEY_UPDATED = "updated";
|
||||
private static final String KEY_PERMISSION = "permission";
|
||||
private static final String KEY_DATA = "data";
|
||||
private JsonObject jFile;
|
||||
|
||||
public McJsonFile(File sourceFile) {
|
||||
this.jFile = new JsonObject();
|
||||
this.setName(sourceFile.getName());
|
||||
this.setData(sourceFile);
|
||||
}
|
||||
|
||||
public McJsonFile(String filePath) {
|
||||
this(new File(filePath));
|
||||
}
|
||||
|
||||
public McJsonFile(String sourceFile, String destinationFile) {
|
||||
this.setName(destinationFile);
|
||||
this.setData(new File(sourceFile));
|
||||
}
|
||||
|
||||
public McJsonFile(File sourceFile, String destinationFile) {
|
||||
this.setName(destinationFile);
|
||||
this.setData(sourceFile);
|
||||
}
|
||||
|
||||
public McJsonFile(String destinationFile, byte[] data) {
|
||||
this.setName(destinationFile);
|
||||
this.setData(data);
|
||||
}
|
||||
|
||||
public McJsonFile(JsonObject jsonFile) {
|
||||
this.jFile = jsonFile;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.jFile.addProperty("name", name);
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.jFile.getAsJsonPrimitive("name").getAsString();
|
||||
}
|
||||
|
||||
public void update() {
|
||||
this.jFile.addProperty("size", this.getData().length);
|
||||
}
|
||||
|
||||
public void setData(File file) {
|
||||
if (file.exists()) {
|
||||
try {
|
||||
this.jFile.addProperty("size", file.length());
|
||||
this.setData(Files.toByteArray(file));
|
||||
this.jFile.addProperty("updated", file.lastModified());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void setData(byte[] data) {
|
||||
String base64 = McStringUtils.toBase64(data);
|
||||
if (base64 != null) {
|
||||
this.jFile.addProperty("data", base64);
|
||||
this.jFile.addProperty("updated", System.currentTimeMillis());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public byte[] getData() {
|
||||
if (this.jFile.has("data")) {
|
||||
JsonPrimitive jPrimitive = this.jFile.getAsJsonPrimitive("data");
|
||||
return McStringUtils.fromBase64(jPrimitive.getAsString());
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public JsonObject toJsonObject() {
|
||||
JsonElement jsonElement = McJsonUtils.toJsonElement((Object)this.jFile);
|
||||
return jsonElement.getAsJsonObject();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return this.jFile.toString();
|
||||
}
|
||||
|
||||
public void extract(String destinationPath) {
|
||||
McFile file = new McFile(destinationPath, this.getName());
|
||||
file.write(this.getData());
|
||||
}
|
||||
|
||||
public void extractTo(String destinationPath) {
|
||||
McFile file = new McFile(destinationPath);
|
||||
file.write(this.getData());
|
||||
}
|
||||
|
||||
public void setLastUpdated(Date date) {
|
||||
this.setLastUpdated(date.getTime());
|
||||
}
|
||||
|
||||
public void setLastUpdated(long date) {
|
||||
this.jFile.addProperty("updated", date);
|
||||
}
|
||||
|
||||
public Date getLastUpdated() {
|
||||
if (this.jFile.has("updated")) {
|
||||
long date = this.jFile.getAsJsonPrimitive("updated").getAsLong();
|
||||
return new Date(date);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public int getSize() {
|
||||
if (this.jFile.has("size")) {
|
||||
int size = this.jFile.getAsJsonPrimitive("size").getAsInt();
|
||||
return size;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getOffset() {
|
||||
if (this.jFile.has("offset")) {
|
||||
int offset = this.jFile.getAsJsonPrimitive("offset").getAsInt();
|
||||
return offset;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public void setOffset(int value) {
|
||||
this.jFile.addProperty("offset", value);
|
||||
}
|
||||
|
||||
public void setPermission(String value) {
|
||||
this.jFile.addProperty("permission", value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package com.mitac.cell.io;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.mitac.cell.internet.http.McHttpClient;
|
||||
import com.mitac.cell.internet.http.McResponse;
|
||||
import com.mitac.cell.utils.McStringUtils;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.RandomAccessFile;
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
public class McResource {
|
||||
public static void copyFileToResponse(ServletContext servletContext, HttpServletResponse response, McFile file, String fileName, long lastModified, String range, long checksum) {
|
||||
Integer to = -1;
|
||||
Integer from = -1;
|
||||
if (!Strings.isNullOrEmpty(range)) {
|
||||
range = range.substring(range.indexOf(61) + 1);
|
||||
if (range.indexOf(44) >= 0) {
|
||||
McResponse.sendError(response, 400, "Multiple ranges not supported.");
|
||||
return;
|
||||
}
|
||||
|
||||
boolean isRangeOk = true;
|
||||
if (range.indexOf(45) >= 0) {
|
||||
String[] tokens = range.split("-");
|
||||
if (tokens.length > 0) {
|
||||
if (Strings.isNullOrEmpty(tokens[0])) {
|
||||
to = (int)file.length() - 1;
|
||||
from = to - Integer.valueOf(tokens[1]) + 1;
|
||||
} else {
|
||||
from = Integer.valueOf(tokens[0]);
|
||||
if (tokens.length > 1) {
|
||||
if (Strings.isNullOrEmpty(tokens[1])) {
|
||||
to = (int)file.length() - 1;
|
||||
} else {
|
||||
to = Integer.valueOf(tokens[1]);
|
||||
}
|
||||
} else {
|
||||
to = (int)file.length() - 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
isRangeOk = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isRangeOk) {
|
||||
McResponse.sendError(response, 400, "Range is invalid.");
|
||||
return;
|
||||
}
|
||||
|
||||
response.addHeader("Accept-Ranges", "bytes");
|
||||
}
|
||||
|
||||
response.addHeader("ETag", String.valueOf(checksum));
|
||||
response.setDateHeader("Last-Modified", lastModified);
|
||||
copyFileToResponse(servletContext, response, file, fileName, from, to);
|
||||
}
|
||||
|
||||
public static void copyFileToResponse(ServletContext servletContext, HttpServletResponse response, McFile file, String fileName, int from, int to) {
|
||||
if (McStringUtils.isNullOrEmpty(fileName)) {
|
||||
fileName = file.getName();
|
||||
}
|
||||
|
||||
if (file.exists()) {
|
||||
int fileSize = (int)file.length();
|
||||
int maxRange = fileSize > 0 ? fileSize - 1 : 0;
|
||||
response.setContentType(servletContext.getMimeType(fileName));
|
||||
if (to < 0 || to > maxRange) {
|
||||
to = maxRange;
|
||||
}
|
||||
|
||||
if (from < 0) {
|
||||
from = 0;
|
||||
} else if (from > maxRange || from > to) {
|
||||
try {
|
||||
response.sendError(416, "Requested Range Not Satisfiable.");
|
||||
} catch (IOException var9) {
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (from <= 0 && to >= maxRange) {
|
||||
response.setContentLength(fileSize);
|
||||
} else {
|
||||
response.setStatus(206);
|
||||
response.setHeader("Content-Range", String.format("bytes %d-%d/%d", from, to, fileSize));
|
||||
response.setContentLength(to - from + 1);
|
||||
response.setHeader("position", Long.toString((long)from));
|
||||
}
|
||||
|
||||
response.setHeader("Content-Disposition", McHttpClient.toContentDisposition(fileName));
|
||||
copyToResponse(servletContext, response, file, from, to);
|
||||
} else {
|
||||
try {
|
||||
response.sendError(404, "File not exists.");
|
||||
} catch (IOException var10) {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void copyToResponse(ServletContext servletContext, HttpServletResponse response, InputStream is) {
|
||||
try {
|
||||
ByteStreams.copy(is, response.getOutputStream());
|
||||
response.flushBuffer();
|
||||
is.close();
|
||||
} catch (IOException var6) {
|
||||
try {
|
||||
response.sendError(404, "Inputstream not work.");
|
||||
} catch (IOException var5) {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void copyToResponse(ServletContext servletContext, HttpServletResponse response, File file, int from, int to) {
|
||||
try {
|
||||
if (file.exists()) {
|
||||
RandomAccessFile raFile = new RandomAccessFile(file, "r");
|
||||
BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());
|
||||
if (from > 0) {
|
||||
raFile.seek((long)from);
|
||||
}
|
||||
|
||||
if (to < 0) {
|
||||
to = (int)raFile.length() - 1;
|
||||
}
|
||||
|
||||
int length = 9863168;
|
||||
byte[] buffer = new byte[length];
|
||||
|
||||
int read;
|
||||
for(read = -1; from < to && (read = raFile.read(buffer, 0, length)) > 0; from += read) {
|
||||
output.write(buffer, 0, read);
|
||||
}
|
||||
|
||||
raFile.close();
|
||||
response.flushBuffer();
|
||||
output.close();
|
||||
} else {
|
||||
response.sendError(404, "File not exists.");
|
||||
}
|
||||
} catch (Exception var10) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void copyToResponse(HttpServletResponse response, BufferedImage image) {
|
||||
try {
|
||||
response.setContentType("image/png");
|
||||
ImageIO.write(image, "png", response.getOutputStream());
|
||||
response.flushBuffer();
|
||||
} catch (IOException var3) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void copyFileToResponse(ServletContext servletContext, HttpServletResponse response, byte[] data, String fileName) {
|
||||
response.setContentType(servletContext.getMimeType(fileName));
|
||||
response.setHeader("Content-Disposition", McHttpClient.toContentDisposition(fileName));
|
||||
|
||||
try {
|
||||
IOUtils.write(data, response.getOutputStream());
|
||||
response.flushBuffer();
|
||||
} catch (IOException var5) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void setNoCacheControl(HttpServletResponse response) {
|
||||
response.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
|
||||
response.setHeader("Expires", "0");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.mitac.cell.io;
|
||||
|
||||
import com.google.common.io.BaseEncoding;
|
||||
import com.google.common.io.Resources;
|
||||
import com.mitac.cell.net.McNetUtils;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.InputStreamResource;
|
||||
import org.springframework.core.io.InputStreamSource;
|
||||
|
||||
public class McUrl {
|
||||
public static String getHost(HttpServletRequest request) {
|
||||
return request == null ? null : getHost(request.getRequestURL().toString());
|
||||
}
|
||||
|
||||
public static String getHost(String stringUrl) {
|
||||
try {
|
||||
URL url = new URL(stringUrl);
|
||||
return url == null ? null : McNetUtils.getHost(url.getHost());
|
||||
} catch (MalformedURLException var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] toBytes(String url) {
|
||||
try {
|
||||
return toBytes(new URL(url));
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] toBytes(URL url) {
|
||||
try {
|
||||
return Resources.toByteArray(url);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String toBase64Encoded(String url) {
|
||||
byte[] bytes = toBytes(url);
|
||||
return bytes == null ? null : BaseEncoding.base64().encode(bytes);
|
||||
}
|
||||
|
||||
public static String toBase64Encoded(URL url) {
|
||||
byte[] bytes = toBytes(url);
|
||||
return bytes == null ? null : BaseEncoding.base64().encode(bytes);
|
||||
}
|
||||
|
||||
public static InputStreamSource toInputStreamSource(String url) {
|
||||
byte[] bytes = toBytes(url);
|
||||
return bytes == null ? null : new ByteArrayResource(bytes);
|
||||
}
|
||||
|
||||
public static InputStream toInputStream(URL url) {
|
||||
try {
|
||||
return url.openStream();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static InputStreamResource toInputStreamResource(URL url) {
|
||||
if (url != null) {
|
||||
InputStream is = toInputStream(url);
|
||||
if (is != null) {
|
||||
return new InputStreamResource(is);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package com.mitac.cell.io;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.common.collect.Sets;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Set;
|
||||
import net.lingala.zip4j.ZipFile;
|
||||
import net.lingala.zip4j.exception.ZipException;
|
||||
import net.lingala.zip4j.model.ZipParameters;
|
||||
import net.lingala.zip4j.model.enums.CompressionLevel;
|
||||
import net.lingala.zip4j.model.enums.CompressionMethod;
|
||||
import net.lingala.zip4j.model.enums.EncryptionMethod;
|
||||
|
||||
public class McZipFile extends McFile {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private ZipFile zipFile;
|
||||
private ZipParameters zipParams;
|
||||
|
||||
public McZipFile(String zipFilePath) {
|
||||
super(zipFilePath);
|
||||
this.genZipFile();
|
||||
}
|
||||
|
||||
public McZipFile(File zipFile) {
|
||||
super(zipFile);
|
||||
this.genZipFile();
|
||||
}
|
||||
|
||||
public McZipFile(String folder, String name) {
|
||||
super(new McFile(folder), name);
|
||||
this.genZipFile();
|
||||
}
|
||||
|
||||
public McZipFile(File file, String name) {
|
||||
super(file, name);
|
||||
this.genZipFile();
|
||||
}
|
||||
|
||||
public boolean save() {
|
||||
return this.saveAs(this, true);
|
||||
}
|
||||
|
||||
public boolean save(boolean overwrite) {
|
||||
return this.saveAs(this, true);
|
||||
}
|
||||
|
||||
private void genZipFile() {
|
||||
this.zipFile = new ZipFile(this.getAbsolutePath());
|
||||
}
|
||||
|
||||
public boolean isZipped() {
|
||||
return this.zipFile.isValidZipFile();
|
||||
}
|
||||
|
||||
public boolean compressFolder(String folder, boolean includeFolder) {
|
||||
McFile dir = new McFile(folder);
|
||||
if (dir.exists() && !dir.isFile()) {
|
||||
if (includeFolder) {
|
||||
return this.compress(dir.getPath());
|
||||
} else {
|
||||
File[] files = dir.listFiles();
|
||||
String[] filePaths = new String[files.length];
|
||||
|
||||
for(int i = 0; i < files.length; ++i) {
|
||||
filePaths[i] = files[i].getPath();
|
||||
}
|
||||
|
||||
return this.compress(filePaths);
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean compress(File... filesToBeCompressed) {
|
||||
String[] paths = new String[filesToBeCompressed.length];
|
||||
|
||||
for(int i = 0; i < filesToBeCompressed.length; ++i) {
|
||||
paths[i] = filesToBeCompressed[i].getPath();
|
||||
}
|
||||
|
||||
return this.compress(paths);
|
||||
}
|
||||
|
||||
public boolean compress(String... filePathToBeCompressed) {
|
||||
return this.compress((String)null, true, false, filePathToBeCompressed);
|
||||
}
|
||||
|
||||
public boolean compress(String fileName, InputStream input) {
|
||||
return this.compress((String)null, true, false, fileName, input);
|
||||
}
|
||||
|
||||
public boolean compress(String password, boolean overwriteIfExists, boolean deleteOnSucceed, String... pathsToBeCompressed) {
|
||||
if (!this.exists() || !this.isDirectory() && overwriteIfExists && pathsToBeCompressed != null) {
|
||||
if (!this.getParentFile().exists()) {
|
||||
this.createParentDirs();
|
||||
}
|
||||
|
||||
try {
|
||||
Set<String> paths = Sets.newHashSet(pathsToBeCompressed);
|
||||
boolean hasPassword = Strings.isNullOrEmpty(password);
|
||||
if (hasPassword) {
|
||||
this.zipFile.setPassword(password.toCharArray());
|
||||
}
|
||||
|
||||
this.zipParams = this.getZipParams(hasPassword);
|
||||
|
||||
for(String path : paths) {
|
||||
McFile file = new McFile(path);
|
||||
if (file.exists()) {
|
||||
if (file.isFile()) {
|
||||
this.zipFile.addFile(file, this.zipParams);
|
||||
} else {
|
||||
this.zipFile.addFolder(file, this.zipParams);
|
||||
}
|
||||
|
||||
if (deleteOnSucceed) {
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (ZipException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean compress(String password, boolean overwriteIfExists, boolean deleteOnSucceed, String fileName, InputStream input) {
|
||||
if (input != null && !Strings.isNullOrEmpty(fileName)) {
|
||||
try {
|
||||
boolean hasPassword = Strings.isNullOrEmpty(password);
|
||||
if (hasPassword) {
|
||||
this.zipFile.setPassword(password.toCharArray());
|
||||
}
|
||||
|
||||
this.zipParams = this.getZipParams(hasPassword);
|
||||
this.zipParams.setFileNameInZip(fileName);
|
||||
this.zipFile.addStream(input, this.zipParams);
|
||||
input.close();
|
||||
return true;
|
||||
} catch (ZipException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean compressAs(File file, String name) {
|
||||
if (file != null && file.exists()) {
|
||||
try {
|
||||
this.zipParams = this.getZipParams(false);
|
||||
this.zipParams.setFileNameInZip(Strings.isNullOrEmpty(name) ? file.getName() : name);
|
||||
this.zipFile.addFolder(file, this.zipParams);
|
||||
return true;
|
||||
} catch (ZipException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean extract(String extractTo) {
|
||||
return this.extract(extractTo, (String)null, false, false);
|
||||
}
|
||||
|
||||
public boolean extract(String extractTo, String password) {
|
||||
return this.extract(extractTo, password, false, false);
|
||||
}
|
||||
|
||||
public boolean extract(String extractTo, String password, boolean deleteOnExists, boolean deleteOnSuccess) {
|
||||
if (this.isDirectory()) {
|
||||
return false;
|
||||
} else {
|
||||
try {
|
||||
ZipFile zipFile = new ZipFile(this);
|
||||
if (zipFile.isEncrypted()) {
|
||||
if (Strings.isNullOrEmpty(password)) {
|
||||
zipFile.close();
|
||||
return false;
|
||||
}
|
||||
|
||||
zipFile.setPassword(password.toCharArray());
|
||||
}
|
||||
|
||||
McFile destFile = new McFile(extractTo);
|
||||
destFile.createParentDirs();
|
||||
if (destFile.exists() && deleteOnExists) {
|
||||
destFile.delete();
|
||||
}
|
||||
|
||||
zipFile.extractAll(extractTo);
|
||||
if (deleteOnSuccess) {
|
||||
this.delete();
|
||||
}
|
||||
|
||||
zipFile.close();
|
||||
} catch (IOException var7) {
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public ZipParameters getZipParams(int deflateLevel) {
|
||||
return this.getZipParams(this.getLevel(deflateLevel), false);
|
||||
}
|
||||
|
||||
public ZipParameters getZipParams(boolean hasPassword) {
|
||||
return this.getZipParams(CompressionLevel.NORMAL, hasPassword);
|
||||
}
|
||||
|
||||
public ZipParameters getZipParams(CompressionLevel deflateLevel, boolean hasPassword) {
|
||||
ZipParameters zParams = new ZipParameters();
|
||||
zParams.setCompressionMethod(CompressionMethod.DEFLATE);
|
||||
zParams.setCompressionLevel(deflateLevel);
|
||||
if (hasPassword) {
|
||||
zParams.setEncryptFiles(true);
|
||||
zParams.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD);
|
||||
}
|
||||
|
||||
return zParams;
|
||||
}
|
||||
|
||||
private CompressionLevel getLevel(int level) {
|
||||
for(CompressionLevel compressionLevel : CompressionLevel.values()) {
|
||||
if (compressionLevel.getLevel() == level) {
|
||||
return compressionLevel;
|
||||
}
|
||||
}
|
||||
|
||||
return CompressionLevel.NORMAL;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package com.mitac.cell.io;
|
||||
|
||||
import com.mitac.cell.utils.McStringUtils;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.transform.Transformer;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
public class Vector2Svg {
|
||||
private final InputStream source;
|
||||
|
||||
public Vector2Svg(String source) throws FileNotFoundException {
|
||||
this(new File(source));
|
||||
}
|
||||
|
||||
public Vector2Svg(File source) throws FileNotFoundException {
|
||||
this((InputStream)(new FileInputStream(source)));
|
||||
}
|
||||
|
||||
public Vector2Svg(byte[] data) {
|
||||
this((InputStream)(new ByteArrayInputStream(data)));
|
||||
}
|
||||
|
||||
public Vector2Svg(InputStream source) {
|
||||
this.source = source;
|
||||
}
|
||||
|
||||
public byte[] toSvgBytes() {
|
||||
try {
|
||||
AndroidVectorDrawable drawable = this.getDrawable();
|
||||
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
|
||||
Element svg = doc.createElement("svg");
|
||||
svg.setAttribute("viewBox", String.format("0 0 %.1f %.1f", drawable.width, drawable.height));
|
||||
|
||||
for(Group group : drawable.groups) {
|
||||
Element g = doc.createElement("g");
|
||||
|
||||
for(VectorPath path : group.paths) {
|
||||
Element child = doc.createElement("path");
|
||||
if (path.fillColor != null) {
|
||||
child.setAttribute("fill", path.fillColor);
|
||||
}
|
||||
|
||||
child.setAttribute("d", path.pathData);
|
||||
g.appendChild(child);
|
||||
}
|
||||
|
||||
svg.appendChild(g);
|
||||
}
|
||||
|
||||
for(VectorPath path : drawable.paths) {
|
||||
Element child = doc.createElement("path");
|
||||
if (path.fillColor != null) {
|
||||
child.setAttribute("fill", path.fillColor);
|
||||
}
|
||||
|
||||
child.setAttribute("d", path.pathData);
|
||||
svg.appendChild(child);
|
||||
}
|
||||
|
||||
doc.appendChild(svg);
|
||||
TransformerFactory transformerFactory = TransformerFactory.newInstance();
|
||||
Transformer transformer = transformerFactory.newTransformer();
|
||||
DOMSource source = new DOMSource(doc);
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
StreamResult result = new StreamResult(output);
|
||||
transformer.setOutputProperty("omit-xml-declaration", "yes");
|
||||
transformer.setOutputProperty("indent", "yes");
|
||||
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
|
||||
transformer.transform(source, result);
|
||||
return output.toByteArray();
|
||||
} catch (Exception var10) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private AndroidVectorDrawable getDrawable() throws ParserConfigurationException, IOException, SAXException {
|
||||
Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(this.source);
|
||||
xml.getDocumentElement().normalize();
|
||||
Node vector = xml.getElementsByTagName("vector").item(0);
|
||||
NamedNodeMap attributes = vector.getAttributes();
|
||||
NodeList children = vector.getChildNodes();
|
||||
double width = (double)0.0F;
|
||||
double height = (double)0.0F;
|
||||
|
||||
for(int i = 0; i < attributes.getLength(); ++i) {
|
||||
if (attributes.item(i).getNodeName().equals("android:viewportHeight")) {
|
||||
height = this.getDouble(attributes.item(i).getNodeValue());
|
||||
} else if (attributes.item(i).getNodeName().equals("android:viewportWidth")) {
|
||||
width = this.getDouble(attributes.item(i).getNodeValue());
|
||||
}
|
||||
}
|
||||
|
||||
List<VectorPath> paths = new ArrayList();
|
||||
List<Group> groups = new ArrayList();
|
||||
|
||||
for(int i = 0; i < children.getLength(); ++i) {
|
||||
Node item = children.item(i);
|
||||
if (!item.getNodeName().equals("group")) {
|
||||
VectorPath path = this.getVectorPathFromNode(item);
|
||||
if (path != null) {
|
||||
paths.add(path);
|
||||
}
|
||||
} else {
|
||||
List<VectorPath> groupPaths = new ArrayList();
|
||||
|
||||
for(int j = 0; j < item.getChildNodes().getLength(); ++j) {
|
||||
VectorPath path = this.getVectorPathFromNode(item.getChildNodes().item(j));
|
||||
if (path != null) {
|
||||
groupPaths.add(path);
|
||||
}
|
||||
}
|
||||
|
||||
if (!groupPaths.isEmpty()) {
|
||||
groups.add(new Group(groupPaths));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new AndroidVectorDrawable(paths, groups, width, height);
|
||||
}
|
||||
|
||||
private Double getDouble(String nodeValue) {
|
||||
if (nodeValue.startsWith("{")) {
|
||||
String[] token = nodeValue.split(":");
|
||||
Double d1 = Double.parseDouble(token[0].substring(1));
|
||||
Double d2 = Double.parseDouble(token[1].substring(0, token[1].length() - 1)) / (double)1024.0F / (double)1024.0F;
|
||||
return d2 / d1;
|
||||
} else {
|
||||
return Double.parseDouble(nodeValue);
|
||||
}
|
||||
}
|
||||
|
||||
private VectorPath getVectorPathFromNode(Node item) {
|
||||
if (item.getNodeName().equals("path")) {
|
||||
String pathData = null;
|
||||
String fillColor = null;
|
||||
|
||||
for(int j = 0; j < item.getAttributes().getLength(); ++j) {
|
||||
Node node = item.getAttributes().item(j);
|
||||
String name = node.getNodeName();
|
||||
String value = node.getNodeValue();
|
||||
if (name.equals("android:pathData")) {
|
||||
pathData = this.normalizedPathData(value);
|
||||
} else if (name.equals("android:fillColor")) {
|
||||
try {
|
||||
McStringUtils.toBytes(value);
|
||||
fillColor = "#" + value;
|
||||
} catch (Exception var9) {
|
||||
fillColor = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (pathData != null) {
|
||||
return new VectorPath(pathData, fillColor);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private String normalizedPathData(String value) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for(int i = 0; i < value.length(); ++i) {
|
||||
char ch = value.charAt(i);
|
||||
if (ch == '.' && (i - 1 < 0 || !Character.isDigit(value.charAt(i - 1)))) {
|
||||
sb.append('0');
|
||||
}
|
||||
|
||||
sb.append(ch);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private class VectorPath {
|
||||
private String pathData;
|
||||
private String fillColor;
|
||||
|
||||
private VectorPath(String pathData, String fillColor) {
|
||||
this.pathData = pathData;
|
||||
this.fillColor = fillColor;
|
||||
}
|
||||
}
|
||||
|
||||
private class Group {
|
||||
private final List paths;
|
||||
|
||||
public Group(List paths) {
|
||||
this.paths = paths;
|
||||
}
|
||||
}
|
||||
|
||||
private class AndroidVectorDrawable {
|
||||
private final List paths;
|
||||
private final List groups;
|
||||
private final double height;
|
||||
private final double width;
|
||||
|
||||
private AndroidVectorDrawable(List paths, List groups, double width, double height) {
|
||||
this.paths = paths;
|
||||
this.groups = groups;
|
||||
this.height = height;
|
||||
this.width = width;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.mitac.cell.map;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mitac.cell.utils.McJsonUtils;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
public class GeoCode {
|
||||
public static String getAddress(String apiKey, String latitude, String longitude) {
|
||||
try {
|
||||
String url = String.format("https://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s&key=%s", latitude, longitude, apiKey);
|
||||
OkHttpClient client = new OkHttpClient();
|
||||
Request request = (new Request.Builder()).url(url).build();
|
||||
Response responses = client.newCall(request).execute();
|
||||
JsonObject jResult = (JsonObject)McJsonUtils.toJsonElement(responses.body().byteStream());
|
||||
JsonObject jInfo = jResult.getAsJsonObject("info");
|
||||
String result = null;
|
||||
if (jInfo.get("statuscode").getAsInt() == 0) {
|
||||
JsonArray jLocations = jResult.getAsJsonArray("locations");
|
||||
if (jLocations.size() > 0) {
|
||||
JsonObject jLocation = jLocations.get(0).getAsJsonObject();
|
||||
String.join(", ", jLocation.get("street").getAsString());
|
||||
result = jLocation.toString();
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (Exception var12) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package com.mitac.cell.must;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonIOException;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import com.mitac.cell.data.McXml;
|
||||
import com.mitac.cell.io.McEncryptedFileDrive;
|
||||
import com.mitac.cell.io.McFile;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.util.LinkedHashMap;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import org.xml.sax.SAXException;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
|
||||
public class MustBuilder {
|
||||
private static byte[] DEFAULT_KEY = "MUST@mitac".getBytes();
|
||||
private static String DEFAULT_SRC_FILE = "must.must";
|
||||
private String format;
|
||||
private McFile sourceFile;
|
||||
private McFile outputFile;
|
||||
private JsonObject mustObject;
|
||||
|
||||
public MustBuilder() {
|
||||
}
|
||||
|
||||
public MustBuilder(JsonObject mustObject) {
|
||||
this.mustObject = mustObject;
|
||||
}
|
||||
|
||||
public McFile getSource() {
|
||||
return this.sourceFile;
|
||||
}
|
||||
|
||||
public String getSourcePath() {
|
||||
return this.sourceFile.getAbsolutePath();
|
||||
}
|
||||
|
||||
public boolean setSource(String path) {
|
||||
if (Strings.isNullOrEmpty(path)) {
|
||||
this.sourceFile = new McFile(".", DEFAULT_SRC_FILE);
|
||||
} else {
|
||||
this.sourceFile = new McFile(path);
|
||||
if (this.sourceFile.exists() && this.sourceFile.isDirectory()) {
|
||||
this.sourceFile = new McFile(path, DEFAULT_SRC_FILE);
|
||||
}
|
||||
}
|
||||
|
||||
return this.isSourceExists();
|
||||
}
|
||||
|
||||
public boolean isSourceExists() {
|
||||
return this.sourceFile != null && this.sourceFile.exists();
|
||||
}
|
||||
|
||||
public String getFormat() {
|
||||
if (Strings.isNullOrEmpty(this.format)) {
|
||||
String ext = this.sourceFile.getExtension();
|
||||
if (Strings.isNullOrEmpty(ext)) {
|
||||
this.format = "xml";
|
||||
} else {
|
||||
ext = ext.toLowerCase();
|
||||
if (!ext.equals("json") && !ext.contentEquals("yaml")) {
|
||||
this.format = "xml";
|
||||
} else {
|
||||
this.format = ext;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return this.format;
|
||||
}
|
||||
|
||||
public boolean setFormat(String format) {
|
||||
if (!format.equals("xml") && !format.equals("json") && !format.equals("yaml")) {
|
||||
return false;
|
||||
} else {
|
||||
this.format = format.trim().toLowerCase();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public McFile getOutput() {
|
||||
return this.outputFile;
|
||||
}
|
||||
|
||||
public String getOutputPath() {
|
||||
return this.outputFile.getAbsolutePath();
|
||||
}
|
||||
|
||||
public void setOutput(String path) {
|
||||
if (Strings.isNullOrEmpty(path)) {
|
||||
this.outputFile = new McFile(this.sourceFile.getParent(), this.sourceFile.getNameWithoutExtension() + ".mst");
|
||||
} else {
|
||||
this.outputFile = new McFile(path);
|
||||
if (this.outputFile.exists() && this.outputFile.isDirectory()) {
|
||||
this.outputFile = new McFile(path, this.sourceFile.getNameWithoutExtension() + ".mst");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public boolean build() throws IOException, JsonIOException, JsonSyntaxException, ParserConfigurationException, SAXException {
|
||||
this.mustObject = null;
|
||||
String format = this.getFormat();
|
||||
if (format.equals("xml")) {
|
||||
McXml xml = new McXml();
|
||||
this.mustObject = xml.load((File)this.sourceFile);
|
||||
} else if (format.equals("json")) {
|
||||
Reader reader = new FileReader(this.sourceFile);
|
||||
JsonElement jElement = JsonParser.parseReader(reader);
|
||||
if (jElement.isJsonObject()) {
|
||||
this.mustObject = jElement.getAsJsonObject();
|
||||
}
|
||||
} else if (format.equals("yaml")) {
|
||||
Reader reader = new FileReader(this.sourceFile);
|
||||
LinkedHashMap<String, Object> map = (LinkedHashMap)(new Yaml()).load(reader);
|
||||
JsonElement jElement = (new GsonBuilder()).create().toJsonTree(map);
|
||||
if (jElement.isJsonObject()) {
|
||||
this.mustObject = jElement.getAsJsonObject();
|
||||
}
|
||||
}
|
||||
|
||||
return this.hasContents();
|
||||
}
|
||||
|
||||
public boolean save(String destPath) {
|
||||
this.setOutput(destPath);
|
||||
McFile destFile = this.outputFile;
|
||||
McEncryptedFileDrive drive = new McEncryptedFileDrive(destFile);
|
||||
drive.enableInstantSave(false);
|
||||
drive.setKey(DEFAULT_KEY);
|
||||
drive.addFile("/must.must", this.mustObject.toString().getBytes());
|
||||
drive.save();
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean save() {
|
||||
if (this.outputFile == null) {
|
||||
this.setOutput((String)null);
|
||||
}
|
||||
|
||||
McFile destFile = this.outputFile;
|
||||
McEncryptedFileDrive drive = new McEncryptedFileDrive(destFile);
|
||||
drive.enableInstantSave(false);
|
||||
drive.setKey(DEFAULT_KEY);
|
||||
drive.addFile("/must.must", this.mustObject.toString().getBytes());
|
||||
drive.save();
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean hasContents() {
|
||||
return this.mustObject != null && this.mustObject.size() > 0;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return this.hasContents() ? (new GsonBuilder()).setPrettyPrinting().create().toJson(this.mustObject) : "No configurations.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package com.mitac.cell.net;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.common.io.BaseEncoding;
|
||||
import com.mitac.cell.utils.McNumberUtils;
|
||||
import com.mitac.cell.utils.McStringUtils;
|
||||
import java.io.IOException;
|
||||
import java.net.Inet6Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class McNetUtils {
|
||||
private static final String[] netMaskArray = new String[]{"255.255.255.255", "255.255.255.254", "255.255.255.252", "255.255.255.248", "255.255.255.240", "255.255.255.224", "255.255.255.192", "255.255.255.128", "255.255.255.0", "255.255.254.0", "255.255.252.0", "255.255.248.0", "255.255.240.0", "255.255.224.0", "255.255.192.0", "255.255.128.0", "255.255.0.0", "255.254.0.0", "255.252.0.0", "255.248.0.0", "255.240.0.0", "255.224.0.0", "255.192.0.0", "255.128.0.0", "255.0.0.0", "254.0.0.0", "252.0.0.0", "248.0.0.0", "240.0.0.0", "224.0.0.0", "192.0.0.0", "128.0.0.0", "0.0.0.0"};
|
||||
private static final Pattern IPv4RegexPattern = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.) {3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
|
||||
|
||||
public static int toInt(String hostName) {
|
||||
try {
|
||||
InetAddress inetAddress = InetAddress.getByName(hostName);
|
||||
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||
buffer.put(inetAddress.getAddress());
|
||||
buffer.position(0);
|
||||
return buffer.getInt();
|
||||
} catch (UnknownHostException e) {
|
||||
e.printStackTrace();
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
public static InetAddress toAddress(int ipAddress) {
|
||||
byte[] byteArray = McNumberUtils.toBytes(4, false, ipAddress);
|
||||
|
||||
try {
|
||||
return InetAddress.getByAddress(byteArray);
|
||||
} catch (UnknownHostException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static int toPrefixLength(String netMask) {
|
||||
int prefixLength = 0;
|
||||
|
||||
for(int i = 0; i < netMaskArray.length; ++i) {
|
||||
if (netMaskArray[i].equals(netMask)) {
|
||||
prefixLength = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return prefixLength;
|
||||
}
|
||||
|
||||
public static String toNetMask(int prefixLength) {
|
||||
return netMaskArray[prefixLength];
|
||||
}
|
||||
|
||||
public static long ipToLong(String ipAddress) {
|
||||
try {
|
||||
return ipToLong(InetAddress.getByName(ipAddress));
|
||||
} catch (UnknownHostException e) {
|
||||
e.printStackTrace();
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
public static long ipToLong(InetAddress inetAddr) {
|
||||
byte[] rawIp = inetAddr.getAddress();
|
||||
return (((long)rawIp[0] & 255L) << 24) + (((long)rawIp[1] & 255L) << 16) + (((long)rawIp[2] & 255L) << 8) + ((long)rawIp[3] & 255L);
|
||||
}
|
||||
|
||||
public static String longToIp(long i) {
|
||||
return (i >> 24 & 255L) + "." + (i >> 16 & 255L) + "." + (i >> 8 & 255L) + "." + (i & 255L);
|
||||
}
|
||||
|
||||
public static String hostName() {
|
||||
try {
|
||||
String hostName = InetAddress.getLocalHost().getHostName();
|
||||
if (Strings.isNullOrEmpty(hostName)) {
|
||||
hostName = System.getenv(System.getProperty("os.name").toLowerCase().startsWith("win") ? "COMPUTERNAME" : "HOSTNAME");
|
||||
}
|
||||
|
||||
if (Strings.isNullOrEmpty(hostName)) {
|
||||
Scanner s = (new Scanner(Runtime.getRuntime().exec("hostname").getInputStream())).useDelimiter("\\n");
|
||||
hostName = s.hasNext() ? s.next() : "";
|
||||
}
|
||||
|
||||
return hostName;
|
||||
} catch (UnknownHostException var2) {
|
||||
} catch (IOException var3) {
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static boolean isVmMacAddress(byte[] mac) {
|
||||
if (null == mac) {
|
||||
return true;
|
||||
} else if (mac.length != 6) {
|
||||
return true;
|
||||
} else {
|
||||
byte[][] invalidMacs = new byte[][]{{0, 5, 105}, {0, 28, 20}, {0, 12, 41}, {0, 80, 86}, {8, 0, 39}, {10, 0, 39}, {0, 3, -1}, {0, 21, 93}};
|
||||
|
||||
for(byte[] invalid : invalidMacs) {
|
||||
if (invalid[0] == mac[0] && invalid[1] == mac[1] && invalid[2] == mac[2]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static String toMacAddressString(byte[] macAddrBytes) {
|
||||
return BaseEncoding.base16().withSeparator(":", 2).encode(macAddrBytes);
|
||||
}
|
||||
|
||||
public static List macAddress() {
|
||||
try {
|
||||
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
|
||||
List<byte[]> macList = new ArrayList();
|
||||
|
||||
while(netInterfaces.hasMoreElements()) {
|
||||
NetworkInterface netInterface = (NetworkInterface)netInterfaces.nextElement();
|
||||
String displayName = netInterface.getDisplayName();
|
||||
if (!McStringUtils.containsIgnoreCase(displayName, "virtual adapter") && !McStringUtils.containsIgnoreCase(displayName, "bluetooth")) {
|
||||
byte[] macAddr = netInterface.getHardwareAddress();
|
||||
if (macAddr != null && netInterface.isUp() && !netInterface.isLoopback() && macAddr.length == 6) {
|
||||
macList.add(macAddr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return macList;
|
||||
} catch (SocketException var5) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getHost(String hostName) {
|
||||
if (!Strings.isNullOrEmpty(hostName)) {
|
||||
hostName = hostName.trim();
|
||||
if (Strings.isNullOrEmpty(hostName)) {
|
||||
return null;
|
||||
} else {
|
||||
int indexPort = hostName.indexOf(":");
|
||||
return indexPort >= 0 ? hostName.substring(0, hostName.indexOf(":")) : hostName;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] getMacAddr() {
|
||||
List<byte[]> macAddresses = macAddress();
|
||||
return macAddresses != null && macAddresses.size() > 0 ? (byte[])macAddress().get(0) : null;
|
||||
}
|
||||
|
||||
public static String ipAddress(InetAddress inetAddress) {
|
||||
if (inetAddress == null) {
|
||||
return null;
|
||||
} else {
|
||||
String address = inetAddress.toString();
|
||||
return Strings.isNullOrEmpty(address) ? null : address.split("/")[1];
|
||||
}
|
||||
}
|
||||
|
||||
public static String getIpAddress() {
|
||||
String ip = null;
|
||||
|
||||
try {
|
||||
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
|
||||
|
||||
while(interfaces.hasMoreElements()) {
|
||||
NetworkInterface iface = (NetworkInterface)interfaces.nextElement();
|
||||
if (!iface.isLoopback() && iface.isUp()) {
|
||||
Enumeration<InetAddress> addresses = iface.getInetAddresses();
|
||||
|
||||
while(addresses.hasMoreElements()) {
|
||||
InetAddress addr = (InetAddress)addresses.nextElement();
|
||||
if (!(addr instanceof Inet6Address)) {
|
||||
ip = addr.getHostAddress();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ip;
|
||||
} catch (SocketException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean validate(String ip) {
|
||||
return IPv4RegexPattern.matcher(ip).matches();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.mitac.cell.net;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Uri {
|
||||
private URI uri;
|
||||
|
||||
public Uri(String uri) {
|
||||
this.uri = URI.create(uri);
|
||||
}
|
||||
|
||||
public String[] paths() {
|
||||
String path = this.uri.getPath();
|
||||
return Strings.isNullOrEmpty(path) ? new String[0] : this.uri.getPath().split("/");
|
||||
}
|
||||
|
||||
public List getPathSegments() {
|
||||
ArrayList<String> list = new ArrayList();
|
||||
|
||||
for(String path : this.paths()) {
|
||||
list.add(path);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public static Uri parse(String uri) {
|
||||
return new Uri(uri);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.mitac.cell.security;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.common.io.BaseEncoding;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
public class McBase64 {
|
||||
public static String toBase64(String source) {
|
||||
return Strings.isNullOrEmpty(source) ? null : toBase64(source.getBytes());
|
||||
}
|
||||
|
||||
public static String toBase64(byte[] bytes) {
|
||||
return bytes == null ? null : BaseEncoding.base64().encode(bytes);
|
||||
}
|
||||
|
||||
public static byte[] fromBase64(String source) {
|
||||
return Strings.isNullOrEmpty(source) ? null : BaseEncoding.base64().decode(source);
|
||||
}
|
||||
|
||||
public static String fromBase64ToString(String source) {
|
||||
if (Strings.isNullOrEmpty(source)) {
|
||||
return null;
|
||||
} else {
|
||||
try {
|
||||
return new String(fromBase64(source), "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,511 @@
|
||||
package com.mitac.cell.security;
|
||||
|
||||
import com.mitac.cell.security.cipher.McRc4;
|
||||
import com.mitac.cell.utils.McConvert;
|
||||
import com.mitac.cell.utils.McNumberUtils;
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.Key;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.Provider;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.spec.InvalidKeySpecException;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
import javax.crypto.BadPaddingException;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.IllegalBlockSizeException;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.NoSuchPaddingException;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.DESKeySpec;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.PBEKeySpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
|
||||
public class McCrypto {
|
||||
public static final int ENCRYPT_MODE = 1;
|
||||
public static final int DECRYPT_MODE = 2;
|
||||
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
|
||||
private static final String PBE_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC";
|
||||
private static final String RANDOM_ALGORITHM = "SHA1PRNG";
|
||||
private int mKeyLength;
|
||||
private String mAlgorithm;
|
||||
private byte[] mKey;
|
||||
private byte[] mSource;
|
||||
private byte[] mTarget;
|
||||
private byte[] mInitVector;
|
||||
private byte[] mPrivateKey;
|
||||
private int mCipherMode;
|
||||
private byte[] mFileHeader;
|
||||
|
||||
public McCrypto() {
|
||||
this(1, "AES/CBC/PKCS5Padding", 128);
|
||||
}
|
||||
|
||||
public McCrypto(int cipherMode) {
|
||||
this(cipherMode, "AES/CBC/PKCS5Padding", 128);
|
||||
}
|
||||
|
||||
public McCrypto(int cipherMode, String algorithm) {
|
||||
this(cipherMode, algorithm, 128);
|
||||
}
|
||||
|
||||
public McCrypto(int cipherMode, String algorithm, int keyLength) {
|
||||
this.mCipherMode = 1;
|
||||
this.mCipherMode = cipherMode;
|
||||
this.mKeyLength = keyLength;
|
||||
this.mAlgorithm = algorithm;
|
||||
}
|
||||
|
||||
public void setFileHeader(byte[] header) {
|
||||
this.mFileHeader = header;
|
||||
}
|
||||
|
||||
public void setFileHeader(String header) {
|
||||
this.setFileHeader(header.getBytes());
|
||||
}
|
||||
|
||||
public byte[] getFileHeader() {
|
||||
return this.mFileHeader;
|
||||
}
|
||||
|
||||
public void setKey(String key) {
|
||||
this.mKey = key.getBytes();
|
||||
}
|
||||
|
||||
public void setKey(byte[] key) {
|
||||
this.mKey = key;
|
||||
}
|
||||
|
||||
public void setSource(byte[] source) {
|
||||
if (this.mCipherMode == 2) {
|
||||
this.setSource((InputStream)(new ByteArrayInputStream(source)));
|
||||
} else {
|
||||
this.mSource = source;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void setSource(String source) {
|
||||
this.setSource(source.getBytes());
|
||||
}
|
||||
|
||||
public void setSourcePath(String sourcePath) {
|
||||
try {
|
||||
this.setSource((InputStream)(new FileInputStream(sourcePath)));
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void setSource(InputStream sourceStream) {
|
||||
try {
|
||||
if (this.mCipherMode == 2) {
|
||||
byte[] data = new byte[4];
|
||||
sourceStream.read(data, 0, 4);
|
||||
if (data[0] != 109 || data[1] != 99) {
|
||||
return;
|
||||
}
|
||||
|
||||
sourceStream.read(data, 0, 4);
|
||||
int fileHeaderLength = McConvert.toInt(true, data);
|
||||
if (fileHeaderLength > 0) {
|
||||
this.mFileHeader = new byte[fileHeaderLength];
|
||||
sourceStream.read(this.mFileHeader, 0, fileHeaderLength);
|
||||
}
|
||||
|
||||
GZIPInputStream gzipInputStream = new GZIPInputStream(new BufferedInputStream(sourceStream));
|
||||
byte[] lenData = new byte[4];
|
||||
gzipInputStream.read(lenData);
|
||||
int pkLen = McConvert.toInt(true, lenData);
|
||||
if (pkLen > 0) {
|
||||
this.mPrivateKey = new byte[pkLen];
|
||||
}
|
||||
|
||||
gzipInputStream.read(lenData);
|
||||
int ivLen = McConvert.toInt(true, lenData);
|
||||
if (ivLen > 0) {
|
||||
this.mInitVector = new byte[ivLen];
|
||||
}
|
||||
|
||||
if (pkLen > 0) {
|
||||
gzipInputStream.read(this.mPrivateKey);
|
||||
}
|
||||
|
||||
if (ivLen > 0) {
|
||||
gzipInputStream.read(this.mInitVector);
|
||||
}
|
||||
|
||||
gzipInputStream.read(lenData);
|
||||
int dataLen = McConvert.toInt(true, lenData);
|
||||
if (dataLen > 0) {
|
||||
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
|
||||
data = new byte[512];
|
||||
|
||||
int n;
|
||||
while((n = gzipInputStream.read(data)) != -1) {
|
||||
byteStream.write(data, 0, n);
|
||||
}
|
||||
|
||||
this.mSource = byteStream.toByteArray();
|
||||
byteStream.close();
|
||||
}
|
||||
|
||||
gzipInputStream.close();
|
||||
} else {
|
||||
int size = sourceStream.available();
|
||||
this.mSource = new byte[size];
|
||||
sourceStream.read(this.mSource);
|
||||
sourceStream.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void save(String destinationPath) {
|
||||
try {
|
||||
FileOutputStream stream = new FileOutputStream(destinationPath);
|
||||
stream.write(this.getBytes());
|
||||
stream.flush();
|
||||
stream.close();
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private byte[] getEncryptedDataHeader() {
|
||||
int size = 12;
|
||||
int pkLen = 0;
|
||||
int ivLen = 0;
|
||||
if (this.mPrivateKey != null) {
|
||||
pkLen = this.mPrivateKey.length;
|
||||
}
|
||||
|
||||
if (this.mInitVector != null) {
|
||||
ivLen = this.mInitVector.length;
|
||||
}
|
||||
|
||||
byte[] header = new byte[size + pkLen + ivLen];
|
||||
size = 0;
|
||||
byte[] lenData = McNumberUtils.toBytes(4, true, pkLen);
|
||||
|
||||
for(byte b : lenData) {
|
||||
header[size++] = b;
|
||||
}
|
||||
|
||||
lenData = McNumberUtils.toBytes(4, true, ivLen);
|
||||
|
||||
for(byte b : lenData) {
|
||||
header[size++] = b;
|
||||
}
|
||||
|
||||
if (pkLen > 0) {
|
||||
for(byte b : this.mPrivateKey) {
|
||||
header[size++] = b;
|
||||
}
|
||||
}
|
||||
|
||||
if (ivLen > 0) {
|
||||
for(byte b : this.mInitVector) {
|
||||
header[size++] = b;
|
||||
}
|
||||
}
|
||||
|
||||
lenData = McNumberUtils.toBytes(4, true, this.mTarget.length);
|
||||
|
||||
for(byte b : lenData) {
|
||||
header[size++] = b;
|
||||
}
|
||||
|
||||
return header;
|
||||
}
|
||||
|
||||
public InputStream getInputStream() {
|
||||
return this.mTarget != null ? new ByteArrayInputStream(this.mTarget) : null;
|
||||
}
|
||||
|
||||
public byte[] getRaw() {
|
||||
return this.mTarget;
|
||||
}
|
||||
|
||||
public byte[] getBytes() {
|
||||
if (this.mCipherMode == 1) {
|
||||
try {
|
||||
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
|
||||
byteStream.write(new byte[]{109, 99, 3, 1});
|
||||
if (this.mFileHeader != null) {
|
||||
byteStream.write(McNumberUtils.toBytes(4, true, this.mFileHeader.length));
|
||||
byteStream.write(this.mFileHeader);
|
||||
} else {
|
||||
byteStream.write(new byte[4]);
|
||||
}
|
||||
|
||||
byteStream.size();
|
||||
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteStream);
|
||||
gzipOutputStream.write(this.getEncryptedDataHeader());
|
||||
gzipOutputStream.write(this.mTarget);
|
||||
gzipOutputStream.flush();
|
||||
gzipOutputStream.close();
|
||||
return byteStream.toByteArray();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return this.mTarget;
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] getInitVector() {
|
||||
return this.mInitVector;
|
||||
}
|
||||
|
||||
public byte[] getPrivateKey() {
|
||||
return this.mPrivateKey;
|
||||
}
|
||||
|
||||
public byte[] run() {
|
||||
return this.mCipherMode == 1 ? this.encrypt() : this.decrypt();
|
||||
}
|
||||
|
||||
private byte[] encrypt() {
|
||||
this.mTarget = null;
|
||||
if (this.mAlgorithm.toUpperCase().equals("RC4")) {
|
||||
this.mTarget = this.doByRc4();
|
||||
} else {
|
||||
this.mTarget = this.doByCipher(1);
|
||||
}
|
||||
|
||||
return this.mTarget;
|
||||
}
|
||||
|
||||
private byte[] decrypt() {
|
||||
this.mTarget = null;
|
||||
if (this.mAlgorithm.toUpperCase().equals("RC4")) {
|
||||
this.mTarget = this.doByRc4();
|
||||
} else {
|
||||
this.mTarget = this.doByCipher(2);
|
||||
}
|
||||
|
||||
return this.mTarget;
|
||||
}
|
||||
|
||||
private void initCipher(Cipher cipher) throws InvalidKeyException, InvalidAlgorithmParameterException {
|
||||
if (this.mCipherMode == 1 && !this.mAlgorithm.contains("ECB") && !this.mAlgorithm.contains("RSA")) {
|
||||
this.mInitVector = this.generateIvSpec();
|
||||
}
|
||||
|
||||
if (this.mAlgorithm.contains("AES")) {
|
||||
if (this.mAlgorithm.contains("ECB")) {
|
||||
cipher.init(this.mCipherMode, this.getAesKey(this.mKey, this.mKeyLength));
|
||||
} else {
|
||||
cipher.init(this.mCipherMode, this.getAesKey(this.mKey, this.mKeyLength), new IvParameterSpec(this.mInitVector));
|
||||
}
|
||||
} else if (this.mAlgorithm.contains("RSA")) {
|
||||
cipher.init(this.mCipherMode, this.mCipherMode == 1 ? this.getRsaPublicKey() : this.getRsaPrivateKey(this.mPrivateKey));
|
||||
} else if (this.mAlgorithm.contains("DESede")) {
|
||||
if (this.mAlgorithm.contains("ECB")) {
|
||||
cipher.init(this.mCipherMode, this.getDesedeKey(this.mKey));
|
||||
} else {
|
||||
cipher.init(this.mCipherMode, this.getDesedeKey(this.mKey), new IvParameterSpec(this.mInitVector));
|
||||
}
|
||||
} else if (this.mAlgorithm.contains("DES")) {
|
||||
if (this.mAlgorithm.contains("ECB")) {
|
||||
cipher.init(this.mCipherMode, this.getDesKey(this.mKey));
|
||||
} else {
|
||||
cipher.init(this.mCipherMode, this.getDesKey(this.mKey), new IvParameterSpec(this.mInitVector));
|
||||
}
|
||||
} else if (this.mAlgorithm.contains("Blowfish")) {
|
||||
if (this.mAlgorithm.contains("ECB")) {
|
||||
cipher.init(this.mCipherMode, this.getAesKey(this.mKey, this.mKeyLength));
|
||||
} else {
|
||||
cipher.init(this.mCipherMode, this.getAesKey(this.mKey, this.mKeyLength), new IvParameterSpec(this.mInitVector));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private byte[] generateIvSpec() {
|
||||
try {
|
||||
int count = 16;
|
||||
if (this.mAlgorithm.contains("DES")) {
|
||||
count = 8;
|
||||
}
|
||||
|
||||
byte[] iv = new byte[count];
|
||||
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
|
||||
random.nextBytes(iv);
|
||||
return iv;
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Key getAesKey(byte[] key, int keyLength) {
|
||||
byte[] SALT = encryptMessageByHmacMd5(key);
|
||||
int ITERATION_COUNT = SALT.length % 10 * 10;
|
||||
|
||||
try {
|
||||
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC");
|
||||
char[] keyArray = new char[key.length];
|
||||
|
||||
for(int i = 0; i < key.length; ++i) {
|
||||
keyArray[i] = (char)key[i];
|
||||
}
|
||||
|
||||
PBEKeySpec keySpec = new PBEKeySpec(keyArray, SALT, ITERATION_COUNT, keyLength);
|
||||
SecretKey tempKey = keyFactory.generateSecret(keySpec);
|
||||
return new SecretKeySpec(tempKey.getEncoded(), this.mAlgorithm);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InvalidKeySpecException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private Key getDesKey(byte[] key) {
|
||||
try {
|
||||
DESKeySpec keySpec = new DESKeySpec(key);
|
||||
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
|
||||
return keyFactory.generateSecret(keySpec);
|
||||
} catch (InvalidKeyException e) {
|
||||
e.printStackTrace();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InvalidKeySpecException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private Key getRsaPublicKey() {
|
||||
try {
|
||||
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
|
||||
keyPairGenerator.initialize(this.mKeyLength);
|
||||
KeyPair keyPair = keyPairGenerator.generateKeyPair();
|
||||
this.mPrivateKey = keyPair.getPrivate().getEncoded();
|
||||
return keyPair.getPublic();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private Key getRsaPrivateKey(byte[] keyBytes) {
|
||||
try {
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
|
||||
return keyFactory.generatePrivate(keySpec);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InvalidKeySpecException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private Key getDesedeKey(byte[] key) {
|
||||
int len = 24;
|
||||
byte[] newKey = new byte[len];
|
||||
System.arraycopy(key, 0, newKey, 0, Math.min(key.length, len));
|
||||
return new SecretKeySpec(newKey, "DESede");
|
||||
}
|
||||
|
||||
private byte[] doByCipher(int cipherMode) {
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance(this.mAlgorithm);
|
||||
this.initCipher(cipher);
|
||||
this.mTarget = cipher.doFinal(this.mSource);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
} catch (NoSuchPaddingException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InvalidKeyException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InvalidAlgorithmParameterException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalBlockSizeException e) {
|
||||
e.printStackTrace();
|
||||
} catch (BadPaddingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return this.mTarget;
|
||||
}
|
||||
|
||||
private byte[] doByRc4() {
|
||||
McRc4 cipher = new McRc4(this.mKey);
|
||||
return cipher.decrypt(this.mSource);
|
||||
}
|
||||
|
||||
public static byte[] encryptMessageByHmacMd5(byte[] message) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacMD5");
|
||||
mac.init(new SecretKeySpec(message, "HmacMD5"));
|
||||
return mac.doFinal(message);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InvalidKeyException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalArgumentException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static byte[] encryptMessageByMd5(String message) {
|
||||
return message != null ? encryptMessageByMd5(message.getBytes()) : null;
|
||||
}
|
||||
|
||||
public static byte[] encryptMessageByMd5(byte[] message) {
|
||||
try {
|
||||
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
|
||||
messageDigest.reset();
|
||||
return messageDigest.digest(message);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] encryptByAES(byte[] key, byte[] src, int mode) {
|
||||
try {
|
||||
Provider bcProvider = new BouncyCastleProvider();
|
||||
SecretKeySpec skey = new SecretKeySpec(key, "AES");
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/ZeroBytePadding", bcProvider);
|
||||
cipher.init(mode == 0 ? 2 : 1, skey);
|
||||
byte[] decrypted = cipher.doFinal(src);
|
||||
return decrypted;
|
||||
} catch (Exception var7) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.mitac.cell.security;
|
||||
|
||||
import com.google.common.io.BaseEncoding;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Arrays;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
public class McOtaCert {
|
||||
private static final String DIGEST_ALGORITHM = "SHA-256";
|
||||
private static BaseEncoding Base64 = BaseEncoding.base64();
|
||||
private byte[] keyBytes = null;
|
||||
private byte[] hashBytes = null;
|
||||
|
||||
public McOtaCert(InputStream input) {
|
||||
this.dispatch(input);
|
||||
}
|
||||
|
||||
public byte[] getKey() {
|
||||
return this.keyBytes;
|
||||
}
|
||||
|
||||
public byte[] getHash() {
|
||||
return this.hashBytes;
|
||||
}
|
||||
|
||||
public boolean sameKey(byte[] bytes) {
|
||||
return Arrays.equals(bytes, this.getKey());
|
||||
}
|
||||
|
||||
public boolean sameHash(String base64Hash) {
|
||||
return base64Hash.equals(this.getBase64Hash());
|
||||
}
|
||||
|
||||
public String getBase64Hash() {
|
||||
return BaseEncoding.base64Url().encode(this.getHash());
|
||||
}
|
||||
|
||||
private void dispatch(InputStream input) {
|
||||
try {
|
||||
String keyContent = IOUtils.toString(input, "UTF-8");
|
||||
keyContent = this.getKeyBody(keyContent);
|
||||
this.keyBytes = Base64.decode(keyContent);
|
||||
this.hashBytes = this.genHash(this.keyBytes);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private String getKeyBody(String keyContent) {
|
||||
return keyContent.replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----", "").replace("\n", "").replace("\r", "");
|
||||
}
|
||||
|
||||
private byte[] genHash(byte[] bytes) {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||
return md.digest(bytes);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.mitac.cell.security;
|
||||
|
||||
import com.mitac.cell.utils.McStringUtils;
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.spec.InvalidKeySpecException;
|
||||
import javax.crypto.BadPaddingException;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.IllegalBlockSizeException;
|
||||
import javax.crypto.NoSuchPaddingException;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.PBEKeySpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public class McTextEncryptor {
|
||||
private SecretKey secretKey;
|
||||
private final Cipher decryptor;
|
||||
|
||||
public McTextEncryptor(String password, String salt) {
|
||||
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), McStringUtils.toBytes(salt), 1024, 256);
|
||||
SecretKey secretKey = this.newSecretKey("PBKDF2WithHmacSHA1", keySpec);
|
||||
this.secretKey = new SecretKeySpec(secretKey.getEncoded(), "AES");
|
||||
this.decryptor = this.newCipher("AES/CBC/PKCS5Padding");
|
||||
}
|
||||
|
||||
public String decrypt(String encrypted) {
|
||||
byte[] bytes = McStringUtils.toBytes(encrypted);
|
||||
byte[] decryptedBytes = this.decrypt(bytes);
|
||||
return decryptedBytes == null ? null : new String(decryptedBytes);
|
||||
}
|
||||
|
||||
public byte[] decrypt(byte[] encryptedBytes) {
|
||||
synchronized(this.decryptor) {
|
||||
byte[] iv = new byte[16];
|
||||
|
||||
byte[] var10000;
|
||||
try {
|
||||
this.decryptor.init(2, this.secretKey, new IvParameterSpec(iv));
|
||||
var10000 = this.decryptor.doFinal(encryptedBytes);
|
||||
} catch (Exception var6) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return var10000;
|
||||
}
|
||||
}
|
||||
|
||||
public String encrypt(String source) {
|
||||
synchronized(this.decryptor) {
|
||||
String var10000;
|
||||
try {
|
||||
byte[] iv = new byte[16];
|
||||
this.decryptor.init(1, this.secretKey, new IvParameterSpec(iv));
|
||||
byte[] bytes = this.decryptor.doFinal(source.getBytes());
|
||||
var10000 = McStringUtils.toHexString(bytes);
|
||||
} catch (BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException var6) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return var10000;
|
||||
}
|
||||
}
|
||||
|
||||
private Cipher newCipher(String algorithm) {
|
||||
try {
|
||||
return Cipher.getInstance(algorithm);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalArgumentException("Not a valid encryption algorithm", e);
|
||||
} catch (NoSuchPaddingException e) {
|
||||
throw new IllegalStateException("Should not happen", e);
|
||||
}
|
||||
}
|
||||
|
||||
private SecretKey newSecretKey(String algorithm, PBEKeySpec keySpec) {
|
||||
try {
|
||||
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
|
||||
return factory.generateSecret(keySpec);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalArgumentException("Not a valid encryption algorithm", e);
|
||||
} catch (InvalidKeySpecException e) {
|
||||
throw new IllegalArgumentException("Not a valid secret key", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.mitac.cell.security;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
public class McUserAuthenticationProvider implements AuthenticationProvider {
|
||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||
boolean result = false;
|
||||
if (result) {
|
||||
List<GrantedAuthority> grantedAuthorities = new ArrayList();
|
||||
McUserAuthenticationToken auth = new McUserAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities);
|
||||
return auth;
|
||||
} else {
|
||||
throw new BadCredentialsException("Bad User Credentials.");
|
||||
}
|
||||
}
|
||||
|
||||
public boolean supports(Class authentication) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.mitac.cell.security;
|
||||
|
||||
import java.util.Collection;
|
||||
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
public class McUserAuthenticationToken extends AbstractAuthenticationToken {
|
||||
private static final long serialVersionUID = 503883598783793420L;
|
||||
private final Object principal;
|
||||
private Object credentials;
|
||||
|
||||
public McUserAuthenticationToken(Object principal, Object credentials, Collection authorities) {
|
||||
super(authorities);
|
||||
this.principal = principal;
|
||||
this.credentials = credentials;
|
||||
super.setAuthenticated(true);
|
||||
}
|
||||
|
||||
public Object getCredentials() {
|
||||
return this.credentials;
|
||||
}
|
||||
|
||||
public Object getPrincipal() {
|
||||
return this.principal;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.mitac.cell.security.cipher;
|
||||
|
||||
public class McRc4 {
|
||||
private final byte[] mPermutationArray = new byte[256];
|
||||
private final byte[] mMixedArray = new byte[256];
|
||||
|
||||
public McRc4() {
|
||||
}
|
||||
|
||||
public McRc4(String key) {
|
||||
this.setKey(key);
|
||||
}
|
||||
|
||||
public McRc4(byte[] key) {
|
||||
this.setKey(key);
|
||||
}
|
||||
|
||||
public void setKey(String key) {
|
||||
if (key != null) {
|
||||
this.setKey(key.getBytes());
|
||||
}
|
||||
}
|
||||
|
||||
public void setKey(byte[] keyBytes) {
|
||||
if (keyBytes != null) {
|
||||
int keyLen = keyBytes.length;
|
||||
if (keyLen >= 1 && keyLen <= 256) {
|
||||
for(int i = 0; i < 256; ++i) {
|
||||
this.mPermutationArray[i] = (byte)i;
|
||||
this.mMixedArray[i] = keyBytes[i % keyLen];
|
||||
}
|
||||
|
||||
int j = 0;
|
||||
|
||||
for(int i = 0; i < 256; ++i) {
|
||||
j = j + this.mPermutationArray[i] + this.mMixedArray[i] & 255;
|
||||
byte[] var10000 = this.mPermutationArray;
|
||||
var10000[i] ^= this.mPermutationArray[j];
|
||||
var10000 = this.mPermutationArray;
|
||||
var10000[j] ^= this.mPermutationArray[i];
|
||||
var10000 = this.mPermutationArray;
|
||||
var10000[i] ^= this.mPermutationArray[j];
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] encrypt(byte[] sourceData) {
|
||||
byte[] encryptedData = new byte[sourceData.length];
|
||||
int i = 0;
|
||||
int j = 0;
|
||||
|
||||
for(int count = 0; count < sourceData.length; ++count) {
|
||||
i = i + 1 & 255;
|
||||
j = j + this.mPermutationArray[i] & 255;
|
||||
byte[] var10000 = this.mPermutationArray;
|
||||
var10000[i] ^= this.mPermutationArray[j];
|
||||
var10000 = this.mPermutationArray;
|
||||
var10000[j] ^= this.mPermutationArray[i];
|
||||
var10000 = this.mPermutationArray;
|
||||
var10000[i] ^= this.mPermutationArray[j];
|
||||
int t = this.mPermutationArray[i] + this.mPermutationArray[j] & 255;
|
||||
int k = this.mPermutationArray[t];
|
||||
encryptedData[count] = (byte)(sourceData[count] ^ k);
|
||||
}
|
||||
|
||||
return encryptedData;
|
||||
}
|
||||
|
||||
public byte[] decrypt(byte[] encryptedData) {
|
||||
return this.encrypt(encryptedData);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.mitac.cell.shell;
|
||||
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.google.common.io.CharStreams;
|
||||
import com.mitac.cell.io.McFile;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class McRuntime {
|
||||
private static Runtime runtime = Runtime.getRuntime();
|
||||
|
||||
public static Process exec(String... cmdArray) {
|
||||
try {
|
||||
return cmdArray.length == 1 ? runtime.exec(cmdArray[0]) : runtime.exec(cmdArray);
|
||||
} catch (IOException var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static InputStream execInputStream(String... cmdArray) {
|
||||
Process process = exec(cmdArray);
|
||||
return process == null ? null : process.getInputStream();
|
||||
}
|
||||
|
||||
public static Reader execReader(String... cmdArray) {
|
||||
InputStream is = execInputStream(cmdArray);
|
||||
return is == null ? null : new InputStreamReader(is);
|
||||
}
|
||||
|
||||
public static byte[] execBytes(String... cmdArray) {
|
||||
InputStream is = execInputStream(cmdArray);
|
||||
if (is == null) {
|
||||
return null;
|
||||
} else {
|
||||
try {
|
||||
return ByteStreams.toByteArray(is);
|
||||
} catch (IOException var3) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static String execString(String... cmdArray) {
|
||||
InputStream is = execInputStream(cmdArray);
|
||||
if (is == null) {
|
||||
return null;
|
||||
} else {
|
||||
try {
|
||||
return CharStreams.toString(new InputStreamReader(is));
|
||||
} catch (IOException var3) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static List execStrings(String... cmdArray) {
|
||||
Reader reader = execReader(cmdArray);
|
||||
if (reader == null) {
|
||||
return null;
|
||||
} else {
|
||||
try {
|
||||
List<String> lines = new ArrayList();
|
||||
BufferedReader bufferReader = new BufferedReader(reader);
|
||||
String line = null;
|
||||
|
||||
while((line = bufferReader.readLine()) != null) {
|
||||
lines.add(line);
|
||||
}
|
||||
|
||||
return lines;
|
||||
} catch (IOException var5) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean execFile(String filePath, String... cmdArray) {
|
||||
return execFile(new McFile(filePath), cmdArray);
|
||||
}
|
||||
|
||||
public static boolean execFile(McFile file, String... cmdArray) {
|
||||
InputStream is = execInputStream(cmdArray);
|
||||
return is != null ? file.write(is) : false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package com.mitac.cell.system;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.mitac.cell.net.McNetUtils;
|
||||
import com.mitac.cell.shell.McRuntime;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.Reader;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.util.UUID;
|
||||
import javax.management.MBeanServer;
|
||||
import javax.management.ObjectName;
|
||||
|
||||
public class HwInfo {
|
||||
private String computerName;
|
||||
private int processors;
|
||||
private String serialNo;
|
||||
private UUID systemUuid;
|
||||
private long maxMemory;
|
||||
private long totalMemory;
|
||||
private long freeMemory;
|
||||
private Long physicalTotal;
|
||||
private Long physicalFree;
|
||||
|
||||
public HwInfo(OsInfo.OS_TYPE osType) {
|
||||
this.retreiveDeviceInfo(osType);
|
||||
MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
|
||||
|
||||
try {
|
||||
ObjectName osObject = new ObjectName("java.lang", "type", "OperatingSystem");
|
||||
this.physicalTotal = (Long)beanServer.getAttribute(osObject, "TotalPhysicalMemorySize");
|
||||
this.physicalFree = (Long)beanServer.getAttribute(osObject, "FreePhysicalMemorySize");
|
||||
} catch (Exception var4) {
|
||||
}
|
||||
|
||||
Runtime runtime = Runtime.getRuntime();
|
||||
this.maxMemory = runtime.maxMemory();
|
||||
this.totalMemory = runtime.totalMemory();
|
||||
this.freeMemory = runtime.freeMemory();
|
||||
this.processors = runtime.availableProcessors();
|
||||
}
|
||||
|
||||
private void retreiveDeviceInfo(OsInfo.OS_TYPE osType) {
|
||||
switch (osType) {
|
||||
case LINUX:
|
||||
this.retrieveDeviceInfoInLinux();
|
||||
break;
|
||||
case WINDOWS:
|
||||
this.retrieveDeviceInfoInWindows();
|
||||
break;
|
||||
case MAC:
|
||||
this.retrieveDeviceInfoInMac();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public String getComputerName() {
|
||||
return this.computerName;
|
||||
}
|
||||
|
||||
public int getProcessors() {
|
||||
return this.processors;
|
||||
}
|
||||
|
||||
public UUID getSystemUuid() {
|
||||
return this.systemUuid;
|
||||
}
|
||||
|
||||
public String serialNo() {
|
||||
return this.serialNo;
|
||||
}
|
||||
|
||||
public long getMaxMemory() {
|
||||
return this.maxMemory;
|
||||
}
|
||||
|
||||
public long getTotalMemory() {
|
||||
return this.totalMemory;
|
||||
}
|
||||
|
||||
public long getFreeMemory() {
|
||||
return this.freeMemory;
|
||||
}
|
||||
|
||||
public long getPhysicalTotal() {
|
||||
return this.physicalTotal;
|
||||
}
|
||||
|
||||
public long getPhysicalFree() {
|
||||
return this.physicalFree;
|
||||
}
|
||||
|
||||
private void retrieveDeviceInfoInWindows() {
|
||||
this.computerName = McNetUtils.hostName();
|
||||
if (Strings.isNullOrEmpty(this.computerName)) {
|
||||
this.computerName = System.getenv("COMPUTERNAME");
|
||||
}
|
||||
|
||||
try {
|
||||
Reader reader = McRuntime.execReader("wmic", "csproduct", "get", "identifyingnumber, uuid");
|
||||
BufferedReader bufferedReader = new BufferedReader(reader);
|
||||
|
||||
String line;
|
||||
for(line = null; (line = bufferedReader.readLine()) != null && (Strings.isNullOrEmpty(line) || line.startsWith("IdentifyingNumber")); var6 = null) {
|
||||
}
|
||||
|
||||
if (line != null && line.length() >= 19) {
|
||||
this.serialNo = line.substring(0, 19).trim();
|
||||
this.systemUuid = UUID.fromString(line.substring(19).trim());
|
||||
}
|
||||
} catch (Exception var4) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void retrieveDeviceInfoInLinux() {
|
||||
this.computerName = McNetUtils.hostName();
|
||||
|
||||
try {
|
||||
Reader reader = McRuntime.execReader("dmidecode", "-t", "system");
|
||||
BufferedReader bufferedReader = new BufferedReader(reader);
|
||||
String line = null;
|
||||
|
||||
while((line = bufferedReader.readLine()) != null) {
|
||||
if (Strings.isNullOrEmpty(line)) {
|
||||
String var6 = null;
|
||||
} else {
|
||||
if (line.contains("Serial")) {
|
||||
this.serialNo = line.substring(16).trim();
|
||||
if (this.serialNo.endsWith("O.E.M")) {
|
||||
this.serialNo = null;
|
||||
}
|
||||
} else if (line.contains("UUID")) {
|
||||
this.systemUuid = UUID.fromString(line.substring(7).trim());
|
||||
}
|
||||
|
||||
if (!Strings.isNullOrEmpty(this.serialNo) && this.systemUuid != null) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception var4) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void retrieveDeviceInfoInMac() {
|
||||
this.computerName = McNetUtils.hostName();
|
||||
|
||||
try {
|
||||
Reader reader = McRuntime.execReader("/usr/sbin/system_profiler", "SPHardwareDataType");
|
||||
BufferedReader bufferedReader = new BufferedReader(reader);
|
||||
String line = null;
|
||||
|
||||
while((line = bufferedReader.readLine()) != null) {
|
||||
if (!Strings.isNullOrEmpty(line) && !line.startsWith("IdentifyingNumber")) {
|
||||
if (line.contains("Serial")) {
|
||||
this.serialNo = line.substring(30).trim();
|
||||
} else if (line.contains("Hardware UUID")) {
|
||||
this.systemUuid = UUID.fromString(line.substring(21).trim());
|
||||
}
|
||||
|
||||
if (!Strings.isNullOrEmpty(this.serialNo) && this.systemUuid != null) {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
String var6 = null;
|
||||
}
|
||||
}
|
||||
} catch (Exception var4) {
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.mitac.cell.system;
|
||||
|
||||
import com.mitac.cell.net.McNetUtils;
|
||||
import java.util.List;
|
||||
|
||||
public class McSystemInfo {
|
||||
private OsInfo osInfo = new OsInfo();
|
||||
private HwInfo hwInfo;
|
||||
private byte[] macAddr;
|
||||
private List macAddresses;
|
||||
|
||||
public McSystemInfo() {
|
||||
this.hwInfo = new HwInfo(this.osInfo.osType());
|
||||
this.macAddresses = McNetUtils.macAddress();
|
||||
this.macAddr = McNetUtils.getMacAddr();
|
||||
}
|
||||
|
||||
public OsInfo getOsInfo() {
|
||||
return this.osInfo;
|
||||
}
|
||||
|
||||
public HwInfo getHwInfo() {
|
||||
return this.hwInfo;
|
||||
}
|
||||
|
||||
public List getMacAddresses() {
|
||||
return this.macAddresses;
|
||||
}
|
||||
|
||||
public byte[] getMacAddress() {
|
||||
return this.macAddr;
|
||||
}
|
||||
|
||||
public String generateHash() {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.mitac.cell.system;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.mitac.cell.shell.McRuntime;
|
||||
|
||||
public class MsWindows {
|
||||
private static final String REGQUERY_UTIL = "reg query ";
|
||||
private static final String REGBINARY_TOKEN = "REG_BINARY";
|
||||
private static final String PRODUCT_KEY_CMD = "reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\" /v DigitalProductId";
|
||||
|
||||
public static String queryRegistry(String cmd, String token) {
|
||||
String cmdOutput = McRuntime.execString(cmd);
|
||||
if (Strings.isNullOrEmpty(cmdOutput)) {
|
||||
return null;
|
||||
} else {
|
||||
int tokenIndex = cmdOutput.indexOf(token);
|
||||
return tokenIndex < 0 ? null : cmdOutput.substring(tokenIndex + token.length()).trim();
|
||||
}
|
||||
}
|
||||
|
||||
public static String getProductKey() {
|
||||
String fullPID = "";
|
||||
String encodedKey = "";
|
||||
if (queryRegistry("reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\" /v DigitalProductId", "REG_BINARY") != null) {
|
||||
fullPID = queryRegistry("reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\" /v DigitalProductId", "REG_BINARY");
|
||||
}
|
||||
|
||||
encodedKey = fullPID.substring(104, 134);
|
||||
char[] digits = new char[]{'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'P', 'Q', 'R', 'T', 'V', 'W', 'X', 'Y', '2', '3', '4', '6', '7', '8', '9'};
|
||||
int D_LEN = 29;
|
||||
int S_LEN = 15;
|
||||
int[] hexDigitalPID = new int[29];
|
||||
char[] des = new char[30];
|
||||
int i = 0;
|
||||
int n = 0;
|
||||
int hn = 0;
|
||||
String rval = "";
|
||||
|
||||
for(int var12 = 0; var12 <= 14; ++var12) {
|
||||
String var10002 = encodedKey.substring(var12 * 2, var12 * 2 + 2);
|
||||
hexDigitalPID[var12] = Integer.decode("0x" + var10002);
|
||||
}
|
||||
|
||||
for(int var13 = 28; var13 >= 0; --var13) {
|
||||
if ((var13 + 1) % 6 == 0) {
|
||||
des[var13] = '-';
|
||||
} else {
|
||||
hn = 0;
|
||||
|
||||
for(int var15 = 14; var15 >= 0; --var15) {
|
||||
hn = (hn << 8) + hexDigitalPID[var15];
|
||||
hexDigitalPID[var15] = hn / 24;
|
||||
hn %= 24;
|
||||
}
|
||||
|
||||
des[var13] = digits[hn];
|
||||
}
|
||||
}
|
||||
|
||||
des[29] = '\n';
|
||||
|
||||
for(int var14 = 0; des[var14] != '\n'; ++var14) {
|
||||
rval = rval + des[var14];
|
||||
}
|
||||
|
||||
return rval;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.mitac.cell.system;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class OsInfo {
|
||||
private OS_TYPE osType;
|
||||
private String name = System.getProperty("os.name");
|
||||
private String version;
|
||||
|
||||
public OsInfo() {
|
||||
if (this.name != null) {
|
||||
this.name = this.name.toLowerCase();
|
||||
}
|
||||
|
||||
this.version = System.getProperty("os.version");
|
||||
if (this.name.contains("nux")) {
|
||||
this.osType = OsInfo.OS_TYPE.LINUX;
|
||||
} else if (this.name.contains("win")) {
|
||||
this.osType = OsInfo.OS_TYPE.WINDOWS;
|
||||
} else if (!this.name.contains("mac") && !this.name.contains("darwin")) {
|
||||
if (!this.name.contains("nix") && !this.name.contains("aix")) {
|
||||
if (this.name.contains("sunos")) {
|
||||
this.osType = OsInfo.OS_TYPE.SOLARIS;
|
||||
} else {
|
||||
this.osType = OsInfo.OS_TYPE.UNKNOWN;
|
||||
}
|
||||
} else {
|
||||
this.osType = OsInfo.OS_TYPE.AIX;
|
||||
}
|
||||
} else {
|
||||
this.osType = OsInfo.OS_TYPE.MAC;
|
||||
}
|
||||
|
||||
if (this.osType == OsInfo.OS_TYPE.WINDOWS) {
|
||||
MsWindows.getProductKey();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public OS_TYPE osType() {
|
||||
return this.osType;
|
||||
}
|
||||
|
||||
public String getAppDataFolderPath() {
|
||||
if (this.osType == OsInfo.OS_TYPE.WINDOWS) {
|
||||
return System.getenv("AppData");
|
||||
} else if (this.osType == OsInfo.OS_TYPE.LINUX) {
|
||||
return System.getProperty("user.home");
|
||||
} else {
|
||||
return this.osType == OsInfo.OS_TYPE.MAC ? "/" : "/";
|
||||
}
|
||||
}
|
||||
|
||||
public File getAppDataFolderPath(String appName) {
|
||||
return new File(this.getAppDataFolderPath(), appName);
|
||||
}
|
||||
|
||||
public String getConfigFolderPath() {
|
||||
if (this.osType == OsInfo.OS_TYPE.WINDOWS) {
|
||||
return "c:\\ProgramData";
|
||||
} else if (this.osType == OsInfo.OS_TYPE.LINUX) {
|
||||
return "/etc";
|
||||
} else {
|
||||
return this.osType == OsInfo.OS_TYPE.MAC ? "/" : "/";
|
||||
}
|
||||
}
|
||||
|
||||
public File getConfigFolder(String appName) {
|
||||
return new File(this.getConfigFolderPath(), appName);
|
||||
}
|
||||
|
||||
public String name() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public String version() {
|
||||
return this.version;
|
||||
}
|
||||
|
||||
public static enum OS_TYPE {
|
||||
WINDOWS,
|
||||
LINUX,
|
||||
SOLARIS,
|
||||
MAC,
|
||||
AIX,
|
||||
UNKNOWN;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.mitac.cell.utils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class McBooleanUtils {
|
||||
private static final List falseValues = new ArrayList() {
|
||||
{
|
||||
Object[] trueValues = new Object[]{'f', 'n', 'x', '0', "false", "no", "not", "off", "down", "stop", "cancel", "disable", "disabled", "negative"};
|
||||
this.addAll(Arrays.asList(trueValues));
|
||||
}
|
||||
};
|
||||
|
||||
public static Boolean isTrue(Object value) {
|
||||
if (value == null) {
|
||||
return false;
|
||||
} else if (value instanceof Boolean) {
|
||||
return (Boolean)value;
|
||||
} else if (value instanceof Character) {
|
||||
return !falseValues.contains(Character.toLowerCase((Character)value));
|
||||
} else if (value instanceof String) {
|
||||
return !falseValues.contains(((String)value).toLowerCase());
|
||||
} else {
|
||||
return value instanceof Number ? ((Number)value).doubleValue() != (double)0.0F : false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.mitac.cell.utils;
|
||||
|
||||
public class McChar {
|
||||
public static final char CHAR_SPACE = ' ';
|
||||
public static final char CHAR_COMMA = ',';
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.mitac.cell.utils;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.Base64;
|
||||
import javax.crypto.Cipher;
|
||||
|
||||
public class McCipherUtils {
|
||||
public static final String RSA_OAEPWITHSHA1_MODE = "RSA/ECB/OAEPWithSHA-1AndMGF1Padding";
|
||||
|
||||
public static String encryptByRsaPublicKey(String encryptMode, String publicKeyBase64, String plainText) {
|
||||
try {
|
||||
byte[] decoded = Base64.getDecoder().decode(publicKeyBase64);
|
||||
X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
|
||||
KeyFactory kf = KeyFactory.getInstance("RSA");
|
||||
RSAPublicKey rsaPublicKey = (RSAPublicKey)kf.generatePublic(spec);
|
||||
Cipher cipher = Cipher.getInstance(encryptMode);
|
||||
cipher.init(1, rsaPublicKey);
|
||||
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
|
||||
return Base64.getEncoder().encodeToString(encryptedBytes);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean decryptByPrivateKey(String decryptMode, String privateKeyBase64, String encrpytString, String serialNo) {
|
||||
try {
|
||||
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyBase64.getBytes(StandardCharsets.UTF_8)));
|
||||
KeyFactory kf = KeyFactory.getInstance("RSA");
|
||||
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)kf.generatePrivate(keySpec);
|
||||
byte[] decodedString = Base64.getDecoder().decode(encrpytString.getBytes(StandardCharsets.UTF_8));
|
||||
Cipher cipher = Cipher.getInstance(decryptMode);
|
||||
cipher.init(2, rsaPrivateKey);
|
||||
byte[] decryptBytes = cipher.doFinal(decodedString);
|
||||
String[] decryptStrings = (new String(decryptBytes)).split(",");
|
||||
return decryptStrings.length == 3 && decryptStrings[0].equals(serialNo);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
package com.mitac.cell.utils;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.mitac.cell.doc.Csv;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInput;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutput;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.StreamCorruptedException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.text.NumberFormat;
|
||||
import java.text.ParseException;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class McConvert {
|
||||
public static String toString(Object value) {
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
public static int toInt(String value) {
|
||||
if (!value.startsWith("x") && !value.startsWith("0x")) {
|
||||
try {
|
||||
return NumberFormat.getInstance(Locale.ENGLISH).parse(value).intValue();
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return -1;
|
||||
}
|
||||
} else {
|
||||
value = value.substring(value.indexOf("x") + 1);
|
||||
return Integer.parseInt(value, 16);
|
||||
}
|
||||
}
|
||||
|
||||
public static int toInt(Object value) {
|
||||
if (value == null) {
|
||||
return 0;
|
||||
} else if (value instanceof Number) {
|
||||
return ((Number)value).intValue();
|
||||
} else {
|
||||
try {
|
||||
return Integer.parseInt(value.toString().trim());
|
||||
} catch (NumberFormatException var2) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static short toShort(Object value) {
|
||||
if (value == null) {
|
||||
return 0;
|
||||
} else {
|
||||
return value instanceof Number ? ((Number)value).shortValue() : Short.parseShort(value.toString());
|
||||
}
|
||||
}
|
||||
|
||||
public static long toLong(Object value) {
|
||||
if (value == null) {
|
||||
return 0L;
|
||||
} else {
|
||||
return value instanceof Number ? ((Number)value).longValue() : Long.parseLong(value.toString());
|
||||
}
|
||||
}
|
||||
|
||||
public static float toFloat(Object value) {
|
||||
if (value == null) {
|
||||
return 0.0F;
|
||||
} else {
|
||||
return value instanceof Number ? ((Number)value).floatValue() : Float.parseFloat(value.toString());
|
||||
}
|
||||
}
|
||||
|
||||
public static double toDouble(Object value) {
|
||||
if (value == null) {
|
||||
return (double)0.0F;
|
||||
} else {
|
||||
return value instanceof Number ? ((Number)value).doubleValue() : Double.parseDouble(value.toString());
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean toBoolean(Object value) {
|
||||
if (value == null) {
|
||||
return false;
|
||||
} else if (value instanceof Boolean) {
|
||||
return (Boolean)value;
|
||||
} else if (value instanceof Number) {
|
||||
return toInt(value) != 0;
|
||||
} else if (value instanceof String) {
|
||||
String val = ((String)value).toLowerCase();
|
||||
return !val.isEmpty() && !val.equals("0") && !val.equals("false") && !val.equals("n") && !val.equals("no") && !val.equals("off") && !val.equals("stop") && !val.equals("down");
|
||||
} else {
|
||||
return value instanceof JsonPrimitive ? ((JsonPrimitive)value).getAsBoolean() : false;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] toBlob(Object value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
} else {
|
||||
try {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream output = new ObjectOutputStream(bos);
|
||||
output.writeObject(value);
|
||||
return bos.toByteArray();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static String toCSVString(String[] values) {
|
||||
Csv formatter = new Csv();
|
||||
return formatter.toString(values);
|
||||
}
|
||||
|
||||
public static String toCSVString(int[] values) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for(int i = 0; i < values.length; ++i) {
|
||||
if (i > 0) {
|
||||
sb.append(",");
|
||||
}
|
||||
|
||||
sb.append(values[i]);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static Object[] toObjectArray(int[] values) {
|
||||
Object[] array = new Object[values.length];
|
||||
|
||||
for(int i = 0; i < values.length; ++i) {
|
||||
array[i] = values[i];
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
public static String toCSVString(List columns) {
|
||||
Csv formatter = new Csv();
|
||||
return formatter.toString(columns);
|
||||
}
|
||||
|
||||
public static String toCSVString(Set columns) {
|
||||
Csv formatter = new Csv();
|
||||
return formatter.toString(columns);
|
||||
}
|
||||
|
||||
public static String[] CSVtoStringArray(String csvString) {
|
||||
Csv formatter = new Csv();
|
||||
|
||||
try {
|
||||
return formatter.parse(csvString);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Set CSVtoStringSet(String csvString) {
|
||||
return new HashSet(CSVtoStringList(csvString));
|
||||
}
|
||||
|
||||
public static List CSVtoStringList(String csvString) {
|
||||
Csv formatter = new Csv();
|
||||
|
||||
try {
|
||||
return Arrays.asList(formatter.parse(csvString));
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] toBytes(int size, boolean isLittleEndian, int value) {
|
||||
return ByteBuffer.allocate(size).order(isLittleEndian ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN).putInt(value).array();
|
||||
}
|
||||
|
||||
public static int toInt(boolean isLittleEndian, byte[] value) {
|
||||
return ByteBuffer.wrap(value).order(isLittleEndian ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN).getInt();
|
||||
}
|
||||
|
||||
public static byte[] toBytes(Object object) {
|
||||
if (object == null) {
|
||||
return null;
|
||||
} else {
|
||||
try {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
ObjectOutput out = new ObjectOutputStream(bos);
|
||||
out.writeObject(object);
|
||||
return bos.toByteArray();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Object toObject(byte[] object) {
|
||||
if (object == null) {
|
||||
return null;
|
||||
} else {
|
||||
try {
|
||||
ByteArrayInputStream bis = new ByteArrayInputStream(object);
|
||||
ObjectInput in = new ObjectInputStream(bis);
|
||||
return in.readObject();
|
||||
} catch (StreamCorruptedException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static int[] toIntArray(byte[] byteArray) {
|
||||
if (byteArray == null) {
|
||||
return null;
|
||||
} else {
|
||||
int[] intArray = new int[byteArray.length];
|
||||
|
||||
for(int i = 0; i < byteArray.length; intArray[i] = byteArray[i++] & 255) {
|
||||
}
|
||||
|
||||
return intArray;
|
||||
}
|
||||
}
|
||||
|
||||
public static int toInt(byte[] byteArray) {
|
||||
int value = 0;
|
||||
|
||||
for(int i = 0; i < byteArray.length; ++i) {
|
||||
int shift = (byteArray.length - 1 - i) * 8;
|
||||
value += (byteArray[i] & 255) << shift;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
public static String toJavaString(String source) {
|
||||
if (Strings.isNullOrEmpty(source)) {
|
||||
return "";
|
||||
} else {
|
||||
String replaced = source.replace("\\r", "\r").replace("\\n", "\n").replace("\\t", "\t").replace("\\b", "\b").replace("\\f", "\f").replace("\\'", "'").replace("\\\"", "\"").replace("\\\\", "\\");
|
||||
Pattern p = Pattern.compile("\\\\[uU][A-Fa-f0-9]{4}");
|
||||
Matcher matcher = p.matcher(replaced);
|
||||
|
||||
for(int pos = 0; matcher.find(pos); pos = matcher.end()) {
|
||||
Integer v = Integer.parseInt(matcher.group(0).substring(2), 16);
|
||||
replaced = replaced.replace(matcher.group(0), String.format("%c", v));
|
||||
}
|
||||
|
||||
return replaced;
|
||||
}
|
||||
}
|
||||
|
||||
public static String toNormalString(String source) {
|
||||
return source.replace("\n", "\\n").replace("\t", "\\t").replace("\b", "\\b").replace("\f", "\\f");
|
||||
}
|
||||
|
||||
public static String toInversedString(String source) {
|
||||
StringBuilder sb = new StringBuilder(source);
|
||||
|
||||
for(int index = 0; index < sb.length(); ++index) {
|
||||
char c = sb.charAt(index);
|
||||
if (Character.isLowerCase(c)) {
|
||||
sb.setCharAt(index, Character.toUpperCase(c));
|
||||
} else {
|
||||
sb.setCharAt(index, Character.toLowerCase(c));
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package com.mitac.cell.utils;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
import org.apache.poi.ss.usermodel.DateUtil;
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.DateTimeZone;
|
||||
import org.joda.time.Days;
|
||||
import org.joda.time.LocalDateTime;
|
||||
import org.joda.time.Years;
|
||||
import org.joda.time.format.DateTimeFormat;
|
||||
import org.joda.time.format.DateTimeFormatter;
|
||||
import org.joda.time.format.ISODateTimeFormat;
|
||||
|
||||
public class McDateTimeUtils {
|
||||
public static final int START_TW_YEAR = 1911;
|
||||
public static final String LONG_FORMAT = "yyyy-MM-dd HH:mm:ss";
|
||||
public static final String SHORT_FORMAT = "yyyy-MM-dd";
|
||||
public static final DateFormat SHORT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
|
||||
|
||||
public static boolean isBetween(DateTime startDate, DateTime endDate) {
|
||||
return isBetween(startDate, endDate, new DateTime());
|
||||
}
|
||||
|
||||
public static boolean isBetween(DateTime startDate, DateTime endDate, DateTime curDateTime) {
|
||||
long mills = curDateTime.getMillis();
|
||||
return startDate.getMillis() <= mills && mills <= endDate.getMillis();
|
||||
}
|
||||
|
||||
public static int yearsFrom(DateTime birthDate) {
|
||||
return yearsBetween(birthDate, new DateTime());
|
||||
}
|
||||
|
||||
public static int yearsBetween(DateTime fromDate, DateTime toDate) {
|
||||
return Years.yearsBetween(fromDate.toLocalDate(), toDate.toLocalDate()).getYears();
|
||||
}
|
||||
|
||||
public static int daysFrom(DateTime fromDate) {
|
||||
return daysBetween(fromDate, new DateTime());
|
||||
}
|
||||
|
||||
public static int daysBetween(DateTime fromDate, DateTime toDate) {
|
||||
return Days.daysBetween(fromDate.toLocalDate(), toDate.toLocalDate()).getDays();
|
||||
}
|
||||
|
||||
public static Date later(long millis) {
|
||||
return DateTime.now().plus(millis).toDate();
|
||||
}
|
||||
|
||||
public static Date secondsLater(int mins) {
|
||||
return DateTime.now().plusSeconds(mins).toDate();
|
||||
}
|
||||
|
||||
public static Date minsLater(int millis) {
|
||||
return DateTime.now().plusMinutes(millis).toDate();
|
||||
}
|
||||
|
||||
public static boolean isSameDate(DateTime date1, DateTime date2) {
|
||||
return date1 != null && date2 != null ? date1.toLocalDate().equals(date2.toLocalDate()) : false;
|
||||
}
|
||||
|
||||
public static boolean isSameDate(Long date1, Long date2) {
|
||||
return date1 != null && date2 != null ? isSameDate(new DateTime(date1, DateTimeZone.getDefault()), new DateTime(date2, DateTimeZone.getDefault())) : false;
|
||||
}
|
||||
|
||||
public static boolean isSameDay(DateTime date1, DateTime date2) {
|
||||
if (date1 != null && date2 != null) {
|
||||
return date1.getMonthOfYear() == date2.getMonthOfYear() && date1.getDayOfMonth() == date2.getDayOfMonth();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isSameDay(Long date1, Long date2) {
|
||||
return date1 != null && date2 != null ? isSameDay(new DateTime(date1, DateTimeZone.UTC), new DateTime(date2, DateTimeZone.UTC)) : false;
|
||||
}
|
||||
|
||||
public static boolean isSameDay(Date date1, String date2, String dateFormat) {
|
||||
return date1 != null && !McStringUtils.isNullOrEmpty(date2) ? (new SimpleDateFormat(dateFormat)).format(date1).equals(date2) : false;
|
||||
}
|
||||
|
||||
public static String toString(DateTime dateTime, String dateFormat) {
|
||||
if (dateTime == null) {
|
||||
return null;
|
||||
} else {
|
||||
return dateFormat == null ? dateTime.toString() : DateTimeFormat.forPattern(dateFormat).print(dateTime);
|
||||
}
|
||||
}
|
||||
|
||||
public static String toString(Date dateTime, TimeZone timeZone, String dateFormat) {
|
||||
return toString(new DateTime(dateTime, DateTimeZone.forTimeZone(timeZone)), dateFormat);
|
||||
}
|
||||
|
||||
public static DateTime parseDate(String dateString, String dateFormat) {
|
||||
return parseDate(dateString, dateFormat, DateTimeZone.UTC);
|
||||
}
|
||||
|
||||
public static DateTime parseDate(String dateString, String dateFormat, String timeZoneText) {
|
||||
if (McStringUtils.isNullOrEmpty(dateString)) {
|
||||
return null;
|
||||
} else {
|
||||
try {
|
||||
DateTimeZone timeZone = McStringUtils.isNullOrEmpty(timeZoneText) ? DateTimeZone.UTC : DateTimeZone.forID(timeZoneText);
|
||||
return parseDate(dateString, dateFormat, timeZone);
|
||||
} catch (Exception var4) {
|
||||
return parseDate(dateString, dateFormat, DateTimeZone.UTC);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static DateTime parseDate(String dateString, String dateFormat, DateTimeZone timeZone) {
|
||||
if (McStringUtils.isNullOrEmpty(dateString)) {
|
||||
return null;
|
||||
} else {
|
||||
if (timeZone == null) {
|
||||
timeZone = DateTimeZone.UTC;
|
||||
}
|
||||
|
||||
try {
|
||||
return McStringUtils.isNullOrEmpty(dateFormat) ? ISODateTimeFormat.dateTime().withZone(timeZone).parseDateTime(dateString) : DateTime.parse(dateString, DateTimeFormat.forPattern(dateFormat).withZone(timeZone));
|
||||
} catch (Exception var4) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static DateTime parseTwDate(String twDateString) {
|
||||
return McStringUtils.isNullOrEmpty(twDateString) ? null : parseTwDate(twDateString, "yyyy/MM/dd");
|
||||
}
|
||||
|
||||
public static DateTime parseTwDate(String twDateString, String format) {
|
||||
if (McStringUtils.isNullOrEmpty(twDateString)) {
|
||||
return null;
|
||||
} else {
|
||||
int yearIndex = format.indexOf("yyyy");
|
||||
String yearString = twDateString.substring(yearIndex, 4);
|
||||
int year = McNumberUtils.toInt(yearString) + 1911;
|
||||
twDateString = twDateString.replaceFirst(yearString, String.valueOf(year));
|
||||
DateTimeFormatter formatter = DateTimeFormat.forPattern(format);
|
||||
return DateTime.parse(twDateString, formatter);
|
||||
}
|
||||
}
|
||||
|
||||
public static DateTime parseExcelDate(String cellValue) {
|
||||
return McStringUtils.isNullOrEmpty(cellValue) ? null : parseExcelDate(Double.parseDouble(cellValue));
|
||||
}
|
||||
|
||||
public static DateTime parseExcelDate(double cellValue) {
|
||||
return new DateTime(DateUtil.getJavaDate(cellValue));
|
||||
}
|
||||
|
||||
public static DateTime getUtcTime() {
|
||||
return DateTime.now(DateTimeZone.UTC);
|
||||
}
|
||||
|
||||
public static DateTime toLocalTime(long utc, DateTimeZone timeZone) {
|
||||
return (new LocalDateTime(utc, DateTimeZone.UTC)).toDateTime(timeZone);
|
||||
}
|
||||
|
||||
public static enum FREQUENCY {
|
||||
second,
|
||||
minute,
|
||||
hour,
|
||||
day,
|
||||
week,
|
||||
month,
|
||||
year;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.mitac.cell.utils;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.StringTokenizer;
|
||||
import java.util.regex.Pattern;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
|
||||
public class McEmailUtils {
|
||||
private static final String EMAIL_REGEX = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z]+$";
|
||||
private static final Pattern emailPattern = Pattern.compile("^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z]+$");
|
||||
|
||||
public static boolean isValid(String email) {
|
||||
return McStringUtils.isNullOrEmpty(email) ? false : emailPattern.matcher(email).matches();
|
||||
}
|
||||
|
||||
public static String formattedMail(String email, String name) {
|
||||
if (isValid(email)) {
|
||||
if (McStringUtils.isNullOrEmpty(name)) {
|
||||
name = email.substring(0, email.indexOf(64));
|
||||
}
|
||||
|
||||
return String.format("%s<%s>", name, email);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static List parseMails(String to) {
|
||||
if (Strings.isNullOrEmpty(to)) {
|
||||
return null;
|
||||
} else {
|
||||
List<InternetAddress> mails = new ArrayList();
|
||||
String delim = "\n\r\t;";
|
||||
StringTokenizer st = new StringTokenizer(to, "\n\r\t;");
|
||||
|
||||
while(st.hasMoreTokens()) {
|
||||
String token = st.nextToken().trim().toLowerCase();
|
||||
|
||||
try {
|
||||
InternetAddress[] address = InternetAddress.parse(token);
|
||||
|
||||
for(InternetAddress addr : address) {
|
||||
if (isValid(addr.getAddress())) {
|
||||
mails.add(addr);
|
||||
}
|
||||
}
|
||||
} catch (Exception var10) {
|
||||
}
|
||||
}
|
||||
|
||||
return mails;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
package com.mitac.cell.utils;
|
||||
|
||||
import com.fatboyindustrial.gsonjodatime.Converters;
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.gson.ExclusionStrategy;
|
||||
import com.google.gson.FieldAttributes;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import com.google.gson.annotations.Expose;
|
||||
import com.mitac.cell.gson.typeAdapter.CipherTypeAdapter;
|
||||
import com.mitac.cell.gson.typeAdapter.CompatibleTimeZoneTypeAdapter;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.lang.reflect.Type;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.TimeZone;
|
||||
import java.util.UUID;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
public class McJsonUtils {
|
||||
public static String FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
|
||||
private static final Gson gson;
|
||||
private static final Gson gsonCloner;
|
||||
|
||||
public static String getString(JsonObject jInfo, String property) {
|
||||
JsonElement element = getProperty(jInfo, property);
|
||||
if (element == null) {
|
||||
return null;
|
||||
} else {
|
||||
return element.isJsonPrimitive() ? element.getAsString() : element.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static int getInt(JsonObject jInfo, String property, int defaultValue) {
|
||||
JsonElement element = getProperty(jInfo, property);
|
||||
return element == null ? defaultValue : element.getAsInt();
|
||||
}
|
||||
|
||||
public static long getLong(JsonObject jInfo, String property, long defaultValue) {
|
||||
JsonElement element = getProperty(jInfo, property);
|
||||
return element == null ? defaultValue : element.getAsLong();
|
||||
}
|
||||
|
||||
public static float getFloat(JsonObject jInfo, String property, float defaultValue) {
|
||||
JsonElement element = getProperty(jInfo, property);
|
||||
return element == null ? defaultValue : element.getAsFloat();
|
||||
}
|
||||
|
||||
public static boolean getBoolean(JsonObject jInfo, String property, boolean defaultValue) {
|
||||
JsonElement element = getProperty(jInfo, property);
|
||||
return element == null ? defaultValue : element.getAsBoolean();
|
||||
}
|
||||
|
||||
public static Date getDate(JsonObject jInfo, String property, Date defaultValue) {
|
||||
JsonElement element = getProperty(jInfo, property);
|
||||
return element == null ? defaultValue : new Date(element.getAsLong());
|
||||
}
|
||||
|
||||
public static URL getUrl(JsonObject jInfo, String property) {
|
||||
JsonElement element = getProperty(jInfo, property);
|
||||
|
||||
try {
|
||||
return element == null ? null : new URL(element.getAsString());
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static UUID getUuid(JsonObject jInfo, String property) {
|
||||
JsonElement element = getProperty(jInfo, property);
|
||||
return element == null ? null : UUID.fromString(element.getAsString());
|
||||
}
|
||||
|
||||
public static JsonElement getProperty(JsonObject jInfo, String property) {
|
||||
if (jInfo == null) {
|
||||
jInfo = new JsonObject();
|
||||
}
|
||||
|
||||
return jInfo == null ? null : jInfo.get(property);
|
||||
}
|
||||
|
||||
public static boolean isValid(JsonObject jObject) {
|
||||
return !isNullOrEmpty(jObject);
|
||||
}
|
||||
|
||||
public static boolean isNullOrEmpty(JsonObject jObject) {
|
||||
return jObject == null || jObject.entrySet().isEmpty();
|
||||
}
|
||||
|
||||
public static JsonElement toJson(byte[] content) {
|
||||
return content == null ? null : JsonParser.parseReader(new InputStreamReader(new ByteArrayInputStream(content)));
|
||||
}
|
||||
|
||||
public static JsonElement toJsonElement(Object src) {
|
||||
return gsonCloner.toJsonTree(src);
|
||||
}
|
||||
|
||||
public static void setProperty(JsonObject jInfo, String property, Object value) {
|
||||
if (jInfo == null) {
|
||||
jInfo = new JsonObject();
|
||||
}
|
||||
|
||||
jInfo.add(property, toJsonElement(value));
|
||||
}
|
||||
|
||||
public static JsonElement toJsonElement(String jsonSource) {
|
||||
try {
|
||||
return McStringUtils.isNullOrEmpty(jsonSource) ? null : JsonParser.parseString(jsonSource);
|
||||
} catch (JsonSyntaxException var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static JsonElement toJsonElement(HttpServletRequest request) {
|
||||
try {
|
||||
return toJsonElement((InputStream)request.getInputStream());
|
||||
} catch (Exception var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static JsonElement toJsonElement(InputStream is) {
|
||||
return is == null ? null : toJsonElement((Reader)(new InputStreamReader(is, Charsets.UTF_8)));
|
||||
}
|
||||
|
||||
public static JsonElement toJsonElement(File file) {
|
||||
try {
|
||||
return file != null && file.exists() && !file.isDirectory() ? toJsonElement((InputStream)(new FileInputStream(file))) : null;
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static JsonElement toJsonElement(Reader jsonReader) {
|
||||
try {
|
||||
return jsonReader == null ? null : JsonParser.parseReader(jsonReader);
|
||||
} catch (Exception var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Map toBooleanMap(String jsonSource) {
|
||||
if (McStringUtils.isNullOrEmpty(jsonSource)) {
|
||||
return null;
|
||||
} else {
|
||||
JsonElement jElement = toJsonElement(jsonSource);
|
||||
return jElement.isJsonObject() ? toBooleanMap(jElement.getAsJsonObject()) : null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Map toBooleanMap(JsonObject jObject) {
|
||||
if (jObject != null && !jObject.entrySet().isEmpty()) {
|
||||
Map<String, Boolean> map = new HashMap();
|
||||
|
||||
for(Map.Entry jEntry : jObject.entrySet()) {
|
||||
boolean value = false;
|
||||
if (((JsonElement)jEntry.getValue()).isJsonPrimitive()) {
|
||||
JsonPrimitive jPrimitive = ((JsonElement)jEntry.getValue()).getAsJsonPrimitive();
|
||||
if (jPrimitive.isBoolean()) {
|
||||
value = jPrimitive.getAsBoolean();
|
||||
} else if (jPrimitive.isNumber()) {
|
||||
value = jPrimitive.getAsDouble() != (double)0.0F;
|
||||
} else if (jPrimitive.isString()) {
|
||||
value = McBooleanUtils.isTrue(jPrimitive.getAsString());
|
||||
}
|
||||
}
|
||||
|
||||
map.put((String)jEntry.getKey(), value);
|
||||
}
|
||||
|
||||
return map;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Object toObject(HttpServletRequest request, Type dataType) {
|
||||
try {
|
||||
return toObject(toJsonElement((InputStream)request.getInputStream()), dataType);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Object toObject(InputStream is, Type dataType) {
|
||||
return toObject(toJsonElement(is), dataType);
|
||||
}
|
||||
|
||||
public static Object toObject(byte[] bytes, Type dataType) {
|
||||
return toObject((InputStream)(new ByteArrayInputStream(bytes)), dataType);
|
||||
}
|
||||
|
||||
public static Object toObject(String jElement, Type dataType) {
|
||||
return toObject(toJsonElement(jElement), dataType);
|
||||
}
|
||||
|
||||
public static Object toObject(JsonElement jElement, Type dataType) {
|
||||
return jElement != null && !jElement.isJsonPrimitive() ? gson.fromJson(jElement, dataType) : null;
|
||||
}
|
||||
|
||||
public static Object clone(Object object) {
|
||||
return gsonCloner.fromJson(toJsonElement(object), object.getClass());
|
||||
}
|
||||
|
||||
public static String toJson(Object object) {
|
||||
return gson.toJson(object);
|
||||
}
|
||||
|
||||
public static String toJson(Object object, boolean pretty) {
|
||||
GsonBuilder builder = new GsonBuilder();
|
||||
if (pretty) {
|
||||
builder.setPrettyPrinting();
|
||||
}
|
||||
|
||||
return builder.create().toJson(object);
|
||||
}
|
||||
|
||||
public static JsonObject merge(JsonObject... jObjects) {
|
||||
if (jObjects != null && jObjects.length != 0) {
|
||||
JsonObject jResult = null;
|
||||
|
||||
for(JsonObject jObject : jObjects) {
|
||||
if (jResult == null) {
|
||||
jResult = jObject;
|
||||
} else {
|
||||
for(Map.Entry entry : jObject.entrySet()) {
|
||||
jResult.add((String)entry.getKey(), (JsonElement)entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return jResult;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean equals(JsonElement src, JsonElement target) {
|
||||
if (src != null && target != null) {
|
||||
if (src.isJsonObject()) {
|
||||
if (target.isJsonObject()) {
|
||||
}
|
||||
|
||||
return false;
|
||||
} else if (src.isJsonArray()) {
|
||||
if (target.isJsonObject()) {
|
||||
}
|
||||
|
||||
return false;
|
||||
} else if (src.isJsonPrimitive()) {
|
||||
if (!target.isJsonPrimitive()) {
|
||||
return false;
|
||||
} else {
|
||||
JsonPrimitive srcPrim = src.getAsJsonPrimitive();
|
||||
JsonPrimitive targetPrim = target.getAsJsonPrimitive();
|
||||
if (srcPrim.isString()) {
|
||||
return targetPrim.isString() && src.getAsString().equals(targetPrim.getAsString());
|
||||
} else if (srcPrim.isNumber()) {
|
||||
return targetPrim.isNumber() && src.getAsDouble() == targetPrim.getAsDouble();
|
||||
} else {
|
||||
return targetPrim.isBoolean() && src.getAsBoolean() == targetPrim.getAsBoolean();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return src.isJsonNull() && target.isJsonNull();
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static {
|
||||
gson = Converters.registerDateTime((new GsonBuilder()).registerTypeAdapter(TimeZone.class, new CompatibleTimeZoneTypeAdapter()).registerTypeAdapter(Cipher.class, new CipherTypeAdapter()).addSerializationExclusionStrategy(new SerializeExclusionStragtegy()).setDateFormat(FULL_FORMAT)).create();
|
||||
gsonCloner = Converters.registerDateTime((new GsonBuilder()).registerTypeAdapter(TimeZone.class, new CompatibleTimeZoneTypeAdapter()).registerTypeAdapter(Cipher.class, new CipherTypeAdapter()).setDateFormat(FULL_FORMAT)).create();
|
||||
}
|
||||
|
||||
private static class SerializeExclusionStragtegy implements ExclusionStrategy {
|
||||
public boolean shouldSkipField(FieldAttributes f) {
|
||||
Expose expose = (Expose)f.getAnnotation(Expose.class);
|
||||
return expose != null && !expose.serialize();
|
||||
}
|
||||
|
||||
public boolean shouldSkipClass(Class clazz) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.mitac.cell.utils;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.text.NumberFormat;
|
||||
import java.text.ParseException;
|
||||
import java.util.Locale;
|
||||
|
||||
public class McNumberUtils {
|
||||
public static Integer toInt(Object number) {
|
||||
return toInt(number, (Integer)null);
|
||||
}
|
||||
|
||||
public static Integer toInt(Object number, Integer defaultValue) {
|
||||
Number value = toNumber(number);
|
||||
return value == null ? defaultValue : value.intValue();
|
||||
}
|
||||
|
||||
public static int toInt(boolean isLittleEndian, byte[] value) {
|
||||
return ByteBuffer.wrap(value).order(isLittleEndian ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN).getInt();
|
||||
}
|
||||
|
||||
public static Long toLong(Object number) {
|
||||
return toLong(number, (Long)null);
|
||||
}
|
||||
|
||||
public static Long toLong(Object number, Long defaultValue) {
|
||||
Number value = toNumber(number);
|
||||
return value == null ? defaultValue : value.longValue();
|
||||
}
|
||||
|
||||
public static Float toFloat(Object number) {
|
||||
return toFloat(number, (Float)null);
|
||||
}
|
||||
|
||||
public static Float toFloat(Object number, Float defaultValue) {
|
||||
Number value = toNumber(number);
|
||||
return value == null ? defaultValue : value.floatValue();
|
||||
}
|
||||
|
||||
public static Double toDouble(Object number) {
|
||||
return toNumber(number).doubleValue();
|
||||
}
|
||||
|
||||
public static Double toDouble(Object number, Double defaultValue) {
|
||||
Number value = toNumber(number);
|
||||
return value == null ? defaultValue : value.doubleValue();
|
||||
}
|
||||
|
||||
public static Number toNumber(Object number) {
|
||||
if (number == null) {
|
||||
return null;
|
||||
} else if (number instanceof Number) {
|
||||
return (Number)number;
|
||||
} else if (number instanceof String) {
|
||||
try {
|
||||
return NumberFormat.getNumberInstance(Locale.getDefault()).parse((String)number);
|
||||
} catch (ParseException var2) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] toBytes(int size, boolean isLittleEndian, int value) {
|
||||
return ByteBuffer.allocate(size).order(isLittleEndian ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN).putInt(value).array();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package com.mitac.cell.utils;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.common.io.BaseEncoding;
|
||||
import com.mitac.cell.security.McTextEncryptor;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class McStringUtils {
|
||||
static final String PRINTABLE_ASCII = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
|
||||
|
||||
public static boolean isValid(String text) {
|
||||
return !isNullOrEmpty(text, true);
|
||||
}
|
||||
|
||||
public static boolean isNullOrEmpty(String text) {
|
||||
return isNullOrEmpty(text, true);
|
||||
}
|
||||
|
||||
public static boolean isNullOrEmpty(String text, boolean trimAllWhiteSpace) {
|
||||
if (Strings.isNullOrEmpty(text)) {
|
||||
return true;
|
||||
} else {
|
||||
if (trimAllWhiteSpace) {
|
||||
text = CharMatcher.whitespace().removeFrom(text);
|
||||
}
|
||||
|
||||
return Strings.isNullOrEmpty(text);
|
||||
}
|
||||
}
|
||||
|
||||
public static String trim(String text, char trimBy) {
|
||||
return CharMatcher.is(trimBy).trimFrom(text);
|
||||
}
|
||||
|
||||
public static List convertToIntList(String csvString) {
|
||||
if (csvString == null) {
|
||||
return null;
|
||||
} else {
|
||||
List<Integer> list = new ArrayList();
|
||||
int i = 0;
|
||||
int a = 0;
|
||||
|
||||
for(int n = csvString.length(); i < n; ++i) {
|
||||
switch (csvString.charAt(i)) {
|
||||
case ' ':
|
||||
break;
|
||||
case '!':
|
||||
case '"':
|
||||
case '#':
|
||||
case '$':
|
||||
case '%':
|
||||
case '&':
|
||||
case '\'':
|
||||
case '(':
|
||||
case ')':
|
||||
case '*':
|
||||
case '+':
|
||||
case '-':
|
||||
case '.':
|
||||
case '/':
|
||||
default:
|
||||
throw new AssertionError();
|
||||
case ',':
|
||||
list.add(a);
|
||||
a = 0;
|
||||
break;
|
||||
case '0':
|
||||
a *= 10;
|
||||
break;
|
||||
case '1':
|
||||
a = a * 10 + 1;
|
||||
break;
|
||||
case '2':
|
||||
a = a * 10 + 2;
|
||||
break;
|
||||
case '3':
|
||||
a = a * 10 + 3;
|
||||
break;
|
||||
case '4':
|
||||
a = a * 10 + 4;
|
||||
break;
|
||||
case '5':
|
||||
a = a * 10 + 5;
|
||||
break;
|
||||
case '6':
|
||||
a = a * 10 + 6;
|
||||
break;
|
||||
case '7':
|
||||
a = a * 10 + 7;
|
||||
break;
|
||||
case '8':
|
||||
a = a * 10 + 8;
|
||||
break;
|
||||
case '9':
|
||||
a = a * 10 + 9;
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
public static String toHexString(byte[] bytes) {
|
||||
return bytes == null ? null : BaseEncoding.base16().lowerCase().encode(bytes);
|
||||
}
|
||||
|
||||
public static String toHexStringWithSeparator(byte[] bytes, String separator) {
|
||||
return BaseEncoding.base16().withSeparator(separator, 2).encode(bytes);
|
||||
}
|
||||
|
||||
public static byte[] toBytes(String hexString) {
|
||||
return isNullOrEmpty(hexString) ? null : BaseEncoding.base16().lowerCase().decode(hexString);
|
||||
}
|
||||
|
||||
public static String toEncryptedBytes(String tokenPassword, String tokenSalt, byte[] source) {
|
||||
return (new McTextEncryptor(tokenPassword, tokenSalt)).encrypt(toHexString(source));
|
||||
}
|
||||
|
||||
public static byte[] toDecryptedBytes(String tokenPassword, String tokenSalt, String source) {
|
||||
String hexString = (new McTextEncryptor(tokenPassword, tokenSalt)).decrypt(source);
|
||||
return toBytes(hexString);
|
||||
}
|
||||
|
||||
public static String toEncrypted(String tokenPassword, String tokenSalt, String source) {
|
||||
return (new McTextEncryptor(tokenPassword, tokenSalt)).encrypt(source);
|
||||
}
|
||||
|
||||
public static String toDecrypted(String tokenPassword, String tokenSalt, String source) {
|
||||
return (new McTextEncryptor(tokenPassword, tokenSalt)).decrypt(source);
|
||||
}
|
||||
|
||||
public static String random(int length) {
|
||||
if (length < 0) {
|
||||
return null;
|
||||
} else if (length == 0) {
|
||||
return "";
|
||||
} else {
|
||||
int gap = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~".length();
|
||||
Random random = new Random();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
while(length-- != 0) {
|
||||
sb.append("!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~".charAt(random.nextInt(gap)));
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static String randomNumeric(int length) {
|
||||
if (length < 0) {
|
||||
return null;
|
||||
} else if (length == 0) {
|
||||
return "";
|
||||
} else {
|
||||
Random random = new Random();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
while(length-- != 0) {
|
||||
sb.append(random.nextInt(10));
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static String toBase64(byte[] bytes) {
|
||||
return bytes != null && bytes.length != 0 ? BaseEncoding.base64().omitPadding().encode(bytes) : null;
|
||||
}
|
||||
|
||||
public static byte[] fromBase64(String base64String) {
|
||||
return Strings.isNullOrEmpty(base64String) ? null : BaseEncoding.base64().omitPadding().decode(base64String);
|
||||
}
|
||||
|
||||
public static boolean containsIgnoreCase(String source, String what) {
|
||||
if (!Strings.isNullOrEmpty(source) && !Strings.isNullOrEmpty(what)) {
|
||||
int len = what.length();
|
||||
int max = source.length() - len;
|
||||
|
||||
while(max >= 0) {
|
||||
if (source.regionMatches(true, max--, what, 0, len)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean hasUpperLowerDigit(String text) {
|
||||
Pattern textPattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).+$");
|
||||
return textPattern.matcher(text).matches();
|
||||
}
|
||||
|
||||
public static String stackTrace(Exception ex) {
|
||||
if (ex == null) {
|
||||
return "";
|
||||
} else {
|
||||
StringWriter stringWriter = new StringWriter();
|
||||
ex.printStackTrace(new PrintWriter(stringWriter));
|
||||
return stringWriter.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.mitac.cell.utils;
|
||||
|
||||
import com.google.common.net.UrlEscapers;
|
||||
import java.net.URL;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.Charset;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
public class McUrlUtils {
|
||||
public static String getHostUrl(HttpServletRequest request) {
|
||||
String hostUrl = request.getRequestURL().toString();
|
||||
hostUrl = hostUrl.substring(0, hostUrl.indexOf(request.getRequestURI()));
|
||||
String contextPath = request.getContextPath();
|
||||
if (!McStringUtils.isNullOrEmpty(contextPath)) {
|
||||
hostUrl = hostUrl + contextPath;
|
||||
}
|
||||
|
||||
return hostUrl;
|
||||
}
|
||||
|
||||
public static String getPropertyKey(String key) {
|
||||
if (key.contains(".")) {
|
||||
return key.substring(key.indexOf(".") + 1);
|
||||
} else if (key.contains("[")) {
|
||||
int start = key.indexOf(39) + 1;
|
||||
int last = key.lastIndexOf(39);
|
||||
return key.substring(start, last).trim();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String encode(String name) {
|
||||
name = UrlEscapers.urlPathSegmentEscaper().escape(name);
|
||||
return URLEncoder.encode(name, Charset.defaultCharset());
|
||||
}
|
||||
|
||||
public static URL toUrl(String url) {
|
||||
try {
|
||||
return new URL(url);
|
||||
} catch (Exception var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.mitac.cell.utils;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.common.io.BaseEncoding;
|
||||
import com.mitac.cell.security.McTextEncryptor;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.UUID;
|
||||
import javax.xml.bind.DatatypeConverter;
|
||||
|
||||
public class McUuidUtils {
|
||||
private static final String tokenPassword = "MiDM@MiTAC.com";
|
||||
private static final String tokenSalt = "171891893b5cef2f";
|
||||
public static final McTextEncryptor encryptor = new McTextEncryptor("MiDM@MiTAC.com", "171891893b5cef2f");
|
||||
|
||||
public static byte[] toBytes(UUID uuid) {
|
||||
long hi = uuid.getMostSignificantBits();
|
||||
long lo = uuid.getLeastSignificantBits();
|
||||
return ByteBuffer.allocate(16).putLong(hi).putLong(lo).array();
|
||||
}
|
||||
|
||||
public static String toHexString(UUID uuid) {
|
||||
return uuid.toString().replace("-", "");
|
||||
}
|
||||
|
||||
public static byte[] toOrderedBytes(UUID uuid) {
|
||||
String hexValue = uuid.toString().replace("-", "");
|
||||
return DatatypeConverter.parseHexBinary(hexValue);
|
||||
}
|
||||
|
||||
public static UUID fromString(String hexValue) {
|
||||
byte[] byteUuid = DatatypeConverter.parseHexBinary(hexValue.replace("-", ""));
|
||||
String formattedValue = toStringFromOrderedBytes(byteUuid);
|
||||
return UUID.fromString(formattedValue);
|
||||
}
|
||||
|
||||
public static UUID fromOrderedBytes(byte[] idValue) {
|
||||
return UUID.fromString(toStringFromOrderedBytes(idValue));
|
||||
}
|
||||
|
||||
public static String toStringFromOrderedBytes(byte[] idValue) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for(int i = 0; i < 16; ++i) {
|
||||
byte byteValue = i < idValue.length ? idValue[i] : 0;
|
||||
sb.append(String.format("%02x", byteValue));
|
||||
if (i == 3 || i == 5 || i == 7 || i == 9) {
|
||||
sb.append('-');
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String toBase64String(UUID uuid) {
|
||||
return toBase64String(uuid, false);
|
||||
}
|
||||
|
||||
public static String toBase64String(UUID uuid, boolean omitPadding) {
|
||||
BaseEncoding encoding = BaseEncoding.base64Url();
|
||||
if (omitPadding) {
|
||||
encoding = encoding.omitPadding();
|
||||
}
|
||||
|
||||
return encoding.encode(toOrderedBytes(uuid));
|
||||
}
|
||||
|
||||
public static UUID toUuidFromBase64(String token) {
|
||||
try {
|
||||
return Strings.isNullOrEmpty(token) ? null : UUID.fromString(toStringFromOrderedBytes(BaseEncoding.base64Url().decode(token)));
|
||||
} catch (Exception var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String encrypt(UUID uuid) {
|
||||
try {
|
||||
return encryptor.encrypt(toHexString(uuid));
|
||||
} catch (Exception var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static UUID decrypt(String encryptedUuid) {
|
||||
try {
|
||||
return fromString(encryptor.decrypt(encryptedUuid));
|
||||
} catch (Exception var2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user