Counting occurrences of an item not giving exactly in android - java

I am trying to count the occurrence of the each string. If the month matches with current, then I'm displaying count of the that string.
Suppose this month is 07 and modifiedtime months are like 07, 06, 09, 06, 07 in that what are the month 07 are there for that month what is count of the each item
Example: Month = 07 , count of opportunity should be 1,
output:
What I'm getting :
Count_opportunity:02
Count_proposal:02
Count_negotiation:01
Count_won:32
Count_lost:17
Desired output:
Count_opportunity:01
Count_proposal:0
Count_negotiation:0
Count_won:0
Count_lost:0
The following code gives me a wrong count. Can some-one detect the error?
private void workingOnResponseMonthwiseOpportunity(SyncModule syncModule){
String success = syncModule.getSuccess();
if (success.equals("true")) {
SyncResults results = syncModule.getResult();
Sync sync = results.getSync();
ArrayList<SyncUpdated> syncUpdateds = sync.getUpdated();
for (SyncUpdated syncUpdated : syncUpdateds) {
ArrayList<SyncBlocks> syncBlocks = syncUpdated.getBlocks();
String scheduleDates = "";
String scheduleDate = "";
String supportrequired="";
String winprob="";
String salesstage="";
String modality="";
String modifydatetime="";
String modifiedtime="";
String date1 = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
for (SyncBlocks syncBlocks1 : syncBlocks) {
String label = syncBlocks1.getLabel();
if (label.equals("Basic Information")) {
ArrayList<SynFields> synFields = syncBlocks1.getFields();
for (SynFields synFields1 : synFields) {
name = synFields1.getName();
values = synFields1.getValue();
//sales stage
if (name.equals("sales_stage")) {
salesstage = String.valueOf(values);
salesstage_list.add(salesstage);
//support required
}
}
}
else if (label.equals("Opportunity Details")) {
ArrayList<SynFields> synFields = syncBlocks1.getFields();
for (SynFields synFields1 : synFields) {
String name = synFields1.getName();
values = synFields1.getValue();
if (("modifiedtime".equals(name))) {
modifydatetime = String.valueOf(values);
Log.d("modifydatetime",modifydatetime);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
modifiedmonth= LocalDateTime.from(LocalDateTime.parse(modifydatetime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
Log.d("modifiedmonth", String.valueOf(modifiedmonth));
break;
}
}
}
PreferenceManagerMyOpportunity.getInstance(requireContext()).setMultipleDataOpportunity(scheduleDate, salesstage, supportrequired, winprob, modality,modifiedtime);
}
MyOpportunityModel opportunityModel = new MyOpportunityModel(scheduleDate, salesstage, supportrequired, winprob, modality, modifydatetime);
java.time.LocalDate today = java.time.LocalDate.now();
int month=today.getMonthValue();
Log.d("month",String.valueOf(month));
boolean isModifiedThisMonth =modifiedmonth==month;
Log.d("isModifiedThisMonth",String.valueOf(isModifiedThisMonth));
if (isModifiedThisMonth) {
//Sales stage starts
Count_opportunity = Collections.frequency(salesstage_list, "Opportunity");
System.out.println("Count_opportunity: "+ Count_opportunity);
Count_proposal = Collections.frequency(salesstage_list, "Proposal or Price Quote");
//System.out.println("Count of In Complete is: "+ Count_Incomplete);
Count_negotiation = Collections.frequency(salesstage_list, "Negotiation or Review");
Count_won = Collections.frequency(salesstage_list, "Closed Won");
Count_lost = Collections.frequency(salesstage_list, "Closed Lost");
// System.out.println("Count of Completed is: "+ Complted_Count);
}
}
}
}
}

Related

Java Format Timestamp

I have below Java code to convert string format to Timestamp object
public class TestUtil{
Object result;
Public Object convertFormat(String format, String value, String type){
String format = "yyyyMMddHHmmss";
String value = "20050225144824";
SimpleDateFormat dformat = new SimpleDateFormat(format);
java.util.Date date = dformat.parse(value);
result = new Timestamp(date.getTime);
System.out.println("Result::"+ result);
}
}
Expected outcome:
I was expecting the outcome should be like below
20050225144824
Actual outcome:
2005-02-25 14:48:24.0
Could anyone tell me what I am missing here? To get "20050225144824" this result
The below code runs fine for me.
Adding few print statements to explain the different behaviors.
import java.util.Date;
import java.text.SimpleDateFormat;
import java.sql.Timestamp;
public class Main
{
public static void main(String[] args) {
String myFormat = "yyyyMMddHHmmss";
String value = "20050225144824";
try {
SimpleDateFormat dformat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = dformat.parse(value);
Timestamp ts = new Timestamp(date.getTime());
Object result = new Timestamp(date.getTime());
System.out.println("Timestamp Format with yyyyMMddHHmmss : " +dformat.format(ts));
System.out.println("Object Format with yyyyMMddHHmmss : " +result);
System.out.println("Object Format with yyyyMMddHHmmss : " +dformat.format(result));
} catch(Exception e) {
e.printStackTrace();
}
}
}
Here is the output of the different behaviors :
Timestamp Format with yyyyMMddHHmmss : 20050225144824
Object Format with yyyyMMddHHmmss : 2005-02-25 14:48:24.0
Object Format with yyyyMMddHHmmss : 20050225144824
If you expect Timestamp to return your custom output then you need to override the default Timestamp library.
Here I create CustomTimestamp.java to extend Timestamp and override its toString() method. I modified the changes according to your requirement.
public class CustomTimestamp extends Timestamp {
private int nanos;
public CustomTimestamp(long time) {
super(time);
}
#Override
public String toString () {
int year = super.getYear() + 1900;
int month = super.getMonth() + 1;
int day = super.getDate();
int hour = super.getHours();
int minute = super.getMinutes();
int second = super.getSeconds();
String yearString;
String monthString;
String dayString;
String hourString;
String minuteString;
String secondString;
String nanosString;
String zeros = "000000000";
String yearZeros = "0000";
StringBuffer timestampBuf;
if (year < 1000) {
// Add leading zeros
yearString = "" + year;
yearString = yearZeros.substring(0, (4-yearString.length())) +
yearString;
} else {
yearString = "" + year;
}
if (month < 10) {
monthString = "0" + month;
} else {
monthString = Integer.toString(month);
}
if (day < 10) {
dayString = "0" + day;
} else {
dayString = Integer.toString(day);
}
if (hour < 10) {
hourString = "0" + hour;
} else {
hourString = Integer.toString(hour);
}
if (minute < 10) {
minuteString = "0" + minute;
} else {
minuteString = Integer.toString(minute);
}
if (second < 10) {
secondString = "0" + second;
} else {
secondString = Integer.toString(second);
}
if (nanos == 0) {
nanosString = "";
} else {
nanosString = Integer.toString(nanos);
// Add leading zeros
nanosString = zeros.substring(0, (9-nanosString.length())) +
nanosString;
// Truncate trailing zeros
char[] nanosChar = new char[nanosString.length()];
nanosString.getChars(0, nanosString.length(), nanosChar, 0);
int truncIndex = 8;
while (nanosChar[truncIndex] == '0') {
truncIndex--;
}
nanosString = new String(nanosChar, 0, truncIndex + 1);
}
// do a string buffer here instead.
timestampBuf = new StringBuffer(20+nanosString.length());
timestampBuf.append(yearString);
timestampBuf.append(monthString);
timestampBuf.append(dayString);
timestampBuf.append(hourString);
timestampBuf.append(minuteString);
timestampBuf.append(secondString);
timestampBuf.append(nanosString);
return (timestampBuf.toString());
}
}
Your main class should use CustomTimestamp to get the output
try {
String format = "yyyyMMddHHmmss";
String value = "20050225144824";
SimpleDateFormat dformat = new SimpleDateFormat(format);
java.util.Date date;
date = dformat.parse(value);
Timestamp result = new CustomTimestamp(date.getTime());
System.out.println("Result::" + result);
} catch (ParseException e) {
e.printStackTrace();
}

How to proceed to the next iteration of a loop whenever the program fails to read files

I'm creating a program that can read .log files in certain directories and then dumps the data from the .log files into a local database.
However, i noticed in my testing that whenever the program reads the files and i happen to access the files during the test run - the program freezes.
How do i solve this issue?
public static void file(File[] files)
{
try
{
for (File lister : files)
{
System.out.println("HERE " + lister);
in = new FileReader(lister);
br = new BufferedReader(in);
try
{
while ((sCurrentLine = br.readLine()) != null)
{
if (sCurrentLine.contains("Performance"))
{
String[] aCurrentLine = sCurrentLine.split("\\|");
if (aCurrentLine.length >= 6) {
Date date = dateinsert.parse(aCurrentLine[0]);
CurrentTime = dateinsert.format(date);
CurrentFlow = aCurrentLine[2];
CurrentModule = aCurrentLine[5];
CurrentType = aCurrentLine[4];
sCurrentID = aCurrentLine[6];
aCurrentLine = aCurrentLine[6].split("ORDER_ID");
if (aCurrentLine.length >= 2)
{
aCurrentLine[1] = aCurrentLine[1].replace (":", "");
aCurrentLine[1] = aCurrentLine[1].replace (" ", "");
aCurrentLine[1] = aCurrentLine[1].replace ("_", "");
aCurrentLine[1] = aCurrentLine[1].replace ("{", "");
aCurrentLine[1] = aCurrentLine[1].replace ("}", "");
aCurrentLine = aCurrentLine[1].split ("\"");
sCurrentID = aCurrentLine[2];
}
else // Happens when there's no order id
{
sCurrentID = "N/A";
}
cal = Calendar.getInstance();
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
datenum = cal.get(Calendar.DAY_OF_MONTH);
hour = cal.get(Calendar.HOUR_OF_DAY);
minute = cal.get(Calendar.MINUTE);
second = cal.get(Calendar.SECOND);
if (month<9)
{
month = month + 1;
smonth = "0" + Integer.toString(month);
}
else
{
month = month + 1;
smonth = Integer.toString(month);
}
if (datenum<10)
{
sdatenum = "0" + Integer.toString(datenum);
}
else
{
sdatenum = Integer.toString(datenum);
}
if (hour<10)
{
shour = "0" + Integer.toString(hour);
}
else
{
shour = Integer.toString(hour);
}
if (minute<10)
{
sminute = "0" + Integer.toString(minute);
}
else
{
sminute = Integer.toString(minute);
}
if (second<10)
{
ssecond = "0" + Integer.toString(second);
}
else
{
ssecond = Integer.toString(second);
}
scalendar = Integer.toString(year) + "-" + smonth + "-" + sdatenum + " " + shour + ":" + sminute+ ":" + ssecond;
ls.insertdata(sCurrentID, CurrentTime, CurrentFlow, CurrentModule, CurrentType, scalendar);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
flag = 0;
}
}
1 - Do you need to worry about the fact that it does not work when the file is open or are you just interested in why it does not work as expected ?
2 - All of the code that you wrote to determine the value for scalendar can be reduced to 2 lines of code :
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(Calendar.getInstance().getTime());
Here is unit test
#Test
public void quickTest() {
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(Calendar.getInstance().getTime());
System.out.println(formattedDate);
}
where the result will look similar to : 2018-03-19 06:42:58

How to read a date of birth from a txt file and check if older than 18

I have a text file which contains a list of athletes with their date of birth.
I'm trying to figure out how I can read from the text file only the athletes who are on the "elite" team and who are older than 18.
I have figured out how to get only the "elite" athletes, but I can't think of how to solve the age problem.
The birthdates are created separated integers day, month and year
This is the code I've been working on
public void readUngdomElite() throws FileNotFoundException, IOException {
BufferedReader br = null;
try {
String sCurrentLine;
//file to read
br = new BufferedReader(new FileReader("medlemlist.txt"));
while ((sCurrentLine = br.readLine()) != null) {
if (sCurrentLine.contains("elite")) {
System.out.println(sCurrentLine);
}}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
This code gets me all the athletes who are elite, but I want the elite athletes who are older than 18.
Firstly you should provide a .txt file content. But to check if team is older than 18 years you can use this method. Date there is String type and YYYY-MM-dd format.
public boolean isAdult(String birthday) {
String[] parts = birthday.split("-");
if (parts.length==3) {
int year = Integer.parseInt(parts[0]);
int month = Integer.parseInt(parts[1]);
int day = Integer.parseInt(parts[2]);
String currentDate = getCurrentDate();
if (!currentDate.isEmpty() && currentDate.contains("-")) {
String[] parts2 = currentDate.split("-");
if (parts2.length==3) {
int cYear = Integer.parseInt(parts2[0]);
int cMonth = Integer.parseInt(parts2[1]);
int cDay = Integer.parseInt(parts2[2]);
int rYear = cYear - year;
int rMonth = cMonth - month;
int rDay = cDay - day;
if (rMonth<0)
rYear = rYear - 1;
else if (rMonth == 0 && rDay<0)
rYear = rYear - 1;
if (rYear > 17)
return true;
}
}
}
return false;
}
private String getCurrentDate() {
Date todayDate = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String todayString = formatter.format(todayDate);
return (todayString!=null)? todayString : "";
}
Feel free to edit the code as you need
The new Date and Time library provides you with convenient methods such as:
LocalDate.of(2015, 02, 20);
LocalDate.parse("2015-02-20");
Period.between(firstDate, secondDate)
With that it shouldn't be too hard to find an age based on how your string looks.
String str = "12 01 1996";
String[] arr = str.split(" ");
LocalDate birth = LocalDate.of(Integer.valueOf(arr[2]), Integer.valueOf(arr[1]), Integer.valueOf(arr[0]));
LocalDate now = LocalDate.now();
if (Period.between(birth, now).getYears() > 18) {
System.out.println("major");
} else {
System.out.println("minor");
}

Java Stock Viewer Application Issue

For the past few hours, I've been trying to figure out my problem with this stock viewer application. I had it working perfectly fine yesterday, did some edits today, then attempted to revert it back to its original form. Now, instead of printing all the stock prices from the dates listed in StockClient (January 7, 2016 to January 7, 2017), it starts in February instead. Please help!
STOCK VIEWER CLASS:
import java.util.*;
import java.net.URL;
import java.net.URLConnection;
public class StockViewer
{
private ArrayList<String> dates;
private ArrayList<String> opens;
private ArrayList<String> highs;
private ArrayList<String> lows;
private ArrayList<String> closes;
private ArrayList<String> volumes;
private ArrayList<String> adjCloses;
private String sym;
private boolean success = false;
public StockViewer(String symbol)
{
dates = new ArrayList<String>();
opens = new ArrayList<String>();
highs = new ArrayList<String>();
lows = new ArrayList<String>();
closes = new ArrayList<String>();
volumes = new ArrayList<String>();
adjCloses = new ArrayList<String>();
sym = symbol;
}
public void viewStock(GregorianCalendar begin, GregorianCalendar fin)
{
while(!success)
{
String url = "http://chart.finance.yahoo.com/table.csv?s=" + sym +
"&a=" + begin.get(Calendar.MONTH) +
"&b=" + begin.get(Calendar.DAY_OF_MONTH) +
"&c=" + begin.get(Calendar.YEAR) +
"&d=" + fin.get(Calendar.MONTH) +
"&e=" + fin.get(Calendar.DAY_OF_MONTH) +
"&f=" + fin.get(Calendar.YEAR) +
"&g=d&ignore=.csv";
try
{
URL yhooFin = new URL(url);
URLConnection data = yhooFin.openConnection();
Scanner input = new Scanner(data.getInputStream());
if(input.hasNext()) // skip a line (that's the header)
input.nextLine();
// start reading data
while(input.hasNextLine())
{
String line = input.nextLine();
String[] elements = line.split(",");
success = true;
dates.add(elements[0]);
opens.add(elements[1]);
highs.add(elements[2]);
lows.add(elements[3]);
closes.add(elements[4]);
volumes.add(elements[5]);
adjCloses.add(elements[6]);
for(int count = 0; count < elements.length; count++)
{
if(count < 6)
System.out.print(elements[count] + " - ");
else
System.out.print(elements[count] + "\n");
}
}
}
catch(Exception e)
{}
}
}
public void viewStockCurrent(GregorianCalendar c1, GregorianCalendar c2)
{
viewStock(c1, c2);
}
}
STOCK CLIENT CLASS:
import java.util.*;
public class StockClient
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a stock symbol: ");
String symbol = scan.next();
StockViewer stock = new StockViewer(symbol);
GregorianCalendar start = new GregorianCalendar(2016, 1, 7);
GregorianCalendar end = new GregorianCalendar(2017, 1, 7);
stock.viewStock(start, end);
}
}
Month property is zero based, you have wrong value in
GregorianCalendar start = new GregorianCalendar(2016, 1, 7);
GregorianCalendar end = new GregorianCalendar(2017, 1, 7);
See Calendar.MONTH for details.
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

Converting Youtube Data API V3 video duration to hh:mm:ss format in java?

I am using Youtube data api v3 to get video information like title, views count and duration.The duration value is new to me as it's an ISO8601 date which I need to convert to a readable format like hh:mm:ss. Duration can have the following different values:
PT1S --> 00:01
PT1M --> 01:00
PT1H --> 01:00:00
PT1M1S --> 01:01
PT1H1S --> 01:00:01
PT1H1M1S --> 01:01:01
I could use Joda Time library to parse the value and calculate the duration in seconds but the library is of 500kb in size which will increase the size of my application that I don't want.
look at this code :
private static HashMap<String, String> regexMap = new HashMap<>();
private static String regex2two = "(?<=[^\\d])(\\d)(?=[^\\d])";
private static String two = "0$1";
public static void main(String[] args) {
regexMap.put("PT(\\d\\d)S", "00:$1");
regexMap.put("PT(\\d\\d)M", "$1:00");
regexMap.put("PT(\\d\\d)H", "$1:00:00");
regexMap.put("PT(\\d\\d)M(\\d\\d)S", "$1:$2");
regexMap.put("PT(\\d\\d)H(\\d\\d)S", "$1:00:$2");
regexMap.put("PT(\\d\\d)H(\\d\\d)M", "$1:$2:00");
regexMap.put("PT(\\d\\d)H(\\d\\d)M(\\d\\d)S", "$1:$2:$3");
String[] dates = { "PT1S", "PT1M", "PT1H", "PT1M1S", "PT1H1S", "PT1H1M", "PT1H1M1S", "PT10H1M13S", "PT10H1S", "PT1M11S" };
for (String date : dates) {
String d = date.replaceAll(regex2two, two);
String regex = getRegex(d);
if (regex == null) {
System.out.println(d + ": invalid");
continue;
}
String newDate = d.replaceAll(regex, regexMap.get(regex));
System.out.println(date + " : " +newDate);
}
}
private static String getRegex(String date) {
for (String r : regexMap.keySet())
if (Pattern.matches(r, date))
return r;
return null;
}
The regex2two has been used to add a leading zero0 to 1-digit numbers. you can try this demo.
In the regexMap I'v stored all 7 cases and appropriate regex-replace.
I did by myself
Let's try
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.
public class YouTubeDurationUtils {
/**
*
* #param duration
* #return "01:02:30"
*/
public static String convertYouTubeDuration(String duration) {
String youtubeDuration = duration; //"PT1H2M30S"; // "PT1M13S";
Calendar c = new GregorianCalendar();
try {
DateFormat df = new SimpleDateFormat("'PT'mm'M'ss'S'");
Date d = df.parse(youtubeDuration);
c.setTime(d);
} catch (ParseException e) {
try {
DateFormat df = new SimpleDateFormat("'PT'hh'H'mm'M'ss'S'");
Date d = df.parse(youtubeDuration);
c.setTime(d);
} catch (ParseException e1) {
try {
DateFormat df = new SimpleDateFormat("'PT'ss'S'");
Date d = df.parse(youtubeDuration);
c.setTime(d);
} catch (ParseException e2) {
}
}
}
c.setTimeZone(TimeZone.getDefault());
String time = "";
if ( c.get(Calendar.HOUR) > 0 ) {
if ( String.valueOf(c.get(Calendar.HOUR)).length() == 1 ) {
time += "0" + c.get(Calendar.HOUR);
}
else {
time += c.get(Calendar.HOUR);
}
time += ":";
}
// test minute
if ( String.valueOf(c.get(Calendar.MINUTE)).length() == 1 ) {
time += "0" + c.get(Calendar.MINUTE);
}
else {
time += c.get(Calendar.MINUTE);
}
time += ":";
// test second
if ( String.valueOf(c.get(Calendar.SECOND)).length() == 1 ) {
time += "0" + c.get(Calendar.SECOND);
}
else {
time += c.get(Calendar.SECOND);
}
return time ;
}
}
Had to deal with this problem as well. I had to convert the length to milliseconds, but once you get the secs/mins/hours variables populated you can convert to any format you want:
// Test Value
$vidLength = 'PT1H23M45S';
$secs = '';
$mins = '';
$hours = '';
$inspecting = '';
for($i=(strlen($vidLength)-1); $i>0; $i--){
if(is_numeric($vidLength[$i])){
if($inspecting == 'S'){
$secs = $vidLength[$i].$secs;
}
else if($inspecting == 'M'){
$mins = $vidLength[$i].$mins;
}
else if($inspecting == 'H'){
$hours = $vidLength[$i].$hours;
}
}
else {
$inspecting = $vidLength[$i];
}
}
$lengthInMS = 1000*(($hours*60*60) + ($mins*60) + $secs);
I needed a array of all these converted duration. So I wrote the below as a workaround and also java.time.duration was not working for me, don't know why.
String[] D_uration = new String[10];
while(iteratorSearchResults.hasNext()){String Apiduration1=Apiduration.replace("PT","");
if(Apiduration.indexOf("H")>=0){
String Apiduration2=Apiduration1.replace("H",":");
if(Apiduration.indexOf("M")>=0){
String Apiduration3=Apiduration2.replace("M",":");
if(Apiduration.indexOf("S")>=0){
D_uration[i]=Apiduration3.replace("S","");
}
else{
String Apiduration4=Apiduration2.replace("M",":00");
D_uration[i]=Apiduration4;
}
}
else{
String Apiduration4=Apiduration2.replace(":",":00:");
if(Apiduration.indexOf("S")>=0){
D_uration[i]=Apiduration4.replace("S","");
}
else{
String Apiduration3=Apiduration4.replace(":00:",":00:00");
D_uration[i]=Apiduration3;
}
}
}
else{
if(Apiduration.indexOf("M")>=0){
String Apiduration2=Apiduration1.replace("M",":");
if(Apiduration.indexOf("S")>=0){
D_uration[i]=Apiduration2.replace("S","");
}
else{
String Apiduration4=Apiduration2.replace(":",":00");
D_uration[i]=Apiduration4;
}
}
else{
D_uration[i]=Apiduration1.replace("S","");
}
}
"Apiduration" is returned by the Youtube data Api in ISO8601 format.
Made some edits now i think it should work fine.

Categories