Inspiring from GENERATED TALEND CLASS and Reuse in JAVA - java

I would like to get the value of from context in a new [java simple class] by inspiring from the seconde generated [talend class] :
I couldn't get filepath value because TALEND CLASS seems a little bit difficult to me ^^
My new java class
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import sapphire.util.DataSet;
public class LHCM_FX {
public static void main(String[] args) {
// Trying to get filepath here from context as TALEND JAVA GENERATED CLASS DO
String filepath = "C:/Users/Administrator/Desktop/Test/";
System.out.println("xmldataset=" + parseFXFile(filepath+"0.txt").toXML());
}
public static DataSet parseFXFile(String filepath) {
// Something Codes Here
}
TALEND GENERATED CLASS where filepath is declared
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import routines.LHCM_FX_ROUTINE;
import routines.TalendString;
import routines.system.IPersistableRow;
import routines.system.ResumeUtil;
import routines.system.TDieException;
import sapphire.util.DataSet;
public class LHCM_FX {
public final Object obj = new Object();
private Object valueObject = null;
private static final String defaultCharset = Charset.defaultCharset().name();
private static final String utf8Charset = "UTF-8";
private Properties defaultProps = new Properties();
private LHCM_FX.ContextProperties context = new LHCM_FX.ContextProperties();
private final String jobVersion = "0.1";
private final String jobName = "LHCM_FX";
private final String projectName = "CETEMCO";
public Integer errorCode = null;
private String currentComponent = "";
private final Map<String, Long> start_Hash = new HashMap();
private final Map<String, Long> end_Hash = new HashMap();
private final Map<String, Boolean> ok_Hash = new HashMap();
private final Map<String, Object> globalMap = new HashMap();
public final List<String[]> globalBuffer = new ArrayList();
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
private final PrintStream errorMessagePS;
private Exception exception;
public String resuming_logs_dir_path;
public String resuming_checkpoint_path;
public String parent_part_launcher;
private String resumeEntryMethodName;
private boolean globalResumeTicket;
public boolean watch;
public Integer portStats;
public int portTraces;
public String clientHost;
public String defaultClientHost;
public String contextStr;
public String pid;
public String rootPid;
public String fatherPid;
public String fatherNode;
public long startTime;
public boolean isChildJob;
private boolean execStat;
private ThreadLocal threadLocal;
private Properties context_param;
public Map<String, Object> parentContextMap;
public String status;
ResumeUtil resumeUtil;
public LHCM_FX() {
this.errorMessagePS = new PrintStream(new BufferedOutputStream(this.baos));
this.exception = null;
this.resuming_logs_dir_path = null;
this.resuming_checkpoint_path = null;
this.parent_part_launcher = null;
this.resumeEntryMethodName = null;
this.globalResumeTicket = false;
this.watch = false;
this.portStats = null;
this.portTraces = 4334;
this.defaultClientHost = "localhost";
this.contextStr = "Default";
this.pid = "0";
this.rootPid = null;
this.fatherPid = null;
this.fatherNode = null;
this.startTime = 0L;
this.isChildJob = false;
this.execStat = true;
this.threadLocal = new ThreadLocal();
Map threadRunResultMap = new HashMap();
threadRunResultMap.put("errorCode", (Object)null);
threadRunResultMap.put("status", "");
this.threadLocal.set(threadRunResultMap);
this.context_param = new Properties();
this.parentContextMap = new HashMap();
this.status = "";
this.resumeUtil = null;
}
public Object getValueObject() {
return this.valueObject;
}
public void setValueObject(Object valueObject) {
this.valueObject = valueObject;
}
public LHCM_FX.ContextProperties getContext() {
return this.context;
}
public String getExceptionStackTrace() {
if ("failure".equals(this.getStatus())) {
this.errorMessagePS.flush();
return this.baos.toString();
} else {
return null;
}
}
public Exception getException() {
return "failure".equals(this.getStatus()) ? this.exception : null;
}
public void tJavaFlex_1_error(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.end_Hash.put("tJavaFlex_1", System.currentTimeMillis());
this.tJavaFlex_1_onSubJobError(exception, errorComponent, globalMap);
}
public void tLogRow_1_error(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.end_Hash.put("tLogRow_1", System.currentTimeMillis());
this.tJavaFlex_1_onSubJobError(exception, errorComponent, globalMap);
}
public void tLabVantageLIMSCIPostData_1_error(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.end_Hash.put("tLabVantageLIMSCIPostData_1", System.currentTimeMillis());
this.tJavaFlex_1_onSubJobError(exception, errorComponent, globalMap);
}
public void tJavaFlex_1_onSubJobError(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.resumeUtil.addLog("SYSTEM_LOG", "NODE:" + errorComponent, "", String.valueOf(Thread.currentThread().getId()), "FATAL", "", exception.getMessage(), ResumeUtil.getExceptionStackTrace(exception), "");
}
public void tJavaFlex_1Process(Map<String, Object> globalMap) throws LHCM_FX.TalendException {
globalMap.put("tJavaFlex_1_SUBPROCESS_STATE", 0);
boolean execStat = this.execStat;
String iterateId = "";
String currentComponent = "";
try {
String currentMethodName = (new Exception()).getStackTrace()[0].getMethodName();
boolean resumeIt = currentMethodName.equals(this.resumeEntryMethodName);
if (this.resumeEntryMethodName == null || resumeIt || this.globalResumeTicket) {
this.globalResumeTicket = true;
LHCM_FX.row1Struct row1 = new LHCM_FX.row1Struct();
this.ok_Hash.put("tLabVantageLIMSCIPostData_1", false);
this.start_Hash.put("tLabVantageLIMSCIPostData_1", System.currentTimeMillis());
currentComponent = "tLabVantageLIMSCIPostData_1";
int tos_count_tLabVantageLIMSCIPostData_1 = 0;
DataSet dsData_tLabVantageLIMSCIPostData_1 = new DataSet();
dsData_tLabVantageLIMSCIPostData_1.addColumn("sdcid", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("keyid1", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("paramlistid", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("variantid", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("paramtype", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("instrumentfield", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("value", 0);
this.ok_Hash.put("tLogRow_1", false);
this.start_Hash.put("tLogRow_1", System.currentTimeMillis());
currentComponent = "tLogRow_1";
int tos_count_tLogRow_1 = 0;
this.ok_Hash.put("tJavaFlex_1", false);
this.start_Hash.put("tJavaFlex_1", System.currentTimeMillis());
currentComponent = "tJavaFlex_1";
int tos_count_tJavaFlex_1 = 0;
DataSet ds = LHCM_FX_ROUTINE.parseFXFile(this.context.filepath);
int i_tLabVantageLIMSCIPostData_1;
String keyid1;
String instrumentfield;
for(int i = 0; i < ds.getRowCount(); ++i) {
currentComponent = "tJavaFlex_1";
row1.sdcid = ds.getValue(i, "sdcid", "");
row1.keyid1 = ds.getValue(i, "keyid1", "");
row1.paramlistid = ds.getValue(i, "paramlistid", "");
row1.variantid = ds.getValue(i, "variantid", "");
row1.paramtype = ds.getValue(i, "paramtype", "");
row1.instrumentfield = ds.getValue(i, "instrumentfield", "");
row1.value = ds.getValue(i, "value", "");
++tos_count_tJavaFlex_1;
currentComponent = "tLogRow_1";
++tos_count_tLogRow_1;
currentComponent = "tLabVantageLIMSCIPostData_1";
i_tLabVantageLIMSCIPostData_1 = dsData_tLabVantageLIMSCIPostData_1.addRow();
keyid1 = "";
instrumentfield = "";
keyid1 = "sdcid";
instrumentfield = row1.sdcid;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "keyid1";
instrumentfield = row1.keyid1;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "paramlistid";
instrumentfield = row1.paramlistid;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "variantid";
instrumentfield = row1.variantid;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "paramtype";
instrumentfield = row1.paramtype;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "instrumentfield";
instrumentfield = row1.instrumentfield;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "value";
instrumentfield = row1.value;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
++tos_count_tLabVantageLIMSCIPostData_1;
currentComponent = "tJavaFlex_1";
}
this.ok_Hash.put("tJavaFlex_1", true);
this.end_Hash.put("tJavaFlex_1", System.currentTimeMillis());
currentComponent = "tLogRow_1";
this.ok_Hash.put("tLogRow_1", true);
this.end_Hash.put("tLogRow_1", System.currentTimeMillis());
currentComponent = "tLabVantageLIMSCIPostData_1";
String sWarningMessages_tLabVantageLIMSCIPostData_1 = "";
if ("LIMS CI".equals("LIMS CI") && (!dsData_tLabVantageLIMSCIPostData_1.isValidColumn("sdcid") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("keyid1") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("instrumentfield") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("value"))) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + "Error : In 'LIMS CI' case, the columns sdcid, keyid1, instrumentfield and value are mandatory. Please change the component schema.";
}
if ("LIMS CI".equals("Protocol Provider") && (!dsData_tLabVantageLIMSCIPostData_1.isValidColumn("instrumentfield") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("value"))) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + "Error : In 'Protocol Provider' case, the columns instrumentfield and value are mandatory. Please change the component schema.";
}
if (sWarningMessages_tLabVantageLIMSCIPostData_1.equals("")) {
for(i_tLabVantageLIMSCIPostData_1 = 0; i_tLabVantageLIMSCIPostData_1 < dsData_tLabVantageLIMSCIPostData_1.getRowCount(); ++i_tLabVantageLIMSCIPostData_1) {
keyid1 = dsData_tLabVantageLIMSCIPostData_1.getValue(i_tLabVantageLIMSCIPostData_1, "keyid1", "null");
instrumentfield = dsData_tLabVantageLIMSCIPostData_1.getValue(i_tLabVantageLIMSCIPostData_1, "instrumentfield", "null");
if ((!"LIMS CI".equals("LIMS CI") || !keyid1.equals("null")) && !instrumentfield.equals("null")) {
for(int j_tLabVantageLIMSCIPostData_1 = 0; j_tLabVantageLIMSCIPostData_1 < dsData_tLabVantageLIMSCIPostData_1.getColumnCount(); ++j_tLabVantageLIMSCIPostData_1) {
String columnid = dsData_tLabVantageLIMSCIPostData_1.getColumnId(j_tLabVantageLIMSCIPostData_1);
String value = dsData_tLabVantageLIMSCIPostData_1.getValue(i_tLabVantageLIMSCIPostData_1, columnid, "nullvalue");
String message = "";
if ("LIMS CI".equals("LIMS CI") && (columnid.equals("sdcid") || columnid.equals("keyid1") || columnid.equals("instrumentfield")) && (value == null || value.equals("") || value.equals("nullvalue"))) {
message = "Error : Invalid value : The column '" + columnid + "' can not be empty or null.\n";
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.contains(message)) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + message;
}
}
if ("LIMS CI".equals("Protocol Provider")) {
if (!columnid.equals("instrumentfield") && !columnid.equals("value")) {
message = "Error : Invalid column '" + columnid + "'. In 'Protocol Provider' case, only 'instrumentfield' and 'value' columns are accepted.\n";
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.contains(message)) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + message;
}
} else if (columnid.equals("instrumentfield") && (value == null || value.equals("") || value.equals("nullvalue"))) {
message = "Error : Invalid value : The column '" + columnid + "' can not be empty or null.\n";
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.contains(message)) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + message;
}
}
}
}
} else {
dsData_tLabVantageLIMSCIPostData_1.deleteRow(i_tLabVantageLIMSCIPostData_1);
--i_tLabVantageLIMSCIPostData_1;
}
}
}
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.equals("")) {
System.out.println("Invalid data ! You must solve the following problems : ");
System.out.println(sWarningMessages_tLabVantageLIMSCIPostData_1);
}
System.out.println("xmldataset=" + dsData_tLabVantageLIMSCIPostData_1.toXML());
globalMap.put("tLabVantageLIMSCIPostData_1_NB_LINE", dsData_tLabVantageLIMSCIPostData_1.getRowCount());
this.ok_Hash.put("tLabVantageLIMSCIPostData_1", true);
this.end_Hash.put("tLabVantageLIMSCIPostData_1", System.currentTimeMillis());
}
} catch (Exception var22) {
throw new LHCM_FX.TalendException(var22, currentComponent, globalMap, (LHCM_FX.TalendException)null);
} catch (Error var23) {
throw new Error(var23);
}
globalMap.put("tJavaFlex_1_SUBPROCESS_STATE", 1);
}
public static void main(String[] args) {
LHCM_FX LHCM_FXClass = new LHCM_FX();
int exitCode = LHCM_FXClass.runJobInTOS(args);
System.exit(exitCode);
}
public String[][] runJob(String[] args) {
int exitCode = this.runJobInTOS(args);
String[][] bufferValue = new String[][]{{Integer.toString(exitCode)}};
return bufferValue;
}
public int runJobInTOS(String[] args) {
String lastStr = "";
boolean hasContextArg = false;
String[] var7 = args;
int var6 = args.length;
for(int var5 = 0; var5 < var6; ++var5) {
String arg = var7[var5];
if (arg.toLowerCase().contains("--context=")) {
hasContextArg = true;
} else if (arg.equalsIgnoreCase("--context_param")) {
lastStr = arg;
} else if (lastStr.equals("")) {
this.evalParam(arg);
} else {
this.evalParam(lastStr + " " + arg);
lastStr = "";
}
}
if (this.clientHost == null) {
this.clientHost = this.defaultClientHost;
}
if (this.pid == null || "0".equals(this.pid)) {
this.pid = TalendString.getAsciiRandomString(6);
}
if (this.rootPid == null) {
this.rootPid = this.pid;
}
if (this.fatherPid == null) {
this.fatherPid = this.pid;
} else {
this.isChildJob = true;
}
try {
InputStream inContext = LHCM_FX.class.getClassLoader().getResourceAsStream("cetemco/lhcm_fx_0_1/contexts/" + this.contextStr + ".properties");
if (inContext != null) {
this.defaultProps.load(inContext);
inContext.close();
this.context = new LHCM_FX.ContextProperties(this.defaultProps);
} else if (hasContextArg) {
System.err.println("Could not find the context " + this.contextStr);
}
if (!this.context_param.isEmpty()) {
this.context.putAll(this.context_param);
}
this.context.filepath = this.context.getProperty("filepath");
} catch (IOException var12) {
System.err.println("Could not load context " + this.contextStr);
var12.printStackTrace();
}
if (this.parentContextMap != null && !this.parentContextMap.isEmpty() && this.parentContextMap.containsKey("filepath")) {
this.context.filepath = (String)this.parentContextMap.get("filepath");
}
this.resumeEntryMethodName = ResumeUtil.getResumeEntryMethodName(this.resuming_checkpoint_path);
this.resumeUtil = new ResumeUtil(this.resuming_logs_dir_path, this.isChildJob, this.rootPid);
this.resumeUtil.initCommonInfo(this.pid, this.rootPid, this.fatherPid, "CETEMCO", "LHCM_FX", this.contextStr, "0.1");
this.resumeUtil.addLog("JOB_STARTED", "JOB:LHCM_FX", this.parent_part_launcher, String.valueOf(Thread.currentThread().getId()), "", "", "", "", ResumeUtil.convertToJsonText(this.context));
long startUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long endUsedMemory = 0L;
long end = 0L;
this.startTime = System.currentTimeMillis();
this.globalResumeTicket = true;
this.globalResumeTicket = false;
try {
this.errorCode = null;
this.tJavaFlex_1Process(this.globalMap);
this.status = "end";
} catch (LHCM_FX.TalendException var11) {
this.status = "failure";
var11.printStackTrace();
this.globalMap.put("tJavaFlex_1_SUBPROCESS_STATE", -1);
}
this.globalResumeTicket = true;
end = System.currentTimeMillis();
if (this.watch) {
System.out.println(end - this.startTime + " milliseconds");
}
endUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
int returnCode = false;
int returnCode;
if (this.errorCode == null) {
returnCode = this.status != null && this.status.equals("failure") ? 1 : 0;
} else {
returnCode = this.errorCode;
}
this.resumeUtil.addLog("JOB_ENDED", "JOB:LHCM_FX", this.parent_part_launcher, String.valueOf(Thread.currentThread().getId()), "", "" + returnCode, "", "", "");
return returnCode;
}
private void evalParam(String arg) {
if (arg.startsWith("--resuming_logs_dir_path")) {
this.resuming_logs_dir_path = arg.substring(25);
} else if (arg.startsWith("--resuming_checkpoint_path")) {
this.resuming_checkpoint_path = arg.substring(27);
} else if (arg.startsWith("--parent_part_launcher")) {
this.parent_part_launcher = arg.substring(23);
} else if (arg.startsWith("--watch")) {
this.watch = true;
} else {
String keyValue;
if (arg.startsWith("--stat_port=")) {
keyValue = arg.substring(12);
if (keyValue != null && !keyValue.equals("null")) {
this.portStats = Integer.parseInt(keyValue);
}
} else if (arg.startsWith("--trace_port=")) {
this.portTraces = Integer.parseInt(arg.substring(13));
} else if (arg.startsWith("--client_host=")) {
this.clientHost = arg.substring(14);
} else if (arg.startsWith("--context=")) {
this.contextStr = arg.substring(10);
} else if (arg.startsWith("--father_pid=")) {
this.fatherPid = arg.substring(13);
} else if (arg.startsWith("--root_pid=")) {
this.rootPid = arg.substring(11);
} else if (arg.startsWith("--father_node=")) {
this.fatherNode = arg.substring(14);
} else if (arg.startsWith("--pid=")) {
this.pid = arg.substring(6);
} else if (arg.startsWith("--context_param")) {
keyValue = arg.substring(16);
int index = true;
int index;
if (keyValue != null && (index = keyValue.indexOf(61)) > -1) {
this.context_param.put(keyValue.substring(0, index), keyValue.substring(index + 1));
}
}
}
}
public Integer getErrorCode() {
return this.errorCode;
}
public String getStatus() {
return this.status;
}
public class ContextProperties extends Properties {
public String filepath;
public ContextProperties(Properties properties) {
super(properties);
}
public ContextProperties() {
}
public void synchronizeContext() {
if (this.filepath != null) {
this.setProperty("filepath", this.filepath.toString());
}
}
public String getFilepath() {
return this.filepath;
}
}
private class TalendException extends Exception {
private Map<String, Object> globalMap;
private Exception e;
private String currentComponent;
private TalendException(Exception e, String errorComponent, Map<String, Object> globalMap) {
this.globalMap = null;
this.e = null;
this.currentComponent = null;
this.currentComponent = errorComponent;
this.globalMap = globalMap;
this.e = e;
}
public void printStackTrace() {
if (!(this.e instanceof LHCM_FX.TalendException) && !(this.e instanceof TDieException)) {
this.globalMap.put(this.currentComponent + "_ERROR_MESSAGE", this.e.getMessage());
System.err.println("Exception in component " + this.currentComponent);
}
if (!(this.e instanceof TDieException)) {
if (this.e instanceof LHCM_FX.TalendException) {
this.e.printStackTrace();
} else {
this.e.printStackTrace();
this.e.printStackTrace(LHCM_FX.this.errorMessagePS);
LHCM_FX.this.exception = this.e;
}
}
if (!(this.e instanceof LHCM_FX.TalendException)) {
try {
Method[] var4;
int var3 = (var4 = this.getClass().getEnclosingClass().getMethods()).length;
for(int var2 = 0; var2 < var3; ++var2) {
Method m = var4[var2];
if (m.getName().compareTo(this.currentComponent + "_error") == 0) {
m.invoke(LHCM_FX.this, this.e, this.currentComponent, this.globalMap);
break;
}
}
boolean var10000 = this.e instanceof TDieException;
} catch (SecurityException var5) {
this.e.printStackTrace();
} catch (IllegalArgumentException var6) {
this.e.printStackTrace();
} catch (IllegalAccessException var7) {
this.e.printStackTrace();
} catch (InvocationTargetException var8) {
this.e.printStackTrace();
}
}
}
// ............. More More code
}
}
Thank you in advance,

