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");
Related
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 :)
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.
I've a problem with hibernate. I'm trying to save an object into a relational db with hibernate using orm.jar library generated by visual-paradigm tool. The problem is that it does not work but the program does not give me exceptions.
I tried to change my code but the program catches an exception and does not work.
MAIN:
CoordinatorIntrusione c = CoordinatorIntrusione.getInstance();
c.avviaRilevamento();
c.notifyProximityBySerraID(1, 4);
ArrayList<Integer> prova = new ArrayList<Integer>();
prova.add(2);
prova.add(1);
prova.add(9);
c.notifyImageBySerraID(1, prova);
System.out.println("ecco");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
c.ripristinaRilevamento(1, "1");
COORDINATORINTRUSIONE:
public class CoordinatorIntrusione {
private volatile static CoordinatorIntrusione coordinator = null;
private ThreadGroup groupBLThread;
public int avviaRilevamento() {
int code = 0;
EntitySmartFarm esm = EntitySmartFarm.getInstance();
EntityColtivazione[] colt = esm.getColtivazioniAttive();
if(colt.length==0) {
code=-1;
return code;
}
for(int i=0; i<colt.length; i++) {
EntitySerra serra = colt[i].getEntitySerra();
int id = serra.getId();
ControllerRilevaIntrusioneBL controller = new ControllerRilevaIntrusioneBL(id, groupBLThread, "worker"+i);
controller.start();
//System.out.println("ID :"+id);
}
return code;
}
public int negaID(int id, String matricola) {
//throw new UnsupportedOperationException();
int code = -1;
EntitySmartFarm esm = EntitySmartFarm.getInstance();
EntityColtivazione coltivazione = esm.getColtivazioneBySerraID(id);
if(coltivazione == null) return code;
String matResp = coltivazione.getEntitySerra().getResponsabile().getMatricola();
if (!matricola.equals(matResp)) return code;
ControllerRilevaIntrusioneBL controller = this.searchWorkerForID(id);
if (controller == null) return code;
code = controller.negaID();
return code;
}
public int ripristinaRilevamento(int id, String matricola) {
//throw new UnsupportedOperationException();
int code = -1;
EntitySmartFarm esm = EntitySmartFarm.getInstance();
EntityColtivazione coltivazione = esm.getColtivazioneBySerraID(id);
if(coltivazione == null) return code;
String matResp = coltivazione.getEntitySerra().getResponsabile().getMatricola();
if (!matricola.equals(matResp)) return code;
ControllerRilevaIntrusioneBL controller = this.searchWorkerForID(id);
if (controller == null) return code;
code = controller.ripristinaRilevamento();
return code;
}
public int confermaId(int id, String matricola) {
//throw new UnsupportedOperationException();
int code = -1;
EntitySmartFarm esm = EntitySmartFarm.getInstance();
EntityColtivazione coltivazione = esm.getColtivazioneBySerraID(id);
if(coltivazione == null) return code;
String matResp = coltivazione.getEntitySerra().getResponsabile().getMatricola();
if (!matricola.equals(matResp)) return code;
ControllerRilevaIntrusioneBL controller = this.searchWorkerForID(id);
if (controller == null) return code;
code = controller.confermaID();
return code;
// quindi se il code è negativo le matricole non combaciano, se positivo combaciano
}
protected ControllerRilevaIntrusioneBL searchWorkerForID(int idSerra) {
ControllerRilevaIntrusioneBL[] th = new ControllerRilevaIntrusioneBL[groupBLThread.activeCount()];
groupBLThread.enumerate(th);
int i=0;
while(i<th.length) {
if(th[i].getID() == idSerra) return th[i];
i++;
}
return null;
}
private CoordinatorIntrusione() {
groupBLThread = new ThreadGroup("workerCoordinator");
}
public void notifyProximityBySerraID(int idSerra, float value) {
ControllerRilevaIntrusioneBL thread = this.searchWorkerForID(idSerra);
thread.proximityValueArrived(value);
}
public void notifyImageBySerraID(int idSerra, ArrayList<Integer> img) {
ControllerRilevaIntrusioneBL thread = this.searchWorkerForID(idSerra);
thread.imgArrived(img);
}
public static CoordinatorIntrusione getInstance() {
if (coordinator == null) {
synchronized(CoordinatorIntrusione.class){ //Serve la sincronizzazione visto che è solo lettura
if(coordinator == null){
coordinator = new CoordinatorIntrusione();
}
}
}
return coordinator;
}
}
CONTROLLERRILEVAINTRUSIONEBL:
public class ControllerRilevaIntrusioneBL extends Thread{
private int id;
private float[] valoreProssimita;
private ArrayList<Integer> img;
private static final float criticalProxValue =5;
private Semaphore proxsem;
private Semaphore camsem;
private Semaphore ripristinasem;
private Semaphore waitsem ;
protected int rilevaVolti() {
//TODO with python script
//throw new UnsupportedOperationException();
return 0;
}
public synchronized int negaID() {
//throw new UnsupportedOperationException();
int code = 0;
if (waitsem.getQueueLength() > 0) {
waitsem.release();
code = 1;
}
else code = -1;
return code;
}
public synchronized int ripristinaRilevamento() {
//throw new UnsupportedOperationException();
int code = 0;
//System.out.println(ripristinasem.getQueueLength());
if (ripristinasem.getQueueLength() > 0) {
ripristinasem.release();
code = 1;
}
else code = -1;
//System.out.println(ripristinasem.getQueueLength());
return code;
}
public synchronized int confermaID() {
//throw new UnsupportedOperationException();
int code = 0;
if (waitsem.getQueueLength() > 0) {
waitsem.release();
code = 1;
}
else code = -1;
return code;
}
public int getID() {
return id;
}
public void setID(int id) {
this.id = id;
}
#Override
public void run() {
EntitySmartFarm esm = EntitySmartFarm.getInstance();
EntityColtivazione colt = esm.getColtivazioneBySerraID(id);
EntitySerra serra = colt.getEntitySerra();
EntitySensore proximity = serra.getSensoreProssimita();
EntitySensore camera = serra.getSensoreFotografico();
//ProxySerra proxyserra = ProxySerra.getInstance();
while (true) {
//MonitoraggioProssimità
//invio messaggio alla serra
try {
proxsem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
proximity.setValore(valoreProssimita);
if(valoreProssimita[0] < criticalProxValue){
// invio messaggio camera alla serra
try {
camsem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
float[] immagine = new float[img.size()];
int index = 0;
for (Integer value: img) {
immagine[index++] = value;
}
camera.setValore(immagine);
int ret = this.rilevaVolti();
if (ret == 0 || ret == -1) {
//New ProxyNotificationSystem
if (ret == 0) {
//ProxyNotificationSystem.inviosegnalazione();
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Rome"), Locale.ITALY);
Date today = calendar.getTime();
Date ora = calendar.getTime();
int[] array = img.stream().mapToInt(i -> i).toArray();
serra.addIntrusione(today, "Selvaggina", array, ora);
} else {
try {
waitsem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
//proxynotsys.nviosegnalazione();
}
System.out.println("Thread: "+this.id+" bloccato");
try {
ripristinasem.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread: "+this.id+" Sbloccato");
}
}
}
}
public ControllerRilevaIntrusioneBL(int id, ThreadGroup group, String threadName){
super(group,threadName);
this.id = id;
valoreProssimita = new float[1];
img = new ArrayList<Integer>();
proxsem = new Semaphore(0);
camsem = new Semaphore(0);
ripristinasem = new Semaphore(0);
waitsem = new Semaphore(0);
}
public void proximityValueArrived(float value) {
valoreProssimita[0]=value;
proxsem.release();
}
public void imgArrived(ArrayList<Integer> img) {
this.img=img;
camsem.release();
}
}
ENTITYSERRA (first "addIntrusione" method catches exception and does not work, second "addIntrusione" method does not catch but does not work anyway):
public class EntitySerra {
public EntitySerra() {
}
private java.util.Set this_getSet (int key) {
if (key == vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYEMPLOYERS) {
return ORM_entityEmployers;
}
else if (key == vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYSENSORES) {
return ORM_entitySensores;
}
else if (key == vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYINTRUSIONES) {
return ORM_entityIntrusiones;
}
else if (key == vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYLETTURAS) {
return ORM_entityLetturas;
}
return null;
}
org.orm.util.ORMAdapter _ormAdapter = new org.orm.util.AbstractORMAdapter() {
public java.util.Set getSet(int key) {
return this_getSet(key);
}
};
private int id;
private java.util.Set ORM_entityEmployers = new java.util.HashSet();
private java.util.Set ORM_entitySensores = new java.util.HashSet();
private java.util.Set ORM_entityIntrusiones = new java.util.HashSet();
private java.util.Set ORM_entityLetturas = new java.util.HashSet();
private void setId(int value) {
this.id = value;
}
public int getId() {
return id;
}
public int getORMID() {
return getId();
}
public void setORM_EntityEmployers(java.util.Set value) {
this.ORM_entityEmployers = value;
}
public java.util.Set getORM_EntityEmployers() {
return ORM_entityEmployers;
}
public final vista_architetturale_gestoresmartfarm.entity2.EntityEmployerSetCollection entityEmployers = new vista_architetturale_gestoresmartfarm.entity2.EntityEmployerSetCollection(this, _ormAdapter, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYEMPLOYERS, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_MUL_ONE_TO_MANY);
public void setORM_EntitySensores(java.util.Set value) {
this.ORM_entitySensores = value;
}
public java.util.Set getORM_EntitySensores() {
return ORM_entitySensores;
}
public final vista_architetturale_gestoresmartfarm.entity2.EntitySensoreSetCollection entitySensores = new vista_architetturale_gestoresmartfarm.entity2.EntitySensoreSetCollection(this, _ormAdapter, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYSENSORES, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_MUL_ONE_TO_MANY);
public void setORM_EntityIntrusiones(java.util.Set value) {
this.ORM_entityIntrusiones = value;
}
public java.util.Set getORM_EntityIntrusiones() {
return ORM_entityIntrusiones;
}
public final vista_architetturale_gestoresmartfarm.entity2.EntityIntrusioneSetCollection entityIntrusiones = new vista_architetturale_gestoresmartfarm.entity2.EntityIntrusioneSetCollection(this, _ormAdapter, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYINTRUSIONES, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_MUL_ONE_TO_MANY);
public void setORM_EntityLetturas(java.util.Set value) {
this.ORM_entityLetturas = value;
}
public java.util.Set getORM_EntityLetturas() {
return ORM_entityLetturas;
}
public final vista_architetturale_gestoresmartfarm.entity2.EntityLetturaSetCollection entityLetturas = new vista_architetturale_gestoresmartfarm.entity2.EntityLetturaSetCollection(this, _ormAdapter, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYLETTURAS, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_MUL_ONE_TO_MANY);
public String getNotifyInformationResponsabile() {
//TODO: Implement Method
String recapito = null;
Iterator<EntityEmployer> it = ORM_entityEmployers.iterator();
boolean trovato = false;
while(trovato == false && it.hasNext()){
EntityEmployer empTemp = it.next();
if(empTemp.getTipo().equals("responsabile")){
trovato = true;
recapito = empTemp.getRecapito();
}
}
return recapito;
}
public void salvaLettura() {
//TODO: Implement Method
throw new UnsupportedOperationException();
}
public void salvaLettura2() {
//TODO: Implement Method
throw new UnsupportedOperationException();
}
public void addIntrusione(java.util.Date data, String tipo, int[] img, java.util.Date ora) {
//TODO: Implement Method
EntityIntrusione intrusione = new EntityIntrusione (data, ora, tipo, img);
//DA TESTARE IMPORTANTISSIMO
ORM_entityIntrusiones.add(intrusione);
try {
//EntitySerraDAO.save(this);
EntityIntrusioneDAO.save(intrusione);
} catch (PersistentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*public synchronized void addIntrusione(java.util.Date data, String tipo, int[] img, java.util.Date ora){
//TODO: Implement Method
EntityIntrusione intrusione = new EntityIntrusione (data,ora,tipo,img);
//DA TESTARE IMPORTANTISSIMO
this.ORM_entityIntrusiones.add(intrusione);
this.entityIntrusiones.add(intrusione);
try {
Stream<EntityIntrusione> stream = this.ORM_entityIntrusiones.stream();
// salva l'ultimo elem
EntityIntrusioneDAO.save(stream.reduce((a, b) -> b).orElse(null));
} catch (PersistentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
public EntitySerra(vista_architetturale_gestoresmartfarm.entity2.EntitySerraDAO serra) {
//TODO: Implement Method
throw new UnsupportedOperationException();
}
public String[] getNotifyInformationEmployers() {
//TODO: Implement Method
throw new UnsupportedOperationException();
}
public vista_architetturale_gestoresmartfarm.entity2.EntitySensore getSensoreProssimita() {
EntitySensore sensProssimita = null;
Iterator<EntitySensore> it = ORM_entitySensores.iterator();
boolean trovato = false;
while(trovato == false && it.hasNext()){
EntitySensore sensTemp = it.next();
if(sensTemp.getTipo().equals("prossimita")){
trovato = true;
sensProssimita = sensTemp;
}
}
return sensProssimita;
}
public vista_architetturale_gestoresmartfarm.entity2.EntitySensore getSensoreFotografico() {
EntitySensore sensFotocamera = null;
Iterator<EntitySensore> it = ORM_entitySensores.iterator();
boolean trovato = false;
while(trovato == false && it.hasNext()){
EntitySensore sensTemp = it.next();
if(sensTemp.getTipo().equals("cam")){
trovato = true;
sensFotocamera = sensTemp;
}
}
return sensFotocamera;
}
public vista_architetturale_gestoresmartfarm.entity2.EntityEmployer getResponsabile() {
//TODO: Implement Method
EntityEmployer responsabile = null;
Iterator<EntityEmployer> it = ORM_entityEmployers.iterator();
boolean trovato = false;
while(trovato == false && it.hasNext()){
EntityEmployer empTemp = it.next();
if(empTemp.getTipo().equals("responsabile")){
trovato = true;
responsabile = empTemp;
}
}
return responsabile;
}
public String toString() {
return String.valueOf(getId());
}
}
ENTITYINTRUSIONEDAO:
public class EntityIntrusioneDAO {
public static boolean save(vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione entityIntrusione) throws PersistentException {
try {
vista_architetturale_gestoresmartfarm.entity2.ProgettoPSSSAgosVersionPersistentManager.instance().saveObject(entityIntrusione);
return true;
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
}
PERSISTENT MANAGER:
public class ProgettoPSSSAgosVersionPersistentManager extends PersistentManager {
private static PersistentManager _instance = null;
private static SessionType _sessionType = SessionType.THREAD_BASE;
private static int _timeToAlive = 60000;
private static JDBCConnectionSetting _connectionSetting = null;
private static Properties _extraProperties = null;
private static String _configurationFile = null;
private ProgettoPSSSAgosVersionPersistentManager() throws PersistentException {
super(_connectionSetting, _sessionType, _timeToAlive, new String[] {}, _extraProperties, _configurationFile);
setFlushMode(FlushMode.AUTO);
}
public String getProjectName() {
return PROJECT_NAME;
}
public static synchronized final PersistentManager instance() throws PersistentException {
if (_instance == null) {
_instance = new ProgettoPSSSAgosVersionPersistentManager();
}
return _instance;
}
public void disposePersistentManager() throws PersistentException {
_instance = null;
super.disposePersistentManager();
}
public static void setSessionType(SessionType sessionType) throws PersistentException {
if (_instance != null) {
throw new PersistentException("Cannot set session type after create PersistentManager instance");
}
else {
_sessionType = sessionType;
}
}
public static void setAppBaseSessionTimeToAlive(int timeInMs) throws PersistentException {
if (_instance != null) {
throw new PersistentException("Cannot set session time to alive after create PersistentManager instance");
}
else {
_timeToAlive = timeInMs;
}
}
public static void setJDBCConnectionSetting(JDBCConnectionSetting aConnectionSetting) throws PersistentException {
if (_instance != null) {
throw new PersistentException("Cannot set connection setting after create PersistentManager instance");
}
else {
_connectionSetting = aConnectionSetting;
}
}
public static void setHibernateProperties(Properties aProperties) throws PersistentException {
if (_instance != null) {
throw new PersistentException("Cannot set hibernate properties after create PersistentManager instance");
}
else {
_extraProperties = aProperties;
}
}
public static void setConfigurationFile(String aConfigurationFile) throws PersistentException {
if (_instance != null) {
throw new PersistentException("Cannot set configuration file after create PersistentManager instance");
}
else {
_configurationFile = aConfigurationFile;
}
}
public static void saveJDBCConnectionSetting() {
PersistentManager.saveJDBCConnectionSetting(PROJECT_NAME, _connectionSetting);
}
}
The exception caught is:
org.orm.PersistentException: org.hibernate.PropertyValueException: not-null property references a null or transient value : vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione._vista_architetturale_gestoresmartfarm.entity2.EntitySerra.ORM_EntityIntrusionesBackref
at org.orm.PersistentSession.saveOrUpdate(PersistentSession.java:598)
at org.orm.PersistentManager.saveObject(PersistentManager.java:326)
at vista_architetturale_gestoresmartfarm.entity2.EntityIntrusioneDAO.save(EntityIntrusioneDAO.java:304)
at vista_architetturale_gestoresmartfarm.entity2.EntitySerra.addIntrusione(EntitySerra.java:146)
at vista_architetturale_gestoresmartfarm.business_logic.ControllerRilevaIntrusioneBL.run(ControllerRilevaIntrusioneBL.java:139)
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value : vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione._vista_architetturale_gestoresmartfarm.entity2.EntitySerra.ORM_EntityIntrusionesBackref
at org.hibernate.engine.internal.Nullability.checkNullability(Nullability.java:89)
at org.hibernate.action.internal.AbstractEntityInsertAction.nullifyTransientReferencesIfNotAlready(AbstractEntityInsertAction.java:115)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:69)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:625)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:279)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:260)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:305)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:97)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:655)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:647)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:642)
at org.orm.PersistentSession.saveOrUpdate(PersistentSession.java:596)
... 4 more
org.orm.PersistentException: org.orm.PersistentException: org.hibernate.PropertyValueException: not-null property references a null or transient value : vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione._vista_architetturale_gestoresmartfarm.entity2.EntitySerra.ORM_EntityIntrusionesBackref
at vista_architetturale_gestoresmartfarm.entity2.EntityIntrusioneDAO.save(EntityIntrusioneDAO.java:309)
at vista_architetturale_gestoresmartfarm.entity2.EntitySerra.addIntrusione(EntitySerra.java:146)
at vista_architetturale_gestoresmartfarm.business_logic.ControllerRilevaIntrusioneBL.run(ControllerRilevaIntrusioneBL.java:139)
Caused by: org.orm.PersistentException: org.hibernate.PropertyValueException: not-null property references a null or transient value : vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione._vista_architetturale_gestoresmartfarm.entity2.EntitySerra.ORM_EntityIntrusionesBackref
at org.orm.PersistentSession.saveOrUpdate(PersistentSession.java:598)
at org.orm.PersistentManager.saveObject(PersistentManager.java:326)
at vista_architetturale_gestoresmartfarm.entity2.EntityIntrusioneDAO.save(EntityIntrusioneDAO.java:304)
... 2 more
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value : vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione._vista_architetturale_gestoresmartfarm.entity2.EntitySerra.ORM_EntityIntrusionesBackref
at org.hibernate.engine.internal.Nullability.checkNullability(Nullability.java:89)
at org.hibernate.action.internal.AbstractEntityInsertAction.nullifyTransientReferencesIfNotAlready(AbstractEntityInsertAction.java:115)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:69)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:625)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:279)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:260)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:305)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:97)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:655)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:647)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:642)
at org.orm.PersistentSession.saveOrUpdate(PersistentSession.java:596)
... 4 more
You can specify the Error Handling method when generating ORM code. May I know which option you selected?
I have following code
The function writes objects to the replicationstream provided by tomcat. IF the object is not serializable then I am trying to write "Misssing value".
public void writeExternal(ObjectOutput out)
throws IOException
{
out.writeInt(getType());
out.writeInt(getAction());
out.writeUTF(getName());
out.writeBoolean(getValue()!=null);
try
{
out.writeObject(getValue());
}
catch (Exception e)
{
System.out.println("Missing Value");
}
}
Following code reads object. Similar to read if the object is not serializable I try to read again to get read "Missing Value"
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
this.type = in.readInt();
this.action = in.readInt();
this.name = in.readUTF();
boolean hasValue=in.readBoolean();
try{
this.value = in.readObject();
}
catch(Exception er)
{
System.out.println("Missing Value");
}
}
I am getting following error, and I am not quite sure what does it mean. Both of the functions are being called for multiple times. First the writeExternal function is called for all the objects and then the readExternal.
java.io.StreamCorruptedException: invalid type code: 4C
at java.io.ObjectInputStream$BlockDataInputStream.readBlockHeader(ObjectInputStream.java:2480)
at java.io.ObjectInputStream$BlockDataInputStream.refill(ObjectInputStream.java:2515)
at java.io.ObjectInputStream$BlockDataInputStream.read(ObjectInputStream.java:2587)
at java.io.DataInputStream.readInt(DataInputStream.java:387)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(ObjectInputStream.java:2792)
at java.io.ObjectInputStream.readInt(ObjectInputStream.java:967)
EDIT
*Here is the code*
public class DeltaRequest
implements Externalizable
{
private LinkedList actions = new LinkedList();
private LinkedList actionPool = new LinkedList();
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
AttributeInfo info = null;
if (this.actionPool.size() > 0) {
info = (AttributeInfo)this.actionPool.removeFirst();
info.readExternal(in);
this.actions.addLast(info);
}
}
public void writeExternal(ObjectOutput out)
throws IOException
{
out.writeUTF(getSessionId());
out.writeBoolean(this.recordAllActions);
out.writeInt(getSize());
for (int i = 0; i < getSize(); i++) {
AttributeInfo info = (AttributeInfo)this.actions.get(i);
info.writeExternal(out);
}
}
protected byte[] serialize()
throws IOException
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
writeExternal(oos);
oos.flush();
oos.close();
return bos.toByteArray();
}
private static class AttributeInfo implements Externalizable {
private String name = null;
private Object value = null;
private int action;
private int type;
public AttributeInfo() {
}
public AttributeInfo(int type, int action, String name, Object value) {
init(type, action, name, value);
}
public void init(int type, int action, String name, Object value)
{
this.name = name;
this.value = value;
this.action = action;
this.type = type;
}
public int getType() {
return this.type;
}
public int getAction() {
return this.action;
}
public Object getValue() {
return this.value;
}
public int hashCode() {
return this.name.hashCode();
}
public String getName() {
return this.name;
}
public void recycle() {
this.name = null;
this.value = null;
this.type = -1;
this.action = -1;
}
public boolean equals(Object o) {
if (!(o instanceof AttributeInfo)) return false;
AttributeInfo other = (AttributeInfo)o;
return other.getName().equals(getName());
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
this.type = in.readInt();
this.action = in.readInt();
this.name = in.readUTF();
boolean hasValue=in.readBoolean();
try{
this.value = in.readObject();
}
catch(Exception er)
{
out.writeObject("Value Missing");
}
}
public void writeExternal(ObjectOutput out)
throws IOException
{
out.writeInt(getType());
out.writeInt(getAction());
out.writeUTF(getName());
out.writeBoolean(getValue()!=null);
try
{
out.writeObject(getValue());
}
catch (Exception e)
{
out.writeObject("Value Missing");
}
}
public String toString()
{
StringBuffer buf = new StringBuffer("AttributeInfo[type=");
buf.append(getType()).append(", action=").append(getAction());
buf.append(", name=").append(getName()).append(", value=").append(getValue());
buf.append(", addr=").append(super.toString()).append("]");
return buf.toString();
}
}
}
Code:
This is how the above function are called.
protected DeltaRequest deserializeDeltaRequest(DeltaSession objbb, byte[] data)
throws ClassNotFoundException, IOException
{
try
{
objbb.lock();
ReplicationStream ois = getReplicationStream(data);
objbb.getDeltaRequest().readExternal(ois);
ois.close();
return objbb.getDeltaRequest();
} finally {
objbb.unlock();
}
}
protected byte[] serializeDeltaRequest(DeltaSession objbb, DeltaRequest objAA)
throws IOException
{
try
{
objbb.lock();
return objAA.serialize();
} finally {
objbb.unlock();
}
}
DeltaManager
public class DeltaManager extends ClusterManagerBase
{
public Session createSession(String sessionId)
{
return createSession(sessionId, true);
}
public Session createSession(String sessionId, boolean distribute)
{
if ((this.maxActiveSessions >= 0) && (this.sessions.size() >= this.maxActiveSessions)) {
this.rejectedSessions += 1;
throw new IllegalStateException(sm.getString("deltaManager.createSession.ise"));
}
DeltaSession session = (DeltaSession)super.createSession(sessionId);
if (distribute) {
sendCreateSession(session.getId(), session);
}
if (log.isDebugEnabled())
log.debug(sm.getString("deltaManager.createSession.newSession", session.getId(), new Integer(this.sessions.size())));
return session;
}
protected void sendCreateSession(String sessionId, DeltaSession session)
{
if (this.cluster.getMembers().length > 0) {
SessionMessage msg = new SessionMessageImpl(getName(), 1, null, sessionId, sessionId + "-" + System.currentTimeMillis());
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.sendMessage.newSession", this.name, sessionId));
msg.setTimestamp(session.getCreationTime());
this.counterSend_EVT_SESSION_CREATED += 1L;
send(msg);
}
}
protected DeltaRequest deserializeDeltaRequest(DeltaSession session, byte[] data)
throws ClassNotFoundException, IOException
{
try
{
session.lock();
ReplicationStream ois = getReplicationStream(data);
session.getDeltaRequest().readExternal(ois);
ois.close();
return session.getDeltaRequest();
} finally {
session.unlock();
}
}
protected byte[] serializeDeltaRequest(DeltaSession session, DeltaRequest deltaRequest)
throws IOException
{
try
{
session.lock();
return deltaRequest.serialize();
} finally {
session.unlock();
}
}
protected void deserializeSessions(byte[] data)
throws ClassNotFoundException, IOException
{
ClassLoader originalLoader = Thread.currentThread().getContextClassLoader();
ObjectInputStream ois = null;
try
{
ois = getReplicationStream(data);
Integer count = (Integer)ois.readObject();
int n = count.intValue();
for (int i = 0; i < n; i++) {
DeltaSession session = (DeltaSession)createEmptySession();
session.readObjectData(ois);
session.setManager(this);
session.setValid(true);
session.setPrimarySession(false);
session.access();
session.setAccessCount(0);
session.resetDeltaRequest();
if (findSession(session.getIdInternal()) == null) {
this.sessionCounter += 1;
} else {
this.sessionReplaceCounter += 1L;
if (log.isWarnEnabled()) log.warn(sm.getString("deltaManager.loading.existing.session", session.getIdInternal()));
}
add(session);
}
} catch (ClassNotFoundException e) {
log.error(sm.getString("deltaManager.loading.cnfe", e), e);
throw e;
} catch (IOException e) {
log.error(sm.getString("deltaManager.loading.ioe", e), e);
throw e;
}
finally {
try {
if (ois != null) ois.close();
}
catch (IOException f)
{
}
ois = null;
if (originalLoader != null) Thread.currentThread().setContextClassLoader(originalLoader);
}
}
protected byte[] serializeSessions(Session[] currentSessions)
throws IOException
{
ByteArrayOutputStream fos = null;
ObjectOutputStream oos = null;
try
{
fos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(new BufferedOutputStream(fos));
oos.writeObject(new Integer(currentSessions.length));
for (int i = 0; i < currentSessions.length; i++) {
((DeltaSession)currentSessions[i]).writeObjectData(oos);
}
oos.flush();
} catch (IOException e) {
log.error(sm.getString("deltaManager.unloading.ioe", e), e);
throw e;
} finally {
if (oos != null) {
try {
oos.close();
}
catch (IOException f) {
}
oos = null;
}
}
return fos.toByteArray();
}
public void start()
throws LifecycleException
{
if (!this.initialized) init();
if (this.started) {
return;
}
this.started = true;
this.lifecycle.fireLifecycleEvent("start", null);
generateSessionId();
try
{
Cluster cluster = getCluster();
if (cluster == null) {
Container context = getContainer();
if ((context != null) && ((context instanceof Context))) {
Container host = context.getParent();
if ((host != null) && ((host instanceof Host))) {
cluster = host.getCluster();
if ((cluster != null) && ((cluster instanceof CatalinaCluster))) {
setCluster((CatalinaCluster)cluster);
} else {
Container engine = host.getParent();
if ((engine != null) && ((engine instanceof Engine))) {
cluster = engine.getCluster();
if ((cluster != null) && ((cluster instanceof CatalinaCluster)))
setCluster((CatalinaCluster)cluster);
}
else {
cluster = null;
}
}
}
}
}
if (cluster == null) {
log.error(sm.getString("deltaManager.noCluster", getName()));
return;
}
if (log.isInfoEnabled()) {
String type = "unknown";
if ((cluster.getContainer() instanceof Host))
type = "Host";
else if ((cluster.getContainer() instanceof Engine)) {
type = "Engine";
}
log.info(sm.getString("deltaManager.registerCluster", getName(), type, cluster.getClusterName()));
}
if (log.isInfoEnabled()) log.info(sm.getString("deltaManager.startClustering", getName()));
cluster.registerManager(this);
getAllClusterSessions();
}
catch (Throwable t) {
log.error(sm.getString("deltaManager.managerLoad"), t);
}
}
public synchronized void getAllClusterSessions()
{
if ((this.cluster != null) && (this.cluster.getMembers().length > 0)) {
long beforeSendTime = System.currentTimeMillis();
Member mbr = findSessionMasterMember();
if (mbr == null) {
return;
}
SessionMessage msg = new SessionMessageImpl(getName(), 4, null, "GET-ALL", "GET-ALL-" + getName());
this.stateTransferCreateSendTime = beforeSendTime;
this.counterSend_EVT_GET_ALL_SESSIONS += 1L;
this.stateTransfered = false;
try
{
synchronized (this.receivedMessageQueue) {
this.receiverQueue = true;
}
this.cluster.send(msg, mbr);
if (log.isWarnEnabled()) log.warn(sm.getString("deltaManager.waitForSessionState", getName(), mbr, Integer.valueOf(getStateTransferTimeout())));
waitForSendAllSessions(beforeSendTime);
} finally {
synchronized (this.receivedMessageQueue) {
for (Iterator iter = this.receivedMessageQueue.iterator(); iter.hasNext(); ) {
SessionMessage smsg = (SessionMessage)iter.next();
if (!this.stateTimestampDrop) {
messageReceived(smsg, smsg.getAddress() != null ? smsg.getAddress() : null);
}
else if ((smsg.getEventType() != 4) && (smsg.getTimestamp() >= this.stateTransferCreateSendTime))
{
messageReceived(smsg, smsg.getAddress() != null ? smsg.getAddress() : null);
}
else if (log.isWarnEnabled()) {
log.warn(sm.getString("deltaManager.dropMessage", getName(), smsg.getEventTypeString(), new Date(this.stateTransferCreateSendTime), new Date(smsg.getTimestamp())));
}
}
this.receivedMessageQueue.clear();
this.receiverQueue = false;
}
}
}
else if (log.isInfoEnabled()) { log.info(sm.getString("deltaManager.noMembers", getName())); }
}
protected void registerSessionAtReplicationValve(DeltaSession session)
{
if ((this.replicationValve == null) &&
((this.container instanceof StandardContext)) && (((StandardContext)this.container).getCrossContext())) {
Cluster cluster = getCluster();
if ((cluster != null) && ((cluster instanceof CatalinaCluster))) {
Valve[] valves = ((CatalinaCluster)cluster).getValves();
if ((valves != null) && (valves.length > 0)) {
for (int i = 0; (this.replicationValve == null) && (i < valves.length); i++) {
if ((valves[i] instanceof ReplicationValve)) this.replicationValve = ((ReplicationValve)valves[i]);
}
if ((this.replicationValve == null) && (log.isDebugEnabled())) {
log.debug("no ReplicationValve found for CrossContext Support");
}
}
}
}
if (this.replicationValve != null)
this.replicationValve.registerReplicationSession(session);
}
protected Member findSessionMasterMember()
{
Member mbr = null;
Member[] mbrs = this.cluster.getMembers();
if (mbrs.length != 0) mbr = mbrs[0];
if ((mbr == null) && (log.isWarnEnabled())) log.warn(sm.getString("deltaManager.noMasterMember", getName(), ""));
if ((mbr != null) && (log.isDebugEnabled())) log.warn(sm.getString("deltaManager.foundMasterMember", getName(), mbr));
return mbr;
}
public void messageDataReceived(ClusterMessage cmsg)
{
if ((cmsg != null) && ((cmsg instanceof SessionMessage))) {
SessionMessage msg = (SessionMessage)cmsg;
switch (msg.getEventType()) {
case 1:
case 2:
case 3:
case 4:
case 13:
synchronized (this.receivedMessageQueue) {
if (this.receiverQueue) {
this.receivedMessageQueue.add(msg);
return;
}
}
break;
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12: } messageReceived(msg, msg.getAddress() != null ? msg.getAddress() : null);
}
}
public ClusterMessage requestCompleted(String sessionId)
{
return requestCompleted(sessionId, false);
}
public ClusterMessage requestCompleted(String sessionId, boolean expires)
{
DeltaSession session = null;
try {
session = (DeltaSession)findSession(sessionId);
DeltaRequest deltaRequest = session.getDeltaRequest();
session.lock();
msg = null;
boolean isDeltaRequest = false;
synchronized (deltaRequest) {
isDeltaRequest = deltaRequest.getSize() > 0;
if (isDeltaRequest) {
this.counterSend_EVT_SESSION_DELTA += 1L;
byte[] data = serializeDeltaRequest(session, deltaRequest);
msg = new SessionMessageImpl(getName(), 13, data, sessionId, sessionId + "-" + System.currentTimeMillis());
session.resetDeltaRequest();
}
}
if (!isDeltaRequest) {
if ((!expires) && (!session.isPrimarySession())) {
this.counterSend_EVT_SESSION_ACCESSED += 1L;
msg = new SessionMessageImpl(getName(), 3, null, sessionId, sessionId + "-" + System.currentTimeMillis());
if (log.isDebugEnabled()) {
log.debug(sm.getString("deltaManager.createMessage.accessChangePrimary", getName(), sessionId));
}
}
}
else if (log.isDebugEnabled()) {
log.debug(sm.getString("deltaManager.createMessage.delta", getName(), sessionId));
}
if (!expires)
session.setPrimarySession(true);
long replDelta;
if ((!expires) && (msg == null)) {
replDelta = System.currentTimeMillis() - session.getLastTimeReplicated();
if (replDelta > getMaxInactiveInterval() * 1000) {
this.counterSend_EVT_SESSION_ACCESSED += 1L;
msg = new SessionMessageImpl(getName(), 3, null, sessionId, sessionId + "-" + System.currentTimeMillis());
if (log.isDebugEnabled()) {
log.debug(sm.getString("deltaManager.createMessage.access", getName(), sessionId));
}
}
}
if (msg != null) {
session.setLastTimeReplicated(System.currentTimeMillis());
msg.setTimestamp(session.getLastTimeReplicated());
}
return msg;
}
catch (IOException x)
{
SessionMessage msg;
log.error(sm.getString("deltaManager.createMessage.unableCreateDeltaRequest", sessionId), x);
return null;
} finally {
if (session != null) session.unlock();
}
}
protected void messageReceived(SessionMessage msg, Member sender)
{
if ((doDomainReplication()) && (!checkSenderDomain(msg, sender))) {
return;
}
ClassLoader contextLoader = Thread.currentThread().getContextClassLoader();
try
{
ClassLoader[] loaders = getClassLoaders();
if ((loaders != null) && (loaders.length > 0)) Thread.currentThread().setContextClassLoader(loaders[0]);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.eventType", getName(), msg.getEventTypeString(), sender));
switch (msg.getEventType()) {
case 4:
handleGET_ALL_SESSIONS(msg, sender);
break;
case 12:
handleALL_SESSION_DATA(msg, sender);
break;
case 14:
handleALL_SESSION_TRANSFERCOMPLETE(msg, sender);
break;
case 1:
handleSESSION_CREATED(msg, sender);
break;
case 2:
handleSESSION_EXPIRED(msg, sender);
break;
case 3:
handleSESSION_ACCESSED(msg, sender);
break;
case 13:
handleSESSION_DELTA(msg, sender);
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
}
} catch (Exception x) { log.error(sm.getString("deltaManager.receiveMessage.error", getName()), x);
} finally {
Thread.currentThread().setContextClassLoader(contextLoader);
}
}
protected void handleALL_SESSION_TRANSFERCOMPLETE(SessionMessage msg, Member sender)
{
this.counterReceive_EVT_ALL_SESSION_TRANSFERCOMPLETE += 1;
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.transfercomplete", getName(), sender.getHost(), new Integer(sender.getPort())));
this.stateTransferCreateSendTime = msg.getTimestamp();
this.stateTransfered = true;
}
protected void handleSESSION_DELTA(SessionMessage msg, Member sender)
throws IOException, ClassNotFoundException
{
this.counterReceive_EVT_SESSION_DELTA += 1L;
byte[] delta = msg.getSession();
DeltaSession session = (DeltaSession)findSession(msg.getSessionID());
if (session != null) {
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.delta", getName(), msg.getSessionID())); try
{
session.lock();
DeltaRequest dreq = deserializeDeltaRequest(session, delta);
dreq.execute(session, this.notifyListenersOnReplication);
session.setPrimarySession(false);
} finally {
session.unlock();
}
}
}
protected void handleSESSION_CREATED(SessionMessage msg, Member sender)
{
this.counterReceive_EVT_SESSION_CREATED += 1L;
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.createNewSession", getName(), msg.getSessionID()));
DeltaSession session = (DeltaSession)createEmptySession();
session.setManager(this);
session.setValid(true);
session.setPrimarySession(false);
session.setCreationTime(msg.getTimestamp());
session.setMaxInactiveInterval(getMaxInactiveInterval());
session.access();
if (this.notifySessionListenersOnReplication) {
session.setId(msg.getSessionID());
} else {
session.setIdInternal(msg.getSessionID());
add(session);
}
session.resetDeltaRequest();
session.endAccess();
}
protected void handleALL_SESSION_DATA(SessionMessage msg, Member sender)
throws ClassNotFoundException, IOException
{
this.counterReceive_EVT_ALL_SESSION_DATA += 1L;
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataBegin", getName()));
byte[] data = msg.getSession();
deserializeSessions(data);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataAfter", getName()));
}
protected void handleGET_ALL_SESSIONS(SessionMessage msg, Member sender)
throws IOException
{
this.counterReceive_EVT_GET_ALL_SESSIONS += 1L;
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.unloadingBegin", getName()));
Session[] currentSessions = findSessions();
long findSessionTimestamp = System.currentTimeMillis();
if (isSendAllSessions()) {
sendSessions(sender, currentSessions, findSessionTimestamp);
}
else {
int len = currentSessions.length < getSendAllSessionsSize() ? currentSessions.length : getSendAllSessionsSize();
Session[] sendSessions = new Session[len];
for (int i = 0; i < currentSessions.length; i += getSendAllSessionsSize()) {
len = i + getSendAllSessionsSize() > currentSessions.length ? currentSessions.length - i : getSendAllSessionsSize();
System.arraycopy(currentSessions, i, sendSessions, 0, len);
sendSessions(sender, sendSessions, findSessionTimestamp);
if (getSendAllSessionsWaitTime() > 0)
try {
Thread.sleep(getSendAllSessionsWaitTime());
}
catch (Exception sleep)
{
}
}
}
SessionMessage newmsg = new SessionMessageImpl(this.name, 14, null, "SESSION-STATE-TRANSFERED", "SESSION-STATE-TRANSFERED" + getName());
newmsg.setTimestamp(findSessionTimestamp);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.createMessage.allSessionTransfered", getName()));
this.counterSend_EVT_ALL_SESSION_TRANSFERCOMPLETE += 1;
this.cluster.send(newmsg, sender);
}
protected void sendSessions(Member sender, Session[] currentSessions, long sendTimestamp)
throws IOException
{
byte[] data = serializeSessions(currentSessions);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.unloadingAfter", getName()));
SessionMessage newmsg = new SessionMessageImpl(this.name, 12, data, "SESSION-STATE", "SESSION-STATE-" + getName());
newmsg.setTimestamp(sendTimestamp);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.createMessage.allSessionData", getName()));
this.counterSend_EVT_ALL_SESSION_DATA += 1L;
this.cluster.send(newmsg, sender);
}
}
The problem here is that you are calling
this.writeExternal(oos);
instead of
oos.writeObject(this);
so the ObjectOutputStream never gets the chance to write the object preamble.
Similarly, you must call
Object o = ois.readObject();
rather than
Object o = this.readExternal(ois);
Re your non-serializable object, you should write a special object. At the moment you are treating every possible exception as just a missing object, when it could be a huge number of other things.
For some reason when I deserialize my quotes ArrayList, I don't get the right object back. I want to make sure that whenever I read/write my object, it will always be the same object.
Serialization code:
private void serializeQuotes(){
FileOutputStream fos;
try {
fos = openFileOutput(Constants.FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(quotes);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private void deserializeQuotes(){
try{
FileInputStream fis = openFileInput(Constants.FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
quotes = (ArrayList<Quote>) ois.readObject();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
Here is my Quote object
package org.stocktwits.model;
import java.io.Serializable;
public class Quote implements Serializable {
private static final long serialVersionUID = 1L;
public String symbol;
public String name;
public String change;
public String percentChange;
public String open;
public String daysHigh;
public String daysLow;
public String volume;
public String peRatio;
public String marketCapitalization;
public String yearHigh;
public String yearLow;
public String lastTradePriceOnly;
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getChange() {
return change;
}
public void setChange(String change) {
this.change = change;
}
public String getPercentChange() {
return percentChange;
}
public void setPercentChange(String percentChange) {
this.percentChange = percentChange;
}
public String getOpen() {
return open;
}
public void setOpen(String open) {
this.open = open;
}
public String getDaysHigh() {
return daysHigh;
}
public void setDaysHigh(String daysHigh) {
this.daysHigh = daysHigh;
}
public String getDaysLow() {
return daysLow;
}
public void setDaysLow(String daysLow) {
this.daysLow = daysLow;
}
public String getVolume() {
return volume;
}
public void setVolume(String volume) {
this.volume = volume;
}
public String getPeRatio() {
return peRatio;
}
public void setPeRatio(String peRatio) {
this.peRatio = peRatio;
}
public String getMarketCapitalization() {
return marketCapitalization;
}
public void setMarketCapitilization(String marketCapitalization) {
this.marketCapitalization = marketCapitalization;
}
public String getYearHigh() {
return yearHigh;
}
public void setYearHigh(String yearHigh) {
this.yearHigh = yearHigh;
}
public String getYearLow() {
return yearLow;
}
public void setYearLow(String yearLow) {
this.yearLow = yearLow;
}
public String getLastTradePriceOnly() {
return lastTradePriceOnly;
}
public void setLastTradePriceOnly(String lastTradePriceOnly) {
this.lastTradePriceOnly = lastTradePriceOnly;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((change == null) ? 0 : change.hashCode());
result = prime * result
+ ((daysHigh == null) ? 0 : daysHigh.hashCode());
result = prime * result + ((daysLow == null) ? 0 : daysLow.hashCode());
result = prime
* result
+ ((lastTradePriceOnly == null) ? 0 : lastTradePriceOnly
.hashCode());
result = prime
* result
+ ((marketCapitalization == null) ? 0 : marketCapitalization
.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((open == null) ? 0 : open.hashCode());
result = prime * result + ((peRatio == null) ? 0 : peRatio.hashCode());
result = prime * result
+ ((percentChange == null) ? 0 : percentChange.hashCode());
result = prime * result + ((symbol == null) ? 0 : symbol.hashCode());
result = prime * result + ((volume == null) ? 0 : volume.hashCode());
result = prime * result
+ ((yearHigh == null) ? 0 : yearHigh.hashCode());
result = prime * result + ((yearLow == null) ? 0 : yearLow.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;
Quote other = (Quote) obj;
if (change == null) {
if (other.change != null)
return false;
} else if (!change.equals(other.change))
return false;
if (daysHigh == null) {
if (other.daysHigh != null)
return false;
} else if (!daysHigh.equals(other.daysHigh))
return false;
if (daysLow == null) {
if (other.daysLow != null)
return false;
} else if (!daysLow.equals(other.daysLow))
return false;
if (lastTradePriceOnly == null) {
if (other.lastTradePriceOnly != null)
return false;
} else if (!lastTradePriceOnly.equals(other.lastTradePriceOnly))
return false;
if (marketCapitalization == null) {
if (other.marketCapitalization != null)
return false;
} else if (!marketCapitalization.equals(other.marketCapitalization))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (open == null) {
if (other.open != null)
return false;
} else if (!open.equals(other.open))
return false;
if (peRatio == null) {
if (other.peRatio != null)
return false;
} else if (!peRatio.equals(other.peRatio))
return false;
if (percentChange == null) {
if (other.percentChange != null)
return false;
} else if (!percentChange.equals(other.percentChange))
return false;
if (symbol == null) {
if (other.symbol != null)
return false;
} else if (!symbol.equals(other.symbol))
return false;
if (volume == null) {
if (other.volume != null)
return false;
} else if (!volume.equals(other.volume))
return false;
if (yearHigh == null) {
if (other.yearHigh != null)
return false;
} else if (!yearHigh.equals(other.yearHigh))
return false;
if (yearLow == null) {
if (other.yearLow != null)
return false;
} else if (!yearLow.equals(other.yearLow))
return false;
return true;
}
}
Why don't you delete the file in "serializeQuotes()" before writing the object. That way you will be sure, that there will be only one object there.
private void serializeQuotes(){
FileOutputStream fos;
File file = new File(Constants.FILENAME);
if (file.exists()) file.delete();
try {
fos = openFileOutput(file, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(quotes);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
Or if you do not want to delete file every time, use some kind of iteration when reading obejcts from it.