Send email on status change - java

I have a project which currently only does methods when I run the site. Now I need to implement a thread which checks the DB/the website for status-changes so I can send out a mail if something occurs. I have successfully added the functionality to mail someone, and also know the logic on how to do this. The problem occurs when I try to write the code, I don't know how to do it (Since I didn't know the back-end mostly, and now I have the responsibility for the project.
The logic would be to implement a java-thread (runnable) and then check the previous color with the new one and if it has changed send out an mail (The colors are statuses, for example, green & red). What is the most understandable and easy way to do this? I'll write the function names so you get an idea of what I have.
I have been stuck with this for a week and don't know what to do. Any help would be appreciated.
The method in the class for the object that changes color:
public void setColour(List<Status> statusar, List<Category> subcategories) {
for (int index = 0; index < subcategories.size(); index++) {
if (this.statusColor.compareToIgnoreCase("red") != 0) {
if ((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("green") == 0)
&& (this.priority < ((Category)subcategories.get(index)).getPriority())) {
this.statusColor = "GREEN";
this.priority = ((Category)subcategories.get(index)).getPriority();
}
if (((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("red") == 0)
&& (((Category)subcategories.get(index)).getPriority() == 2))
|| ((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("yellow") == 0)
&& (this.priority <= ((Category)subcategories.get(index)).getPriority()))
|| ((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("yellow") == 0)
&& (((Category)subcategories.get(index)).getPriority() == 3))) {
this.statusColor = "YELLOW";
this.priority = ((Category)subcategories.get(index)).getPriority();
}
if (((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("red") == 0)
&& (((Category)subcategories.get(index)).getPriority() == 3))
|| ((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("red") == 0)
&& (this.priority <= ((Category)subcategories.get(index)).getPriority()))) {
this.statusColor = "RED";
this.priority = ((Category)subcategories.get(index)).getPriority();
}
}
}
}
A color function I found in the DB part:
public List<Map<String, Object>> listColorsOverDays(String days, String categoryName) {
String SQL_getColors = "SELECT COUNT(*) count,color FROM ( ";
SQL_getColors += " SELECT CASE";
SQL_getColors += " WHEN CAST(status.value AS DECIMAL) >= CAST(greenFrom AS DECIMAL) AND CAST(status.value AS DECIMAL) <= CAST(greenTo AS DECIMAL) THEN 'GREEN' ";
SQL_getColors += " WHEN CAST(status.value AS DECIMAL) >= CAST(yellowFrom AS DECIMAL) AND CAST(status.value AS DECIMAL) <= CAST(yellowTo AS DECIMAL) THEN 'YELLOW' ";
SQL_getColors += " ELSE 'RED' END AS color ";
SQL_getColors += " FROM status INNER JOIN category ON status.idCategory = category.idCategory ";
SQL_getColors += " INNER JOIN threshold ON category.idCategory = threshold.idCategory ";
SQL_getColors += " WHERE status.timeStamp>DATE_SUB(NOW(), INTERVAL " + days + " DAY) ";
SQL_getColors += " AND category.name = '"+categoryName+"'";
SQL_getColors += " ) as p group by p.color";
List<Map<String, Object>> colorList = null;
try {
colorList = getJdbcTemplate().queryForList(SQL_getColors);
} catch (Exception e) {
e.printStackTrace();
}
return colorList;
}
Here's the controller which uses this function:
public List<Map<String, Object>> getColorList(String days, String categoryName) {
StatusDAO statusDao_i = (StatusDAO)this.context.getBean("statusDAO");
List<Map<String, Object>> colorList = new ArrayList();
try {
colorList = statusDao_i.listColorsOverDays(days, categoryName);
} catch (BadSqlGrammarException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return colorList;
}
A status list which contains the colors:
public List<Status> getStatusList(Status status) {
StatusDAO statusDao_i = (StatusDAO)this.context.getBean("statusDAO");
status.setCategoryId(this.categoryService_i.getCategoryId(status.getCategoryName()));
Timestamp fromTime = Timestamp.valueOf(status.getFromTime());
Timestamp toTime = Timestamp.valueOf(status.getToTime());
List<Status> statusList = new ArrayList();
try {
statusList = statusDao_i.getStatusesByTime(status, fromTime, toTime);
status.setCategoryId(this.categoryService_i.getCategoryId(status.getCategoryName()));
} catch (BadSqlGrammarException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return statusList;
}

Related

100 records at a time to udf

I have to pass record to an UDF which calls an API but as we want to do it parallely,we are using spark and thats why UDF is being developed, the problem here is that that UDF needs to take only 100 records at a time not more than that, it can't handle more than 100 records parallely, so how to ensure that only 100 record pass to it in one go please note we don't want to use count() function on whole record.
I am attaching the UDF code here,it's a generic UDF which returns array of struct.moreover if we pass 100 records in batchsize variable each time then,if suppose there are 198 records then if as we dont want to use count() we will not be knowing that its last batchsize is going to be 98.so how to handle that thing.
Guys... I have a generic UDF in which call is made for an API but before calling it creates batch of 100 firstly then only call restapi.. So the argument UDF takes are x1:string, x2:string, batchsize:integer(currently the batchsize is 100)..so in UDF until and unless the batchsize is not 100 the call will not happen.. And for each record it will return null.
So till 99th record it will return. Null but at 100th record the call will happen
[So, now the problem part:as we are taking batchsize 100 and call will take place only at 100th record. So, in condition like if we have suppose 198 record in file then 100 record will get the output but, other 98 will only return null as they will not get processed..
So please help a way around, and UDF take one record at a time, but it keep on collecting till 100th record.. I hope this clears up
public class Standardize_Address extends GenericUDF {
private static final Logger logger = LoggerFactory.getLogger(Standardize_Address.class);
private int counter = 0;
Client client = null;
private Batch batch = new Batch();
public Standardize_Address() {
client = new ClientBuilder().withUrl("https://ss-staging-public.beringmedia.com/street-address").build();
}
// StringObjectInspector streeti;
PrimitiveObjectInspector streeti;
PrimitiveObjectInspector cityi;
PrimitiveObjectInspector zipi;
PrimitiveObjectInspector statei;
PrimitiveObjectInspector batchsizei;
private ArrayList ret;
#Override
public String getDisplayString(String[] argument) {
return "My display string";
}
#Override
public ObjectInspector initialize(ObjectInspector[] args) throws UDFArgumentException {
System.out.println("under initialize");
if (args[0] == null) {
throw new UDFArgumentTypeException(0, "NO Street is mentioned");
}
if (args[1] == null) {
throw new UDFArgumentTypeException(0, "No Zip is mentioned");
}
if (args[2] == null) {
throw new UDFArgumentTypeException(0, "No city is mentioned");
}
if (args[3] == null) {
throw new UDFArgumentTypeException(0, "No State is mentioned");
}
if (args[4] == null) {
throw new UDFArgumentTypeException(0, "No batch size is mentioned");
}
/// streeti =args[0];
streeti = (PrimitiveObjectInspector)args[0];
// this.streetvalue = (StringObjectInspector) streeti;
cityi = (PrimitiveObjectInspector)args[1];
zipi = (PrimitiveObjectInspector)args[2];
statei = (PrimitiveObjectInspector)args[3];
batchsizei = (PrimitiveObjectInspector)args[4];
ret = new ArrayList();
ArrayList structFieldNames = new ArrayList();
ArrayList structFieldObjectInspectors = new ArrayList();
structFieldNames.add("Street");
structFieldNames.add("city");
structFieldNames.add("zip");
structFieldNames.add("state");
structFieldObjectInspectors.add(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
structFieldObjectInspectors.add(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
structFieldObjectInspectors.add(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
structFieldObjectInspectors.add(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
StructObjectInspector si2 = ObjectInspectorFactory.getStandardStructObjectInspector(structFieldNames,
structFieldObjectInspectors);
ListObjectInspector li2;
li2 = ObjectInspectorFactory.getStandardListObjectInspector(si2);
return li2;
}
#Override
public Object evaluate(DeferredObject[] args) throws HiveException {
ret.clear();
System.out.println("under evaluate");
// String street1 = streetvalue.getPrimitiveJavaObject(args[0].get());
Object oin = args[4].get();
System.out.println("under typecasting");
int batchsize = (Integer) batchsizei.getPrimitiveJavaObject(oin);
System.out.println("batchsize");
Object oin1 = args[0].get();
String street1 = (String) streeti.getPrimitiveJavaObject(oin1);
Object oin2 = args[1].get();
String zip1 = (String) zipi.getPrimitiveJavaObject(oin2);
Object oin3 = args[2].get();
String city1 = (String) cityi.getPrimitiveJavaObject(oin3);
Object oin4 = args[3].get();
String state1 = (String) statei.getPrimitiveJavaObject(oin4);
logger.info("address passed, street=" + street1 + ",zip=" + zip1 + ",city=" + city1 + ",state=" + state1);
counter++;
try {
System.out.println("under try");
Lookup lookup = new Lookup();
lookup.setStreet(street1);
lookup.setCity(city1);
lookup.setState(state1);
lookup.setZipCode(zip1);
lookup.setMaxCandidates(1);
batch.add(lookup);
} catch (BatchFullException ex) {
logger.error(ex.getMessage(), ex);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
/* batch.add(lookup); */
if (counter == batchsize) {
System.out.println("under if");
try {
logger.info("batch input street " + batch.get(0).getStreet());
try {
client.send(batch);
} catch (Exception e) {
logger.error(e.getMessage(), e);
logger.warn("skipping current batch, continuing with the next batch");
batch.clear();
counter = 0;
return null;
}
Vector<Lookup> lookups = batch.getAllLookups();
for (int i = 0; i < batch.size(); i++) {
// ListObjectInspector candidates;
ArrayList<Candidate> candidates = lookups.get(i).getResult();
if (candidates.isEmpty()) {
logger.warn("Address " + i + " is invalid.\n");
continue;
}
logger.info("Address " + i + " is valid. (There is at least one candidate)");
for (Candidate candidate : candidates) {
final Components components = candidate.getComponents();
final Metadata metadata = candidate.getMetadata();
logger.info("\nCandidate " + candidate.getCandidateIndex() + ":");
logger.info("Delivery line 1: " + candidate.getDeliveryLine1());
logger.info("Last line: " + candidate.getLastLine());
logger.info("ZIP Code: " + components.getZipCode() + "-" + components.getPlus4Code());
logger.info("County: " + metadata.getCountyName());
logger.info("Latitude: " + metadata.getLatitude());
logger.info("Longitude: " + metadata.getLongitude());
}
Object[] e;
e = new Object[4];
e[0] = new Text(candidates.get(i).getComponents().getStreetName());
e[1] = new Text(candidates.get(i).getComponents().getCityName());
e[2] = new Text(candidates.get(i).getComponents().getZipCode());
e[3] = new Text(candidates.get(i).getComponents().getState());
ret.add(e);
}
counter = 0;
batch.clear();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return ret;
} else {
return null;
}
}
}

How to read multiple sheets with Event model using Apache POI?

I can successfully read Excel file (.xls) using Event model POI. I am not using the usermodel (org.apache.poi.ss.usermodel) but an Event API to process xls and xlsx files (to address the memory footprint issue). However, when reading an .xls file with multiple sheets, only first sheet is read. Other sheets are ignored.
I am implementing HSSFListener and overriding its processRecord(Record record) method for xls files.
Here is my part of the code:
/**
* Main HSSFListener method for xls. It processes events and creates a RuntimeRecord to put into the DataPool.
*/
public void processRecord(Record record) {
int thisRow = -1;
String thisStr = null;
switch (record.getSid()) {
case BoundSheetRecord.sid:
boundSheetRecords.add(record);
break;
case BOFRecord.sid:
BOFRecord br = (BOFRecord)record;
if(br.getType() == BOFRecord.TYPE_WORKSHEET) {
// Works by ordering the BSRs by the location of their BOFRecords, and then knowing that we
// process BOFRecords in byte offset order
if(orderedBSRs == null) {
orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
}
// Check the existence of sheets
if(sheetIndex == 0) {
for(int i=0;i<excelSheetList.length;i++) {
boolean found = false;
if(this.getExcelSheetSpecification().equals(MSExcelAdapter.USE_WORKSHEET_NAME)) {
for(BoundSheetRecord rec : orderedBSRs) {
int len = rec.getSheetname().length();
if(len > 31)
this.warning("processRecord()","The length of sheet: " + rec.getSheetname() + " has more than 31 characters. Please change the name of the sheet, save the file and try again.");
}
}
if(this.getExcelSheetSpecification().equals(MSExcelAdapter.USE_WORKSHEET_NUMBER)) {
int sheetNo = Integer.parseInt(excelSheetList[i]);
if(sheetNo > 0 && sheetNo <= orderedBSRs.length) {
found = true;
}
} else {
for(int j=0;j<orderedBSRs.length;j++) {
if(this.getExcelSheetSpecification().equals(MSExcelAdapter.USE_WORKSHEET_NAME)) {
String sheetName = ((BoundSheetRecord) boundSheetRecords.get(j)).getSheetname();
if(excelSheetList[i].equals(sheetName)) {
found = true;
break;
}
}
}
}
if(!found)
this.error("processRecord()","Sheet: " + excelSheetList[i] + " does not exist.");
}
}
readCurrentSheet = true;
sheetIndex++;
System.out.println(sheetIndex);
if(this.getExcelSheetSpecification().equals(MSExcelAdapter.USE_WORKSHEET_NAME)) {
String sheetName = ((BoundSheetRecord) boundSheetRecords.get(sheetIndex-1)).getSheetname();
if(!canRead(sheetName)) {
readCurrentSheet = false;
}
} else {
if(!canRead(sheetIndex + "")) {
readCurrentSheet = false;
}
}
}
break;
case SSTRecord.sid:
sstRecord = (SSTRecord) record;
break;
case BlankRecord.sid:
BlankRecord brec = (BlankRecord) record;
thisRow = brec.getRow();
thisStr = null;
values.add(thisStr);
columnCount++;
break;
case FormulaRecord.sid:
FormulaRecord frec = (FormulaRecord) record;
thisRow = frec.getRow();
if(Double.isNaN( frec.getValue() )) {
// Formula result is a string
// This is stored in the next record
outputNextStringRecord = true;
nextRow = frec.getRow();
} else {
thisStr = formatListener.formatNumberDateCell(frec);
}
break;
case StringRecord.sid:
if(outputNextStringRecord) {
// String for formula
StringRecord srec = (StringRecord)record;
thisStr = srec.getString();
thisRow = nextRow;
outputNextStringRecord = false;
}
break;
case LabelSSTRecord.sid:
if(readCurrentSheet) {
LabelSSTRecord lsrec = (LabelSSTRecord) record;
thisRow = lsrec.getRow() + 1;
if(rowNumberList.contains(thisRow + "") ||
(rowNumberList.contains(END_OF_ROWS) && thisRow >= secondLastRow)) {
if(sstRecord == null) {
thisStr = "(No SST Record, can't identify string)";
} else {
thisStr = sstRecord.getString(lsrec.getSSTIndex()).toString();
}
}
}
break;
case NumberRecord.sid:
if(readCurrentSheet) {
NumberRecord numrec = (NumberRecord) record;
thisRow = numrec.getRow() + 1;
if(rowNumberList.contains(thisRow + "") ||
(rowNumberList.contains(END_OF_ROWS) && thisRow >= secondLastRow)) {
// No need to format.
// thisStr = formatListener.formatNumberDateCell(numrec); // Format
thisStr = String.valueOf(numrec.getValue());
}
}
break;
default:
break;
}
// Handle missing column
if(record instanceof MissingCellDummyRecord) {
thisStr = "";
}
// If we got something to print out, do so
if(thisStr != null) {
values.add(thisStr);
columnCount++;
}
// Handle end of row
if(record instanceof LastCellOfRowDummyRecord) {
if(readCurrentSheet) {
int currentRow = ((LastCellOfRowDummyRecord) record).getRow() + 1;
if(rowsReadSet.add(String.valueOf(currentRow))) {
if(processTestData) {
try {
int dpSize = this.getOutputDP().getSize();
if(dpSize < 1000 &&
(rowNumberList.contains(currentRow + "") ||
(rowNumberList.contains(END_OF_ROWS) && currentRow >= secondLastRow))) {
for(int i=columnCount; i<this.getConfigRecord().size(); i++) {
values.add(null); // Add empty string for missing columns
}
RuntimeRecord resultRecord = this.createRuntimeRecord(values);
this.fireRecordCreatedEvent(resultRecord);
this.putNextRecord(resultRecord);
}
} catch (Exception e) {
this.error("processRecord()",e.getMessage());
this.fireRecordCreationFailedEvent(e.getMessage(), e.getMessage());
}
} else {
try {
if(rowNumberList.contains(currentRow + "") || (rowNumberList.contains(END_OF_ROWS) && currentRow >= secondLastRow)) {
for(int i=columnCount; i<this.getConfigRecord().size(); i++) {
values.add(null); // Add empty string for missing columns
}
RuntimeRecord resultRecord = this.createRuntimeRecord(values);
this.fireRecordCreatedEvent(resultRecord);
this.putNextRecord(resultRecord);
}
} catch (Exception e) {
this.error("processRecord()",e.getMessage());
this.fireRecordCreationFailedEvent(e.getMessage(), e.getMessage());
}
}
}
values.removeAllElements();
columnCount = 0;
}
}
}
Here is the method that registers the listener:
private void readxls() throws FileNotFoundException, IOException {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(this.getFileName()));
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
request.addListenerForAllRecords(formatListener);
rowsReadSet.clear();
factory.processWorkbookEvents(request, fs);
}
When I debugged by adding some breakpoints, I noticed that it actually adds the column values to my values Vector. However, following condition is never matched for second sheet.
if(record instanceof LastCellOfRowDummyRecord) {
...
}
How to get rid off this problem? I want to read all the sheets in Excel file (.xls). I am using Apache POI 3.11-20141221 with JDK7.

Java with Pagination

I am working on writing a java client code which calls a web service. When I make a call to one of my client's web service, its accepting the input parameter like below:
KalturaFilterPager pager = new KalturaFilterPager();
pager.pageIndex = 1;
pager.pageSize = 50;
So If i have 430 records, I need to change the input parameter everytime like pageIndex =2 pageSize =50 like this to get all the records.
Now my requirement is I want to retrieve all my records in one page. How can I do this without specifying pageSize =431 as this record number might change in the future.
My code is:
private static String getMediaMetadata() throws KalturaApiException,
IOException, ParserConfigurationException, SAXException {
getKalturaClient();
String country = null;
KalturaMediaService mediaService = client.getMediaService();
System.out.println("Got the mediaservice" + mediaService);
KalturaMediaEntryFilter filter = new KalturaMediaEntryFilter();
KalturaFilterPager pager = new KalturaFilterPager();
pager.pageIndex = 1;
pager.pageSize = 50;
KalturaMediaListResponse mediaResponse = mediaService.list(filter,
pager);
if (mediaResponse.totalCount > 0) {
System.out.println("mediaResponse.totalCount"
+ mediaResponse.totalCount);
// pager.pageSize = mediaResponse.objects;
List<KalturaMediaEntry> mediaEntriesList = mediaResponse.objects;
if (mediaEntriesList != null && mediaEntriesList.size() > 0) {
for (int i = 0; i < mediaEntriesList.size(); i++) {
System.out.println("mediaEntriesList.size()-------->"
+ mediaEntriesList.size());
KalturaMediaEntry media = mediaEntriesList.get(i);
if (media != null) {
System.out.println("Media ID -------->" + media.id);
KalturaMetadataListResponse metadataResp = getMetadata(media.id);
if (metadataResp != null && metadataResp.totalCount > 0) {
System.out.println("Got the metadataResp"
+ metadataResp.totalCount);
List<KalturaMetadata> metadataObjs = metadataResp.objects;
if (metadataObjs != null && metadataObjs.size() > 0) {
System.out.println("got the metadaobjs");
for (int j = 0; j < metadataObjs.size(); j++) {
KalturaMetadata metadata = metadataObjs
.get(j);
if (metadata != null) {
System.out
.println("metadata not null --------->"
+ metadata);
String xml = metadata.xml;
if (xml != null) {
System.out
.println("xml not null --------->"
+ xml);
country = parseXml(xml);
if (country != null) {
System.out
.println("Country Value --------->"
+ country);
}
}
}
}
}
}
}
}
}
}
return country;
}
is there any way to get total number of records before actually getting records? Is there such an API ? If so, call that first use that value as the page size instead.

Threaded application writing duplicate lines to log file

I have written a multithreaded application that analyzes rows in a database with regex and updates them appropriately. I am writing each row to a log file for logging purposes. I have noticed that the same row is being written to the log file several times...sometimes upwards of 15 times. Here are snippets of the code.
Setting up ThreadPoolExecuter:
private static BlockingQueue<Runnable> worksQueue = new ArrayBlockingQueue<Runnable>(blockingQueueSize);
private static ThreadPoolExecutor exec = new ThreadPoolExecutor(threadPoolSize, threadPoolSize, 10, TimeUnit.SECONDS, worksQueue);
In this part, I run a query, then go through the results:
rs = ps.executeQuery();
while (rs.next()) {
exec.execute(new UpdateMember(rs, conn, fileWriter));
if (worksQueue.size() == blockingQueueSize) {
//reach the maximum, stop refill
for (;;) {
Thread.yield();
//wait until the size of queue reached the minimum
if (worksQueue.size() == 0) {
//start refill
break;
}
}
}
}
UpdateMember (with only run and writeToLog methods showing):
public class UpdateMember implements Runnable {
ResultSet rs;
Connection conn;
FileWriter fw;
public UpdateMember(ResultSet rs, Connection conn, FileWriter fw) {
this.rs = rs;
this.conn = conn;
this.fw = fw;
}
#Override
public void run() {
try {
String regex = "((?<city>[a-zA-Z\\s\\.]+)\\s)?(?<provState>AB|ALB|Alta|alberta|BC|B\\.C\\.|British Columbia|LB|Labrador|MB|Man|Manitoba|N[BLTSU]|Nfld|NF|Newfoundland|NWT|Northwest Territories|Nova Scotia|New Brunswick|Nunavut|ON|ONT|Ontario|PE|PEI|Prince Edward Island|QC|PC|QUE|QU|Quebec|SK|Sask|Saskatchewan|YT|Yukon|Yukon Territories)(\\s(?<country>CA|CAN|CANADA))?$";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
BigDecimal memrecno = rs.getBigDecimal(2);
String addressLineTwo = rs.getString(4);
String addressLineThree = rs.getString(5);
String addressLineFour = rs.getString(6);
BigDecimal attrrecno = rs.getBigDecimal(9);
String addressBeingParsed = "";
String city = null;
String province = null;
String country = null;
boolean usingAddressThree = false;
boolean usingAddressFour = false;
if (addressLineFour == null) {
if (addressLineThree == null) {
city = "Unknown";
}
else
{
addressBeingParsed = addressLineThree;
usingAddressThree = true;
}
}
else
{
addressBeingParsed = addressLineFour;
usingAddressFour = true;
}
if (usingAddressThree || usingAddressFour) {
Matcher matcher = pattern.matcher(addressBeingParsed);
// if matches are found
if (matcher.matches()) {
city = matcher.group("city");
province = matcher.group("provState");
country = matcher.group("country");
if (city == null || city.isEmpty()) {
// cities are alpha characters and spaces only
String cityRegex = "(?<city>^[a-zA-Z\\s\\.]+$)";
Pattern cityPattern = Pattern.compile(cityRegex, Pattern.CASE_INSENSITIVE);
if (usingAddressFour && (addressLineThree != null) && !addressLineThree.isEmpty()) {
Matcher cityMatcher = cityPattern.matcher(addressLineThree);
if (cityMatcher.matches()) {
city = cityMatcher.group("city");
}
else
{
city = "Unknown";
}
}
else if (usingAddressThree && (addressLineTwo != null) && !addressLineTwo.isEmpty()) {
Matcher cityMatcher = cityPattern.matcher(addressLineTwo);
if (cityMatcher.matches()) {
city = cityMatcher.group("city");
}
else
{
city = "Unknown";
}
}
else
{
city = "Unknown";
}
}
if (province != null && !province.isEmpty()) {
province = createProvinceCode(province);
}
}
else
{
city = "Unknown";
}
}
// update attributes in database
boolean success = updateRow(memrecno, attrrecno, city, province);
String logLine = memrecno.toString() + "|" + attrrecno.toString() + "|" + addressLineTwo + "|" + addressLineThree + "|" + addressLineFour + "|" + city + "|" + province + "|" + country + "|" + success + "|" + String.valueOf(Thread.currentThread().getId());
writeToLog(logLine);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private synchronized void writeToLog(String line) {
try {
fw.write(line + "\r\n");
fw.flush();
}
catch (IOException ex)
{
System.out.println("Error writing to log file. " + ex.getMessage());
}
}
}
I don't know if the threads are also calling the updateRow method multiple times, but I'm assuming they are and that's really bad.
Any ideas as to why it would be doing this?
I don't think ResultSet is thread safe. From your code, you should get the value first and then pass the value instead of rs into the thread.

Loading contact from phone book in J2ME

I implemented this code below in order to read contacts from the addressbook of the phone
The problem is, In a case when all the numbers in the phonebook are saved in the SIM it reads and displays the contacts for selection.
But in a case whereby any number is included on the phone memory, it gives an application error.(OutOfMemoryException)
What do I do (PS do not mind some System.out.println statements there. I used them for debugging)
public void execute() {
try {
// go through all the lists
String[] allContactLists = PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
if (allContactLists.length != 0) {
for (int i = 0; i < allContactLists.length; i++) {
System.out.println(allContactLists[i] + " " + allContactLists[1]);
System.out.println(allContactLists.length);
loadNames(allContactLists[i]);
System.out.println("Execute() error");
}
} else {
available = false;
}
} catch (PIMException e) {
available = false;
} catch (SecurityException e) {
available = false;
}
}
private void loadNames(String name) throws PIMException, SecurityException {
ContactList contactList = null;
try {
// ----
// System.out.println("loadErr1");
contactList = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, name);
// System.out.println(contactList.getName());//--Phone Contacts or Sim Contacts
// First check that the fields we are interested in are supported(MODULARIZE)
if (contactList.isSupportedField(Contact.FORMATTED_NAME)
&& contactList.isSupportedField(Contact.TEL)) {
// ContactLst.append("Reading contacts...", null);
// System.out.println("sup1");
Enumeration items = contactList.items();
// System.out.println("sup2");
Vector telNumbers = new Vector();
telNames = new Vector();
while (items.hasMoreElements()) {
Contact contact = (Contact) items.nextElement();
int telCount = contact.countValues(Contact.TEL);
int nameCount = contact.countValues(Contact.FORMATTED_NAME);
// System.out.println(telCount);
// System.out.println(nameCount);
// we're only interested in contacts with a phone number
// nameCount should always be > 0 since FORMATTED_NAME is
// mandatory
if (telCount > 0 && nameCount > 0) {
String contactName = contact.getString(Contact.FORMATTED_NAME, 0);
// go through all the phone numbers
for (int i = 0; i < telCount; i++) {
System.out.println("Read Telno");
int telAttributes = contact.getAttributes(Contact.TEL, i);
String telNumber = contact.getString(Contact.TEL, i);
System.out.println(telNumber + " " + "tel");
// check if ATTR_MOBILE is supported
if (contactList.isSupportedAttribute(Contact.TEL, Contact.ATTR_MOBILE)) {
if ((telAttributes & Contact.ATTR_MOBILE) != 0) {
telNames.insertElementAt(telNames, i);
telNumbers.insertElementAt(telNumber, i);
} else {
telNumbers.addElement(telNumber);
telNames.addElement(telNames);
}
}
// else {
//// telNames.addElement(contactName);
// telNumbers.addElement(telNumber);
// }
System.out.println("telephone nos");
}
// Shorten names which are too long
shortenName(contactName, 20);
for (int i = 0; i <= telNumbers.size(); i++) {
System.out.println(contactName + " here " + telNames.size());
telNames.addElement(contactName);
System.out.println(telNames.elementAt(i) + " na " + i);
}
names = new String[telNames.size()];
for (int j = 0; j < names.length; j++) {
names[j] = (String) telNames.elementAt(j);
System.out.println(names[j] + "....");
}
// allTelNames.addElement(telNames);
System.out.println("cap :" + telNames.size() + " " + names.length);
// telNames.removeAllElements();
// telNumbers.removeAllElements();
}
}
available = true;
} else {
// ContactLst.append("Contact list required items not supported", null);
available = false;
}
} finally {
// always close it
if (contactList != null) {
contactList.close();
}
}
}

Categories

Resources