My bad!
I have the parameter filepath inside args of my : MAIN (String[] args)
so filepath = args[4]
Im sorry and thanks anyway :)

Related

Execute command line equivalent to Runtime.getRuntime().exec(cmd); in JNI C

I was developing an app which had requirement to implement root detection logic, so by researching I found some detection logic in JAVA and had implemented following class.
class RootDetection {
public boolean isDeviceRooted() {
return checkForBinary("su") || checkForBinary("busybox") || checkForMaliciousPaths() || checkSUonPath()
|| detectRootManagementApps() || detectPotentiallyDangerousApps() || detectRootCloakingApps()
|| checkForDangerousProps() || checkForRWPaths()
|| detectTestKeys() || checkSuExists();
}
private boolean detectTestKeys() {
String buildTags = android.os.Build.TAGS;
String buildFinger = Build.FINGERPRINT;
String product = Build.PRODUCT;
String hardware = Build.HARDWARE;
String display = Build.DISPLAY;
System.out.println("Java: build: " + buildTags + "\nFingerprint: " + buildFinger + "\n Product: " + product + "\n Hardware: " + hardware + "\nDisplay: " + display);
return (buildTags != null) && (buildTags.contains("test-keys") || buildFinger.contains("genric.*test-keys") || product.contains("generic") || product.contains("sdk") || hardware.contains("goldfish") || display.contains(".*test-keys"));
}
private boolean detectRootManagementApps() {
return detectRootManagementApps(null);
}
private boolean detectRootManagementApps(String[] additionalRootManagementApps) {
ArrayList<String> packages = new ArrayList<>();
packages.addAll(Arrays.asList(knownRootAppsPackages));
if (additionalRootManagementApps != null && additionalRootManagementApps.length > 0) {
packages.addAll(Arrays.asList(additionalRootManagementApps));
}
return isAnyPackageFromListInstalled(packages);
}
private boolean detectPotentiallyDangerousApps() {
return detectPotentiallyDangerousApps(null);
}
private boolean detectPotentiallyDangerousApps(String[] additionalDangerousApps) {
ArrayList<String> packages = new ArrayList<>();
packages.addAll(Arrays.asList(knownDangerousAppsPackages));
if (additionalDangerousApps != null && additionalDangerousApps.length > 0) {
packages.addAll(Arrays.asList(additionalDangerousApps));
}
return isAnyPackageFromListInstalled(packages);
}
private boolean detectRootCloakingApps() {
return detectRootCloakingApps(null);
}
private boolean detectRootCloakingApps(String[] additionalRootCloakingApps) {
ArrayList<String> packages = new ArrayList<>();
packages.addAll(Arrays.asList(knownRootCloakingPackages));
if (additionalRootCloakingApps != null && additionalRootCloakingApps.length > 0) {
packages.addAll(Arrays.asList(additionalRootCloakingApps));
}
return isAnyPackageFromListInstalled(packages);
}
private boolean checkForBinary(String filename) {
for (String path : suPaths) {
String completePath = path + filename;
File f = new File(completePath);
boolean fileExists = f.exists();
if (fileExists) {
return true;
}
}
return false;
}
private boolean checkForMaliciousPaths() {
for (String path : maliciousPaths) {
File f = new File(path);
boolean fileExists = f.exists();
if (fileExists) {
return true;
}
}
return false;
}
private static boolean checkSUonPath() {
for (String pathDir : System.getenv("PATH").split(":")) {
if (new File(pathDir, "su").exists()) {
return true;
}
}
return false;
}
private String[] propsReader() {
InputStream inputstream = null;
try {
inputstream = Runtime.getRuntime().exec("getprop").getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
String propval = "";
try {
propval = new Scanner(inputstream).useDelimiter("\\A").next();
} catch (NoSuchElementException e) {
}
return propval.split("\n");
}
private String[] mountReader() {
InputStream inputstream = null;
try {
inputstream = Runtime.getRuntime().exec("mount").getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
if (inputstream == null) return null;
String propval = "";
try {
propval = new Scanner(inputstream).useDelimiter("\\A").next();
} catch (NoSuchElementException e) {
e.printStackTrace();
}
return propval.split("\n");
}
private boolean isAnyPackageFromListInstalled(List<String> packages) {
PackageManager pm = activity.getPackageManager();
for (String packageName : packages) {
try {
pm.getPackageInfo(packageName, 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
}
}
return false;
}
private boolean checkForDangerousProps() {
final Map<String, String> dangerousProps = new HashMap<>();
dangerousProps.put("ro.debuggable", "1");
dangerousProps.put("ro.secure", "0");
String[] lines = propsReader();
for (String line : lines) {
for (String key : dangerousProps.keySet()) {
if (line.contains(key)) {
String badValue = dangerousProps.get(key);
badValue = "[" + badValue + "]";
if (line.contains(badValue)) {
return true;
}
}
}
}
return false;
}
private boolean checkForRWPaths() {
String[] lines = mountReader();
for (String line : lines) {
String[] args = line.split(" ");
if (args.length < 4) {
continue;
}
String mountPoint = args[1];
String mountOptions = args[3];
for (String pathToCheck : pathsThatShouldNotBeWrtiable) {
if (mountPoint.equalsIgnoreCase(pathToCheck)) {
for (String option : mountOptions.split(",")) {
if (option.equalsIgnoreCase("rw")) {
return true;
}
}
}
}
}
return false;
}
private boolean checkSuExists() {
Process process = null;
try {
process = Runtime.getRuntime().exec(new String[]{"which", "su"});
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
return in.readLine() != null;
} catch (Throwable t) {
return false;
} finally {
if (process != null) process.destroy();
}
}
}
but now to increase security I want to do this root detection logic in native C++ JNI code. I managed to migrate package detection code to JNI C but am not able to find anything regarding these 3 functions
checkForDangerousProps(),checkForRWPaths(),checkSuExists()
these 3 use Runtime.getRuntime().exec which am not able to find. can someone help me in converting this 3 logics to JNI C one from above code? Help would be really appreciated.
Pls guys help.

Twitter API Login Process using Java

I am trying to build a twitter Spring Boot API using 3-legged but, when i was running the code it was showing the error of: HTTP request may not be null.
As, i had tried different method for 4-5 hrs even then, i am unable to resolve the issue for the same.
Every time it was throwing "HTTP request may not be null".
My Controller:
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.HTTP;
import org.json.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
#RestController
public class TwitterController {
#RequestMapping(value = "/twitterLogin", method = RequestMethod.GET)
public ModelAndView linkAuthorization() {
ModelAndView model = new ModelAndView("twitterLogin");
return model;
}
#RequestMapping(value = "/twittersignin", method = RequestMethod.GET)
public ModelAndView twitterLogin() {
ModelAndView model = new ModelAndView("success");
String requestTokenUrl = "https://api.twitter.com/oauth/request_token";
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
RequestOauthHeaderGenerator generator = new RequestOauthHeaderGenerator("http://127.0.0.1:8080/success",
"8gviQnqApIePyzx5Fm84K0jCg", "signatureMethod", "oauthTimestamp", "oauthNounce", "1.0");
String header = generator.generateHeader("POST", requestTokenUrl);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", header);
JSONObject jsonObject = new JSONObject();
jsonObject.put("Authorization", "header");
String header1 = HTTP.toString(jsonObject);
HttpPost httpPost1 = new HttpPost(header1);
StringEntity requestString = new StringEntity("");
httpPost1.setEntity(requestString);
HttpResponse initialRespone = httpClient.execute(httpPost1);
if (initialRespone.getStatusLine().getStatusCode() == 200) {
String initialResult = EntityUtils.toString(initialRespone.getEntity());
if (initialResult != null && initialResult != "") {
JSONObject jsonObjectInitialResult = new JSONObject(initialResult);
TwitterResponseDetails twitterResponseDetails = new TwitterResponseDetails();
String oauthConfirmation = jsonObjectInitialResult.get("oauth_callback_confirmed").toString();
if (oauthConfirmation != null && oauthConfirmation != "" && oauthConfirmation != "false") {
twitterResponseDetails.setOauthConfirmation(oauthConfirmation);
String initialToken = jsonObjectInitialResult.get("oauth_token").toString();
if (initialToken != null && initialToken != "") {
twitterResponseDetails.setToken1(initialToken);
}
String initialSecretToken = jsonObjectInitialResult.get("oauth_token_secret").toString();
if (initialSecretToken != null && initialSecretToken != "") {
twitterResponseDetails.setSecretToken1(initialSecretToken);
}
String authenticationUrl = "https://api.twitter.com/oauth/authenticate?oauth_token="
+ initialToken;
HttpGet httpGetAuthenticationUrl = new HttpGet(authenticationUrl);
HttpResponse intermediateResponse = httpClient.execute(httpGetAuthenticationUrl);
System.out.println("intermediateResponse : " + intermediateResponse);
if (intermediateResponse.getStatusLine().getStatusCode() == 200) {
String intermediateResult = EntityUtils.toString(intermediateResponse.getEntity());
if (intermediateResult != null && intermediateResult != "") {
JSONObject jsonObjectIntermediateResult = new JSONObject(intermediateResult);
String intermediateToken = jsonObjectIntermediateResult.get("oauth_token").toString();
if (intermediateToken != null && intermediateToken != "") {
twitterResponseDetails.setToken2(intermediateToken);
}
String oauthVerifier = jsonObjectInitialResult.get("oauth_verifier").toString();
if (oauthVerifier != null && oauthVerifier != "") {
twitterResponseDetails.setOauthVerifier(oauthVerifier);
}
if (initialToken == intermediateToken) {
String clientRediectUrl = "https://callbackurl?oauth_token=" + intermediateToken
+ "&" + "oauth_verifier=" + oauthVerifier;
HttpGet httpGetClientRedirectUrl = new HttpGet(clientRediectUrl);
HttpResponse clientRedirectResponse = httpClient.execute(httpGetClientRedirectUrl);
if (initialRespone.getStatusLine().getStatusCode() == 200) {
System.out.println("ClientRedirectResponse : " + clientRedirectResponse);
String accessTokenUrl = "https://api.twitter.com/oauth/access_token?oauth_token="
+ intermediateToken + "&" + "oauth_verifier=" + oauthVerifier;
HttpPost httpPostAccesstokenUrl = new HttpPost(accessTokenUrl);
HttpResponse accessTokenResponse = httpClient.execute(httpPostAccesstokenUrl);
if (accessTokenResponse.getStatusLine().getStatusCode() == 200) {
String accessTokenResult = EntityUtils
.toString(accessTokenResponse.getEntity());
if (accessTokenResult != null && accessTokenResult != "") {
JSONObject jsonObjectFinalResult = new JSONObject(accessTokenResult);
String finalToken = jsonObjectFinalResult.get("oauth_token").toString();
if (finalToken != null && finalToken != "") {
twitterResponseDetails.setToken3(finalToken);
}
String finalSecretToken = jsonObjectFinalResult
.get("oauth_token_secret").toString();
if (finalSecretToken != null && finalSecretToken != "") {
twitterResponseDetails.setSecretToken2(finalSecretToken);
}
} else {
System.out.println("Incorrect access token");
}
} else {
System.out.println(" Incorrect Tokens");
}
}
} else {
System.out.println(" Incorrect intermediateResult");
}
} else {
System.out.println(" Incorrect Conformation");
}
} else {
System.out.println("Incorrect InitialResult");
}
}
}
}
} catch (
Exception e) {
e.printStackTrace();
}
return model;
}
}
Header Generator:
import java.math.BigInteger;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
public class RequestOauthHeaderGenerator {
public String callbackUrl;
public String consumerKey;
public String oauthNounce;
public String signatureMethod;
public String oauthTimestamp;
public String oauthVersion;
public RequestOauthHeaderGenerator(String callbackUrl, String consumerKey, String oauthNounce,
String signatureMethod, String oauthTimestamp, String oauthVersion) {
this.callbackUrl = callbackUrl;
this.consumerKey = consumerKey;
this.oauthNounce = getNonce();
this.signatureMethod = "HMAC-SHA1";
this.oauthTimestamp = getTimestamp();
this.oauthVersion = oauthVersion;
}
private static final String oauth_callback = "oauth_callback";
private static final String oauth_consumer_key = "oauth_consumer_key";
private static final String oauth_nonce = "oauth_nonce";
private static final String oauth_signature = "oauth_signature";
private static final String oauth_signature_method = "oauth_signature_method";
private static final String oauth_timestamp = "oauth_timestamp";
private static final String oauth_version = "oauth_version";
private static final String HMAC_SHA1 = "SHA-1";
public String generateHeader(String httpMethod, String url) throws NoSuchAlgorithmException {
StringBuilder base = new StringBuilder();
String baseSignatureString = generateSignatureBaseString(httpMethod, url);
String signature = encryptUsingHmacSHA1(baseSignatureString);
System.out.println(signature);
base.append("OAuth ");
append(base, oauth_callback, callbackUrl);
append(base, oauth_consumer_key, consumerKey);
append(base, oauth_nonce, oauthNounce);
append(base, oauth_signature, signature);
append(base, oauth_signature_method, signatureMethod);
append(base, oauth_timestamp, oauthTimestamp);
base.deleteCharAt(base.length() - 1);
System.out.println("header : " + base.toString());
append(base, "oauth_version", oauthVersion);
System.out.println("base : " + base);
return base.toString();
}
String generateSignatureBaseString(String httpMethod, String url) {
Map<String, String> params = new HashMap<>();
put(params, oauth_callback, callbackUrl);
put(params, oauth_consumer_key, consumerKey);
put(params, oauth_nonce, getNonce());
put(params, oauth_signature_method, signatureMethod);
put(params, oauth_timestamp, getTimestamp());
put(params, oauth_version, oauthVersion);
Map<String, String> sortedParams = params.entrySet().stream().sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
LinkedHashMap::new));
StringBuilder base = new StringBuilder();
sortedParams.entrySet().forEach(entry -> {
base.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
});
base.deleteCharAt(base.length() - 1);
String baseString = httpMethod.toUpperCase() + "&" + encode(url) + "&" + encode(base.toString());
System.out.println("baseString : " + baseString);
return baseString;
}
private static String encryptUsingHmacSHA1(String input) throws NoSuchAlgorithmException {
try {
MessageDigest md = MessageDigest.getInstance(HMAC_SHA1);
byte[] messageDigest = md.digest(input.getBytes(StandardCharsets.UTF_8));
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private static String encode(String value) {
String encoded = "";
try {
encoded = URLEncoder.encode(value, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
String sb = "";
char focus;
for (int i = 0; i < encoded.length(); i++) {
focus = encoded.charAt(i);
if (focus == '*') {
sb += "%2A";
} else if (focus == '+') {
sb += "%20";
} else if (focus == '%' && i + 1 < encoded.length() && encoded.charAt(i + 1) == '7'
&& encoded.charAt(i + 2) == 'E') {
sb += '~';
i += 2;
} else {
sb += focus;
}
}
return sb.toString();
}
private void put(Map<String, String> map, String key, String value) {
map.put(encode(key), encode(value));
}
private void append(StringBuilder builder, String key, String value) {
builder.append(encode(key)).append("=\"").append(encode(value)).append("\",");
}
private String getNonce() {
return UUID.randomUUID().toString().replace("-", "");
}
private String getTimestamp() {
return Math.round((new Date()).getTime() / 1000.0) + "";
}
}

Found some code for serialization of an ItemStack in Bukkit, how to deserialize it?

I've dug up the following code for serializing an ItemStack in bukkit (Minecraft). I've been able to serialize an item in hand with the following:
itemString = ItemStackUtils.deserialize(player.getInventory().getItemInHand());
I can't figure out how to utilize the deserial call however. What I am trying to do is to pull an item from the players hand, serialize it, stick it into a config file, then when the player runs another command... deserialize it and slap it into their inventory. I am fairly certain this class will meet my needs if I just can get the last part working.
public final class ItemStackUtils {
public static String getEnchants(ItemStack i){
List<String> e = new ArrayList<String>();
Map<Enchantment, Integer> en = i.getEnchantments();
for(Enchantment t : en.keySet()) {
e.add(t.getName() + ":" + en.get(t));
}
return StringUtils.join(e, ",");
}
public static String deserialize(ItemStack i){
String[] parts = new String[6];
parts[0] = i.getType().name();
parts[1] = Integer.toString(i.getAmount());
parts[2] = String.valueOf(i.getDurability());
parts[3] = i.getItemMeta().getDisplayName();
parts[4] = String.valueOf(i.getData().getData());
parts[5] = getEnchants(i);
return StringUtils.join(parts, ";");
}
public ItemStack deserial(String p){
String[] a = p.split(";");
ItemStack i = new ItemStack(Material.getMaterial(a[0]), Integer.parseInt(a[1]));
i.setDurability((short) Integer.parseInt(a[2]));
ItemMeta meta = i.getItemMeta();
meta.setDisplayName(a[3]);
i.setItemMeta(meta);
MaterialData data = i.getData();
data.setData((byte) Integer.parseInt(a[4]));
i.setData(data);
if (a.length > 5) {
String[] parts = a[5].split(",");
for (String s : parts) {
String label = s.split(":")[0];
String amplifier = s.split(":")[1];
Enchantment type = Enchantment.getByName(label);
if (type == null)
continue;
int f;
try {
f = Integer.parseInt(amplifier);
} catch(Exception ex) {
continue;
}
i.addEnchantment(type, f);
}
}
return i;
}
}
here it saves & loads the whole NBT
package XXXXXXXXX
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.MaterialData;
import net.minecraft.server.v1_8_R3.MojangsonParseException;
import net.minecraft.server.v1_8_R3.MojangsonParser;
import net.minecraft.server.v1_8_R3.NBTTagCompound;
public class ItemSerialize {
public ItemSerialize() {
}
public static String serialize(ItemStack i) {
String[] parts = new String[7];
parts[0] = i.getType().name();
parts[1] = Integer.toString(i.getAmount());
parts[2] = String.valueOf(i.getDurability());
parts[3] = i.getItemMeta().getDisplayName();
parts[4] = String.valueOf(i.getData().getData());
parts[5] = getEnchants(i);
parts[6] = getNBT(i);
return StringUtils.join(parts, ";");
}
public static String getEnchants(ItemStack i) {
List<String> e = new ArrayList<String>();
Map<Enchantment, Integer> en = i.getEnchantments();
for (Enchantment t : en.keySet()) {
e.add(t.getName() + ":" + en.get(t));
}
return StringUtils.join(e, ",");
}
public static String getLore(ItemStack i) {
List<String> e = i.getItemMeta().getLore();
return StringUtils.join(e, ",");
}
public static String getNBT(ItemStack i) {
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(i);
NBTTagCompound compound = nmsStack.hasTag() ? nmsStack.getTag() : new NBTTagCompound();
return compound.toString();
}
public static ItemStack setNBT(ItemStack i, String NBT) {
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(i);
try {
NBTTagCompound compound = MojangsonParser.parse(NBT);
nmsStack.setTag(compound);
} catch (MojangsonParseException e1) {
e1.printStackTrace();
}
return CraftItemStack.asBukkitCopy(nmsStack);
}
#SuppressWarnings("deprecation")
public static ItemStack deserial(String p) {
String[] a = p.split(";");
ItemStack i = new ItemStack(Material.getMaterial(a[0]), Integer.parseInt(a[1]));
i.setDurability((short) Integer.parseInt(a[2]));
ItemMeta meta = i.getItemMeta();
meta.setDisplayName(a[3]);
i.setItemMeta(meta);
MaterialData data = i.getData();
data.setData((byte) Integer.parseInt(a[4]));
i.setData(data);
if (!a[6].isEmpty()) {
i = setNBT(i, a[6]);
}
if (!a[5].isEmpty()) {
String[] parts = a[5].split(",");
for (String s : parts) {
String label = s.split(":")[0];
String amplifier = s.split(":")[1];
Enchantment type = Enchantment.getByName(label);
if (type == null)
continue;
int f;
try {
f = Integer.parseInt(amplifier);
} catch (Exception ex) {
continue;
}
i.addUnsafeEnchantment(type, f);
}
}
return i;
}
}
ItemStack rItem = ItemStackUtils.deserial(itemString);

After reading xml file trying to send mail

I am trying to read the xml file and trying to send the mail.
here is the xml code
<?xml version="1.0" encoding="UTF-8"?><xml>
<u_incident_task>
<description>messafe</description>
<priority>1</priority>
<number>12345</number>
<u_task_incident_service_ci>A</u_task_incident_service_ci>
</u_incident_task>
<u_incident_task>
<description>messafe</description>
<priority>3</priority>
<number>123456</number>
<u_task_incident_service_ci>A</u_task_incident_service_ci>
</u_incident_task>
</xml>
so when ever Priority is 1 i need to send mail. currently my below code is working and able to send.
But when ever Priority is updated from 3 to 1 mail is not able to send. may be the reason i am storing all the number in array since i dont want to send mail repeatedly. so i stored the numbers in array so that i can be sent only once. so while i am storing the numbers if any Priority is updated to 1 mail is not working.
But when record is created with 1 mail i sent but if we updated the existing priority from 3 to 1 it not workin. complete working code is here. can any one help what i missed in logic pls?
complete code here.
Incidentreport2000.java
package com.asn.model;
import java.awt.Desktop;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.asn.model.incident200;
import com.asn.model.incident1;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import javax.mail.Message;
import javax.mail.MessagingException;import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
public class incidentreport2000 implements Runnable {
List<String> number1 = new ArrayList<String>();
public incidentreport2000(){
}
public void run(){
for(int i=1;i>0;i++){
try{
Thread.sleep(9600);
List<incident1> incident1List = new ArrayList<incident1>();
List<incident200> incident200List = new ArrayList<incident200>();
FileWriter fw =null;
BufferedWriter bw=null;
String Path = "C:\\Users";
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
InputStream input = null;
String address ="C:\\Users" ;
String localFileName = "\\file.xml";
try {
File fXmlFile = new File(Path + "\\file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList incident1NodeList = doc.getElementsByTagName("u_incident_task");
for (int temp = 0; temp < incident1NodeList.getLength(); temp++) {
Node varNode = incident1NodeList.item(temp);
if (varNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) varNode;
NodeList u_task_incident_service_ciList = eElement.getElementsByTagName
("u_task_incident_service_ci");
NodeList varsionList = eElement.getElementsByTagName("priority");
NodeList numberList = eElement.getElementsByTagName("number");
NodeList descriptionList = eElement.getElementsByTagName("description");
/* Node u_task_incident_service_ciNode =
u_task_incident_service_ciList.item(0);
Node priorityNode = varsionList.item(0);*/
Node u_task_incident_service_ciNode =
u_task_incident_service_ciList.item(0);
Node priorityNode = varsionList.item(0);
Node numberNode = numberList.item(0);
Node descriptionNode = descriptionList.item(0);
if (u_task_incident_service_ciNode.getNodeType() == Node.ELEMENT_NODE
&& priorityNode.getNodeType() ==
Node.ELEMENT_NODE) {
Element u_task_incident_service_ciElement = (Element)
u_task_incident_service_ciNode;
Element priorityElement = (Element) priorityNode;
Element numberElement = (Element) numberNode;
Element descriptionElement = (Element) descriptionNode;
incident1 incident1 = new incident1(
u_task_incident_service_ciElement.getTextContent(),
priorityElement.getTextContent());
incident1List.add(incident1);
incident200 incident200 = new incident200(
u_task_incident_service_ciElement.getTextContent(),
priorityElement.getTextContent(),numberElement.getTextContent (),descriptionElement.getTextContent());
incident200List.add(incident200);
}
}
// fw = new FileWriter(file.getAbsoluteFile());
// bw = new BufferedWriter(fw);
}
} catch (Exception e) {
e.printStackTrace();
}
Map<incident1, Integer> count = new HashMap<incident1, Integer>();
for (incident1 c : incident1List)
if (!count.containsKey(c))
count.put(c, Collections.frequency(incident1List, c));
List<String> prioritys = getprioritys(count);
List<String> u_task_incident_service_cis = getu_task_incident_service_cis(count);
Map<incident200, Integer> count1 = new HashMap<incident200, Integer>();
for (incident200 c1 : incident200List)
if (!count1.containsKey(c1))
count1.put(c1, Collections.frequency(incident200List, c1));
List<String> number = getnumber(count1);
List<String> description = getdescription(count1);
List<String> prioritys1 = getprioritys1(count1);
List<String> u_task_incident_service_cis1 = getu_task_incident_service_cis1(count1);
for (String v2 : prioritys1 ) {
if (v2 =="P1" ){
for (String n2 : number ) {
System.out.println(number);
if (!number1.contains(n2)) {
for (String d : description){
for (String m3 : u_task_incident_service_cis1){
if (m3 == "A"){
getCountu_task_incident_service_cis1( m3,prioritys1,n2,d, count1);
}
if (m3 == "B"){
getCountu_task_incident_service_cis1( m3,prioritys1,n2,d, count1);
}
}} number1.add(n2);
}}
}}
}catch(Exception e){}
}
}
private static List<String> getu_task_incident_service_cis(Map<incident1, Integer>
count) {
List<String> u_task_incident_service_cis = new ArrayList<String>();
for (Map.Entry<incident1, Integer> ent : count.entrySet())
if (!u_task_incident_service_cis.contains(ent.getKey
().getu_task_incident_service_ci()))
u_task_incident_service_cis.add(ent.getKey().getu_task_incident_service_ci
());
System.out.println(u_task_incident_service_cis);
if(!u_task_incident_service_cis.contains("A"))
u_task_incident_service_cis.add("A");
return u_task_incident_service_cis;
}
private static List<String> getu_task_incident_service_cis1(Map<incident200, Integer>
count) {
List<String> u_task_incident_service_cis1 = new ArrayList<String>();
for (Map.Entry<incident200, Integer> ent : count.entrySet())
if (!u_task_incident_service_cis1.contains(ent.getKey
().getu_task_incident_service_ci()))
u_task_incident_service_cis1.add(ent.getKey().getu_task_incident_service_ci
());
System.out.println(u_task_incident_service_cis1+"NewCIS");
if(!u_task_incident_service_cis1.contains("BIRSD"))
u_task_incident_service_cis1.add("BIRSD");
return u_task_incident_service_cis1;
}
private static String getNumOfu_task_incident_service_cis(String
u_task_incident_service_ci, List<String> prioritys,
Map<incident1, Integer>
count) {
StringBuilder builder = new StringBuilder();
for (String v : prioritys) {
Integer cnt = count.get(new incident1(u_task_incident_service_ci, v));
if (cnt == null) {
cnt = 0;
}
}
return builder.toString();
}
private static String getCountu_task_incident_service_cis1(String
u_task_incident_service_ci, List<String> prioritys1, String number,String description,
Map<incident200, Integer>
count1) {
StringBuilder builder1 = new StringBuilder();
List<String> ARRAY = new ArrayList<>();
for (String v : prioritys1) {
if ( v == "P1") {
Integer cnt1 = count1.get(new incident200(u_task_incident_service_ci, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
}
else
if (cnt1 !=0){
cnt1 = 1;
if (!ARRAY.contains(number)) {
mail1 (u_task_incident_service_ci,v,number,description);
ARRAY.add(number);
}
}}
else
if ( v == "P2") {
Integer cnt1 = count1.get(new incident200(u_task_incident_service_ci, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
}
else
if (cnt1 !=0){
if (!ARRAY.contains(number)) {
mail1(u_task_incident_service_ci,v,number,description);
ARRAY.add(number);
}}
}}
return number;
}
private static List<String> getprioritys(Map<incident1, Integer> count) {
List<String> prioritys = new ArrayList<String>();
for (Map.Entry<incident1, Integer> ent : count.entrySet())
if (!prioritys.contains(ent.getKey().getpriority()))
prioritys.add(ent.getKey().getpriority());
Collections.sort(prioritys);
return prioritys;
}
private static List<String> getprioritys1(Map<incident200, Integer> count) {
List<String> prioritys1 = new ArrayList<String>();
for (Map.Entry<incident200, Integer> ent : count.entrySet())
if (!prioritys1.contains(ent.getKey().getpriority()))
prioritys1.add(ent.getKey().getpriority());
;
//Collections.sort(prioritys);
System.out.println("check1");
return prioritys1;
}
private static List<String> getnumber(Map<incident200, Integer> count) {
List<String> number = new ArrayList<String>();
for (Map.Entry<incident200, Integer> ent : count.entrySet())
if (!number.contains(ent.getKey().getnumber()))
number.add(ent.getKey().getnumber());
return number;
}
private static List<String> getdescription(Map<incident200, Integer> count) {
List<String> description = new ArrayList<String>();
for (Map.Entry<incident200, Integer> ent : count.entrySet())
if (!description.contains(ent.getKey().getdescription()))
description.add(ent.getKey().getdescription());
return description;
}
public static void mail1(String Email,String v,String n, String d) {
System.out.println(Email);
System.out.println(v);
final String username = "mailid";
final String password = "password";
//w2011.kpnnl.local
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
//props.put("mail.transport.protocol","smtp");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse
("toaddress"));
message.setSubject("Priority:"+v+": "+n+"Incident has bee raised for the team"+Email);
message.setText("messager,"
);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws IOException {
incidentreport2000 mrt = new incidentreport2000();
Thread t = new Thread(mrt);
t.start();
String Path = "C:\\Users";
List<String> number1 = new ArrayList<String>();
}
}
incident200.java
package com.asn.model;
public class incident200 {
private String u_task_incident_service_ci;
private String priority;
private String number;
private String description;
public incident200(String u_task_incident_service_ci, String priority, String number,String description ) {
super();
if (u_task_incident_service_ci.equals("A"))
{ String Team= "A";
this.u_task_incident_service_ci = Team;}
else
this.u_task_incident_service_ci = u_task_incident_service_ci;
if (priority.equals("1"))
{ String priority1 = "P1";
this.priority = priority1;}
else
if (priority.equals("3"))
{ String priority3 = "P3";
this.priority = priority3;}
else
if (priority.equals("4"))
{ String priority4 = "P3";
this.priority = priority4;}
else
if (priority.equals("5"))
{ String priority5 = "P3";
this.priority = priority5;}
else
if (priority.equals("2"))
{ String priority2 = "P2";
this.priority = priority2;}
else
this.priority = priority;
this.number = number;
this.description = description;
}
public String getu_task_incident_service_ci() {
return u_task_incident_service_ci;
}
public void setu_task_incident_service_ci(String u_task_incident_service_ci) {
this.u_task_incident_service_ci = u_task_incident_service_ci;
}
public String getpriority() {
return priority;
}
public void setpriority(String priority) {
this.priority = priority;
}
public String getnumber() {
return number;
}
public void setnumber(String number) {
this.number = number;
}
public String getdescription() {
return description;
}
public void setdescription(String description) {
this.description = description;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((u_task_incident_service_ci == null) ? 0 : u_task_incident_service_ci.hashCode());
result = prime * result + ((priority == null) ? 0 : priority.hashCode());
result = prime * result + ((number == null) ? 0 : number.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
incident200 other = (incident200) obj;
if (u_task_incident_service_ci == null) {
if (other.u_task_incident_service_ci != null)
return false;
} else if (!u_task_incident_service_ci.equals(other.u_task_incident_service_ci))
return false;
if (priority == null) {
if (other.priority != null)
return false;
} else if (!priority.equals(other.priority))
return false;
if (number == null) {
if (other.number != null)
return false;
} else if (!number.equals(other.number))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
return true;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("incident99 [u_task_incident_service_ci=");
builder.append(u_task_incident_service_ci);
builder.append(", priority1=");
builder.append(priority);
builder.append(", number=");
builder.append(number);
builder.append(", description=");
builder.append(description);
builder.append("]");
return builder.toString();
}
}
Incident1.java
package com.asn.model;
public class incident1 {
private String u_task_incident_service_ci;
private String priority;
public incident1(String u_task_incident_service_ci, String priority) {
super();
if (u_task_incident_service_ci.equals("A"))
{ String Team= "A";
this.u_task_incident_service_ci = Team;}
else
this.u_task_incident_service_ci = u_task_incident_service_ci;
if (priority.equals("1"))
{ String priority1 = "P1";
this.priority = priority1;}
else
if (priority.equals("3"))
{ String priority3 = "P3";
this.priority = priority3;}
else
this.priority = priority;
}
public String getu_task_incident_service_ci() {
return u_task_incident_service_ci;
}
public void setu_task_incident_service_ci(String u_task_incident_service_ci) {
this.u_task_incident_service_ci = u_task_incident_service_ci;
}
public String getpriority() {
return priority;
}
public void setpriority(String priority) {
this.priority = priority;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((u_task_incident_service_ci == null) ? 0 : u_task_incident_service_ci.hashCode());
result = prime * result + ((priority == null) ? 0 : priority.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
incident1 other = (incident1) obj;
if (u_task_incident_service_ci == null) {
if (other.u_task_incident_service_ci != null)
return false;
} else if (!u_task_incident_service_ci.equals(other.u_task_incident_service_ci))
return false;
if (priority == null) {
if (other.priority != null)
return false;
} else if (!priority.equals(other.priority))
return false;
return true;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("incident1 [u_task_incident_service_ci=");
builder.append(u_task_incident_service_ci);
builder.append(", priority=");
builder.append(priority);
builder.append("]");
return builder.toString();
}
}
This code is rather ... peculiar. Looking at one method:
private static String
getNumOfu_task_incident_service_cis(String u_task_incident_service_ci,
List<String> prioritys,
Map<incident1, Integer> count) {
StringBuilder builder = new StringBuilder();
for (String v : prioritys) {
Integer cnt = count.get(new incident1(u_task_incident_service_ci, v));
if (cnt == null) {
cnt = 0;
}
}
return builder.toString();
}
Several "count" values are obtained from the Map, but the StringBuilder happily remains unchanged; the method always returns "".
Another method:
private static String
getCountu_task_incident_service_cis1( ..., String number,... ){
//...
if ( v == "P1") {
Integer cnt1 = count1.get(new incident200(u_task_incident_service_ci, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
} else
if (cnt1 != 0){
cnt1 = 1;
//...
return number;
}
Here, cnt1 is set to 0 or 1, but not used later on within the same if statement. And the return value is number, a String parameter. So - what's the point?
public incident200(String u_task_incident_service_ci,
String priority, String number,String description ) {
super();
if (u_task_incident_service_ci.equals("A")){
String Team= "A";
this.u_task_incident_service_ci = Team;}
else
this.u_task_incident_service_ci = u_task_incident_service_ci;
What's the purpose of this complication? A single statement would be sufficient:
this.u_task_incident_service_ci = u_task_incident_service_ci;
I regret that I can only point out why this code may be difficult to understand. Cleaning up the code might be a good start towards finding the bug.
Later
If method getCountu_task_incident_service_cis1 should send emails, it does so for priorities P1 and P2 only:
for (String v : prioritys1) {
if ( v == "P1") {
// ...
} else
if ( v == "P2") {
//...
}
}
Moreover, method run contains
for (String v2 : prioritys1 )
if (v2 =="P1" ){
// some code...
}
}
Do you expect that any other priority is ever sent?

Accessing Java Class/function from CFML script

I want to access some Java class and function from within a CFML script (I'm total noob in Java):
<cfscript>
passwordutils = createObject("java","coldfusion.util.PasswordUtils");
newPass = passwordutils.encryptPassword("p455w0rd");
</cfscript>
<cfoutput>#newPass#</cfoutput>
Getting the following error:
The Java class I want to use is the one below (in coldfusion.util.PasswordUtils):
package coldfusion.util;
import coldfusion.archivedeploy.ArchiveDeployServiceImpl;
import coldfusion.flex.FlexAssemblerService;
import coldfusion.log.CFLogs;
import coldfusion.log.Logger;
import coldfusion.lucene.SolrServiceImpl;
import coldfusion.mail.MailSpooler;
import coldfusion.monitor.MonitoringServiceImpl;
import coldfusion.runtime.ApplicationException;
import coldfusion.runtime.CFPage;
import coldfusion.runtime.RuntimeServiceImpl;
import coldfusion.runtime.Struct;
import coldfusion.scheduling.CronServiceImpl;
import coldfusion.security.SecurityManager;
import coldfusion.security.SecurityUtils;
import coldfusion.server.SecurityService;
import coldfusion.server.ServiceException;
import coldfusion.server.ServiceFactory;
import coldfusion.server.ServiceRuntimeException;
import coldfusion.sql.Executive;
import coldfusion.tagext.io.FileUtils;
import coldfusion.wddx.Base64Encoder;
import coldfusion.xml.rpc.XmlRpcServiceImpl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Observable;
import java.util.Observer;
import java.util.Properties;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class PasswordUtils
extends Observable
{
private static final char PADCHAR = '#';
private static final String DESALGORITHM = "DESede";
private static final String AES_CBC_PKCS5_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String SEEDFILE = "seed.properties";
private static final String BASEENCODING = "Base64";
public static final String SEED = "seed";
public static final String ALGORITHM = "algorithm";
public static final String CURRENT_ALGORITHM = "AES/CBC/PKCS5Padding";
public static final int FORAES_START_MAJOR_VERSION = 9;
public static final int FORAES_START_MINOR_VERSION = 5;
private static String ROOTDIR;
private static String SEEDFILEPATH;
private static PasswordUtils instance = null;
private String seedValue;
private Properties seedProperties;
private static File seedFileObj;
public static PasswordUtils getInstance(String rootDir)
throws ServiceException
{
if (instance == null)
{
ROOTDIR = rootDir;
SEEDFILEPATH = ROOTDIR + File.separatorChar + "lib" + File.separatorChar + "seed.properties";
instance = new PasswordUtils();
}
return instance;
}
public static PasswordUtils getInstance()
{
return instance;
}
private PasswordUtils()
throws ServiceException
{
this.seedProperties = new Properties();
loadSeed();
}
private void loadSeed()
throws ServiceException
{
seedFileObj = new File(SEEDFILEPATH);
FileInputStream finput = null;
try
{
finput = new FileInputStream(seedFileObj);
this.seedProperties.load(finput);
try
{
finput.close();
}
catch (Throwable t) {}
seed = this.seedProperties.getProperty("seed");
}
catch (Throwable t)
{
if (seedFileObj.exists()) {
throw new ServiceException(t);
}
}
finally
{
try
{
finput.close();
}
catch (Throwable t) {}
}
String seed;
String algoValue = this.seedProperties.getProperty("algorithm");
if ((seed != null) && (algoValue != null) && (seed.length() > 0) && (algoValue.length() > 0))
{
this.seedValue = seed;
if (!algoValue.equalsIgnoreCase("AES/CBC/PKCS5Padding")) {
throw new SeedException();
}
}
else
{
throw new SeedException();
}
}
public void setSeed(String seedVal)
throws Exception
{
if (seedVal != null)
{
String digest = SecurityUtils.hash(seedVal, "SHA-256", "", "");
seedVal = digest.substring(0, 16);
}
else
{
throw new RuntimeException("Seed cannot be null");
}
if (seedVal.equals(this.seedValue)) {
return;
}
this.seedValue = seedVal;
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
PasswordUtils.this.seedProperties.setProperty("seed", PasswordUtils.this.seedValue);
PasswordUtils.this.storeSeedProperties();
return null;
}
});
setChanged();
notifyObservers(this.seedValue);
}
public synchronized void addObserver(Observer o)
{
if (o == null) {
throw new NullPointerException();
}
if ((!(o instanceof RuntimeServiceImpl)) && (!(o instanceof SolrServiceImpl)) && (!(o instanceof SecurityManager)) && (!(o instanceof Executive)) && (!(o instanceof FlexAssemblerService)) && (!(o instanceof CronServiceImpl)) && (!(o instanceof MonitoringServiceImpl)) && (!(o instanceof MailSpooler)) && (!(o instanceof XmlRpcServiceImpl)) && (!(o instanceof ArchiveDeployServiceImpl))) {
throw new SeedException();
}
super.addObserver(o);
o.update(instance, this.seedValue);
}
public static String reEncryptWithNewSeed(String encryptedStr, String oldSeed, String newSeed, String oldAlgoValue, int majorVersion, int minorVersion)
{
return reEncryptWithNewSeed(encryptedStr, oldSeed, newSeed, false, oldAlgoValue, majorVersion, minorVersion);
}
public static String reEncryptWithNewSeed(String encryptedStr, String oldSeed, String newSeed, boolean noEncodingForDecryption, String oldAlgoValue, int majorVersion, int minorVersion)
{
if ((encryptedStr == null) || ((encryptedStr != null) && (encryptedStr.equals("")))) {
return encryptedStr;
}
if (majorVersion == 0)
{
PasswordUtils tmp31_28 = instance;tmp31_28.getClass();throw new SeedException(tmp31_28);
}
if (isAESS(majorVersion, minorVersion))
{
if ((oldAlgoValue != null) && (oldAlgoValue.length() > 0))
{
if ((oldAlgoValue.equalsIgnoreCase("AES/CBC/PKCS5Padding")) && (oldSeed.equals(newSeed))) {
return encryptedStr;
}
if (oldAlgoValue.equalsIgnoreCase("AES/CBC/PKCS5Padding")) {
return encryptWithAES_CBC_PKCS5(decryptWithAES_CBC_PKCS5(encryptedStr, oldSeed), newSeed);
}
}
else
{
PasswordUtils tmp110_107 = instance;tmp110_107.getClass();throw new SeedException(tmp110_107);
}
}
else {
return encryptWithAES_CBC_PKCS5(decryptWith3DES(encryptedStr, oldSeed, noEncodingForDecryption), newSeed);
}
return encryptedStr;
}
public static String reEncryptForSM(String encryptedStr, String oldSeed, String newSeed)
{
if ((encryptedStr == null) || ((encryptedStr != null) && (encryptedStr.equals("")))) {
return encryptedStr;
}
if ((oldSeed != null) && (oldSeed.equals(newSeed))) {
return encryptedStr;
}
return encryptWith3DES(decryptWithAES_CBC_PKCS5(encryptedStr, oldSeed), newSeed);
}
public static String reEncryptWithNewSeed(String encryptedStr, String oldSeed, String newSeed)
{
if ((encryptedStr == null) || ((encryptedStr != null) && (encryptedStr.equals("")))) {
return encryptedStr;
}
if ((oldSeed != null) && (oldSeed.equals(newSeed))) {
return encryptedStr;
}
return encryptWithAES_CBC_PKCS5(decryptWithAES_CBC_PKCS5(encryptedStr, oldSeed), newSeed);
}
public static String decryptPassword(String encryptedPassword, String seedval, String algoValue)
{
if ((encryptedPassword == null) || ((encryptedPassword != null) && (encryptedPassword.equals("")))) {
return encryptedPassword;
}
if (seedval == null) {
throw new RuntimeException("Seed passed for encryption in null.");
}
String pwd = null;
if ((algoValue != null) && (algoValue.length() > 0)) {
if (algoValue.equalsIgnoreCase("AES/CBC/PKCS5Padding"))
{
pwd = decryptWithAES_CBC_PKCS5(encryptedPassword, seedval);
}
else
{
CFLogs.SERVER_LOG.error("Unknown Algorithm Specified."); PasswordUtils
tmp79_76 = instance;tmp79_76.getClass();throw new UnknownAlgorithmException(tmp79_76);
}
}
return pwd;
}
public static String decryptPassword(String encryptedPassword, String seedval)
{
if ((encryptedPassword == null) || ((encryptedPassword != null) && (encryptedPassword.equals("")))) {
return encryptedPassword;
}
if (seedval == null) {
throw new RuntimeException("Seed passed for encryption in null.");
}
String pwd = null;
pwd = decryptWithAES_CBC_PKCS5(encryptedPassword, seedval);
return pwd;
}
public static String encryptPassword(String p, String seedval)
{
if ((p == null) || ((p != null) && (p.equals("")))) {
return p;
}
if (seedval == null) {
throw new RuntimeException("Seed passed for encryption in null.");
}
return encryptWithAES_CBC_PKCS5(p, seedval);
}
public static String encryptWith3DES(String p, String seedval)
{
String secKey = CFPage.generate3DesKey(seedval);
return CFPage.Encrypt(p, secKey, "DESede", "Base64");
}
private static String decryptWith3DES(String encryptedPassword, String seedval, boolean noEncodingForDecryption)
{
String secKey = CFPage.generate3DesKey(seedval);
String pwd;
String pwd;
if (noEncodingForDecryption) {
pwd = CFPage.Decrypt(encryptedPassword, secKey, "DESede");
} else {
pwd = CFPage.Decrypt(encryptedPassword, secKey, "DESede", "Base64");
}
return pwd;
}
private static String decryptWithAES_CBC_PKCS5(String encryptedPassword, String seedval)
{
String secKey = generateAesKey(seedval);
return CFPage.Decrypt(encryptedPassword, secKey, "AES/CBC/PKCS5Padding", "Base64");
}
private static String decryptWithAES_CBC_PKCS5(String encryptedPassword, String seedval, String enc)
{
String secKey = generateAesKey(seedval);
if ((enc != null) && (enc.length() > 0)) {
return CFPage.Decrypt(encryptedPassword, secKey, "AES/CBC/PKCS5Padding", enc);
}
return CFPage.Decrypt(encryptedPassword, secKey, "AES/CBC/PKCS5Padding", "Base64");
}
private static String encryptWithAES_CBC_PKCS5(String p, String seedval)
{
String secKey = generateAesKey(seedval);
return CFPage.Encrypt(p, secKey, "AES/CBC/PKCS5Padding", "Base64");
}
private static String encryptWithAES_CBC_PKCS5(String p, String seedval, String enc)
{
String secKey = generateAesKey(seedval);
if ((enc != null) && (enc.length() > 0)) {
return CFPage.Encrypt(p, secKey, "AES/CBC/PKCS5Padding", enc);
}
return CFPage.Encrypt(p, secKey, "AES/CBC/PKCS5Padding", "Base64");
}
private static String generateAesKey(String seed)
{
if ((seed == null) || ((seed != null) && (seed.length() == 0)))
{
PasswordUtils tmp22_19 = instance;tmp22_19.getClass();throw new SeedException(tmp22_19);
}
byte[] seedBytes = null;
try
{
seedBytes = seed.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e)
{
seedBytes = seed.getBytes();
}
int seedLen = seedBytes.length;
seedBytes = Arrays.copyOf(seedBytes, 16);
if (seedLen < 16) {
for (int i = seedLen; i < 16; i++) {
seedBytes[i] = 35;
}
}
SecretKey secretKey = new SecretKeySpec(seedBytes, "AES");
return Base64Encoder.encode(secretKey.getEncoded());
}
private final void storeSeedProperties()
{
FileOutputStream foutput = null;
try
{
foutput = new FileOutputStream(SEEDFILEPATH);
this.seedProperties.store(foutput, null);
if (foutput != null) {
try
{
foutput.close();
}
catch (Exception e)
{
CFLogs.SERVER_LOG.error(e);
}
}
try
{
FileUtils.setUnixModes(SEEDFILEPATH, 600);
}
catch (Exception e)
{
CFLogs.SERVER_LOG.error(e);
}
}
catch (Exception ex)
{
throw new ServiceRuntimeException(ex);
}
finally
{
if (foutput != null) {
try
{
foutput.close();
}
catch (Exception e)
{
CFLogs.SERVER_LOG.error(e);
}
}
}
}
public static FastHashtable loadSeedForMigration(String filePath)
throws ServiceException
{
ServiceFactory.getSecurityService().authenticateAdmin();
FastHashtable struct = Struct.StructNew();
Properties props = new Properties();
if (filePath == null) {
return struct;
}
File seedFile = new File(filePath);
if ((seedFile != null) && (!seedFile.exists())) {
return struct;
}
try
{
if ((seedFileObj != null) && (seedFile != null) && (seedFileObj.getCanonicalPath().equalsIgnoreCase(seedFile.getCanonicalPath()))) {
return struct;
}
}
catch (IOException e)
{
CFLogs.SERVER_LOG.error(e);
}
FileInputStream finput = null;
try
{
finput = new FileInputStream(seedFile);
props.load(finput);
try
{
finput.close();
}
catch (Throwable t)
{
CFLogs.SERVER_LOG.error(t);
}
if (props == null) {
return struct;
}
}
catch (Throwable t) {}finally
{
try
{
finput.close();
}
catch (Throwable t)
{
CFLogs.SERVER_LOG.error(t);
}
}
String seed = props.getProperty("seed");
String algoValue = props.getProperty("algorithm");
if ((seed != null) && (seed.length() > 0)) {
struct.put("seed", seed);
}
if ((algoValue != null) && (algoValue.length() > 0)) {
struct.put("algorithm", algoValue);
}
return struct;
}
public static boolean isAESS(int majorVersion, int minorVersion)
{
if ((majorVersion > 9) || ((majorVersion == 9) && (minorVersion == 5))) {
return true;
}
return false;
}
public static String encryptWithEncoding(String p, String seedval, String enc)
{
if ((p == null) || ((p != null) && (p.equals("")))) {
return p;
}
if (seedval == null) {
throw new RuntimeException("Seed passed for encryption in null.");
}
return encryptWithAES_CBC_PKCS5(p, seedval, enc);
}
public static String decryptWithEncoding(String encryptedPassword, String seedval, String enc)
{
if ((encryptedPassword == null) || ((encryptedPassword != null) && (encryptedPassword.equals("")))) {
return encryptedPassword;
}
if (seedval == null) {
throw new RuntimeException("Seed passed for encryption in null.");
}
String pwd = null;
pwd = decryptWithAES_CBC_PKCS5(encryptedPassword, seedval, enc);
return pwd;
}
public class SeedException
extends ApplicationException
{
private static final long serialVersionUID = 1L;
public SeedException() {}
}
public class UnknownAlgorithmException
extends ApplicationException
{
private static final long serialVersionUID = 1L;
public UnknownAlgorithmException() {}
}
}
public static String encryptPassword(String p, String seedval)
I think you forgot the seedval argument. Does this work?
newPass = passwordutils.encryptPassword("p455w0rd","thisisnotaseed");

Categories

Resources