I have application which keeps listening on a port and if any request comes ,processes and sends the response back.I have redirected System.out.println of the program to a text file. I want the file to be rolledout everyday.But i don see a rollout at 12.00 am .Sometimes rollout happens and sometimes logs are appended on yesterday's file itself. Code snippet given below.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MBServ {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
String request_date = null;
String request_time = null;
String logFile="MBServ_";
ConnectServiceInfo fiServiceInfo = ConnectServiceInfo.getInstance();
ConnectServiceInfo fiservice = fiServiceInfo.getInstance();
try {
serverSocket = new ServerSocket(1122);
} catch (IOException e) {
System.exit(-1);
}
while (listening) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
request_date = sdf.format(date);
logFile="MBServ_"+request_date+".log";
System.setOut(new PrintStream(new FileOutputStream(logFile,true)));
new MBServT(serverSocket.accept(), fiservice).start();
}
serverSocket.close();
}
}
I think you have to force the creation of the file before using it.
Here's an exmaple :
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
request_date = sdf.format(date);
logFile="MBServ_"+request_date+".log";
File file = new File(logFile);
file.createNewFile();
...
Documentation : https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile()
Related
These codes:
String genType = FileConstants.CHANGE_CYCLE;
ResultTable[] genericCode = RTManager.getRTCsmGenericCodesDecodeList(genType);
String genCode = Arrays.toString(genericCode);
Returns these values:
genCode = [[code=22:00:00]
[dCode=Cut-off time for change bill_cycle if existing cycle_close_date=activity_date]]
Question: how do i get only '22:00:00' and convert it as Time datatype?
If the item in the ResultTable array has a toString() and it produces string then you can get it like this.
genericCode[0].toString().split("=")[1]
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateExample {
public static void main(String[] args) {
String time = "22:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date;
try {
date = sdf.parse(time);
System.out.println("Time: " + sdf.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I'm trying to convert a string date to a an object date.
It works perfectly if i use a string, but when i read the string date from a file, the result is ko.
On forums, i have found the cause may come from zone. It is still KO.
I'm unable to say why the dateformat rise an exception. :o(
A snippet of my code :
package main;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
public class dateTestConv {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String dateOK1 = new String("21/01/2017");
convertDateStringEuroToDateObject(dateOK1);
String dateOK2= "21/01/2017";
convertDateStringEuroToDateObject(dateOK2);
//From file =KO
collectDateFromFile();
}
public static Date convertDateStringEuroToDateObject(String date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy",Locale.FRANCE);
Date d = null;
try {
dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
d = dateFormat.parse(date);
} catch (ParseException ex) {
Logger.getLogger(dateTestConv.class.getName()).log(Level.SEVERE, null, ex);
}
return d;
}
public static void collectDateFromFile(){
String dirName=new String("dates.txt");
File file = new File(dirName);
try {
FileInputStream fstreami = new FileInputStream(dirName);
DataInputStream in = new DataInputStream(fstreami);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String dateFormatNormal = strLine;
Date d0= convertDateStringEuroToDateObject(dateFormatNormal);
}
in.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
The file dates.txt contains just one line :
21/01/2017
When the method collectDateFromFile() is called , this exception is rised :
SEVERE: null
java.text.ParseException: Unparseable date: "21/01/2017"
at java.text.DateFormat.parse(DateFormat.java:366)
at main.dateTestConv.convertDateStringEuroToDateObject(dateTestConv.java:52)
at main.dateTestConv.collectDateFromFile(dateTestConv.java:75)
at main.dateTestConv.main(dateTestConv.java:42)
Thanks for your help.
Simply put, the string is not what you think it is. So you need to debug it by comparing the received with the expected value. For example, if there is an unexpected unicode codepoint hiding in there, you might detect it like this:
String dateFormatNormal = strLine;
/* Debug: is there an unexpected unicode codepoint hiding in there? */
System.out.println("Received: " + dateFormatNormal.codePoints()
.mapToObj(i -> String.format("0x%04x (%s)", i, String.valueOf(Character.toChars(i))))
.collect(Collectors.toList()));
System.out.println("Expected: " + "21/01/2017".codePoints()
.mapToObj(i -> String.format("0x%04x (%s)", i, String.valueOf(Character.toChars(i))))
.collect(Collectors.toList()));
/* Remove Debug code when done */
It could be due to space in string. Try trim on string and then parse
i am trying to code for a new file existed in folder or not by passing specific time stamp through javacode but i am not getting it ..can u help...
String filePath = System.getProperty("user.dir");
//create a new file with Time Stamp
File file = new File(filePath + "\\" + filename+GetCurrentTimeStamp().replace(":","_").replace(".","_")+".txt");
try {
if (!file.exists()) {
file.createNewFile();
System.out.println("File is created; file name is " + file.getName());
} else {
System.out.println("File already exist");
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Get current system time
public static String GetCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");// dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
// Get Current Host Name
public static String GetCurrentTestHostName() throws UnknownHostException {
InetAddress localMachine = InetAddress.getLocalHost();
String hostName = localMachine.getHostName();
return hostName;
}
// Get Current User Name
public static String GetCurrentTestUserName() {
return System.getProperty("user.name");
package com.test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class trst {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
boolean b = false;
File file, file1;
Date today = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("MMddyyyyhhmmss");
String folder_name="backup_"+ft.format(today);
file = new File("./"+folder_name);
if (!file.exists())
{
b = file.mkdirs();
}
file1 = new File(file+"/"+"Test");
FileWriter fileWriter = new FileWriter(file1);
fileWriter.write("abc");
fileWriter.flush();
fileWriter.close();
if (b)
System.out.println("Backup has been created.");
else
System.out.println("Failed to create backup.");
}
}
I have written few lines of code which reads data from the cookies stored in a text file and then write it on the web browser whenever required.
Block of code which i am using to store and write the cookies on a text file-
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class StoreCookieInfo {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","D:\\Java Programs and files\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.facebook.com");
driver.findElement(By.name("email")).sendKeys("Your username");
driver.findElement(By.name("pass")).sendKeys("Your password");
driver.findElement(By.name("persistent")).click();
driver.findElement(By.name("pass")).submit();
File f = new File("browser.data");
try{
f.delete();
f.createNewFile();
FileWriter fos = new FileWriter(f);
BufferedWriter bos = new BufferedWriter(fos);
for(Cookie ck : driver.manage().getCookies()) {
bos.write((ck.getName()+";"+ck.getValue()+";"+ck.getDomain()
+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure()));
bos.newLine();
}
bos.flush();
bos.close();
fos.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
It is running fine and storing data on text file.
Block of code which i am using to read cookies from the text file-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Date;
import java.util.StringTokenizer;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class LoadCookieInfo {
#SuppressWarnings("deprecation")
public static void main(String[] args){
System.setProperty("webdriver.chrome.driver","D:\\Java Programs and files\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//WebDriver driver = new FirefoxDriver();
driver.get("http://www.facebook.com");
try{
File f2 = new File("browser.data");
FileReader fr = new FileReader(f2);
BufferedReader br = new BufferedReader(fr);
String line;
while((line=br.readLine())!=null){
StringTokenizer str = new StringTokenizer(line,";");
while(str.hasMoreTokens()){
String name = str.nextToken();
String value = str.nextToken();
String domain = str.nextToken();
String path = str.nextToken();
System.out.println("1");
Date expiry = null;
String dt;
if(!(dt=str.nextToken()).equals("null")){
expiry = new Date(dt);
}
boolean isSecure = new Boolean(str.nextToken()).booleanValue();
Cookie ck = new Cookie(name,value,domain,path,expiry,isSecure);
driver.manage().addCookie(ck);
System.out.println(name+value);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
driver.get("http://www.facebook.com");
}
}
When i am trying to run the second code i am getting the following exception on date -
java.lang.IllegalArgumentException
at java.util.Date.parse(Unknown Source)
at java.util.Date.<init>(Unknown Source)
at com.Selenium_Practice.LoadCookieInfo.main(LoadCookieInfo.java:39)
This is the first time i am trying to read data using cookies so i am not able to figure out what wrong i am doing in the code.
In java to convert a string into a date object use SimpleDateFormat Class.It is a concrete class for formatting and parsing dates.It allows you to start by choosing any user-defined patterns for date-time formatting
In the browser.data file the date is saved in format Sat Oct 03 01:12:17 IST 2015
So use a SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy")
E----->Day name in week(Sat)
MMM----->Month (Oct)
dd------>Day in month(03)
HH:mm:ss---->Hours:minutes:seconds(01:12:17)
Z----->Time Zone(IST)
yyyy---->Year(2015)
Date expiry = null;
SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
try {
String dt;
if(!(dt=str.nextToken()).equals("null")){
expiry = formatter.parse(dt);
System.out.println(expiry);
System.out.println(formatter.format(expiry));
}
} catch (ParseException e) {
e.printStackTrace();
}
I tested the above code it was working fine.I was able to add the cookie successfully after applying the above changes to LoadCookieInfo class
Hope this helps you...Kindly get back if you have any queries
The exception java.lang.IllegalArgumentException is thrown because you are passing String as a parameter to the Date constructor, that is deprecated and replaced by DateFormat.parse(String s).
String dt;
if(!(dt=str.nextToken()).equals("null")){
expiry = new Date(dt);
}
Try Using:
SimpleDateFormat formatter = new SimpleDateFormat("("E MMM dd HH:mm:ss Z yyyy")");
Date date = formatter.parse(dt);
There seems to be issue with your if condition also. (dt=str.nextToken()) will assign the value and give you true always, never equaling to null.
Let me know if it works with above solution.
I have a JDateChooser bean panel named basDate. When i execute System.out.println(basDate.getText()); it returns 12.02.2014 But i must convert and edit it to 2014-02-12 00:00:00.000
Just i want edit and assign new output to a variable coming as "12.02.2014" value as "2014-02-12 00:00:00.000"
I use Netbeans Gui Builder.
Since the input date is a string in a different format from what you want, you need to two SimpleDateFormats. One to parse the String to a Date and another to format the Date to a different format.
Test this out. input 12.02.2014 output 2014-12-02 00:00:00:000
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MyDateFormat {
public static void main(String[] args){
String inputStringDate = "12.02.2014";
SimpleDateFormat inputFormat = new SimpleDateFormat("dd.MM.yyyy");
Date inputDate = null;
try {
inputDate = inputFormat.parse(inputStringDate);
} catch (ParseException ex) {
Logger.getLogger(MyDateFormat.class.getName()).log(Level.SEVERE, null, ex);
}
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss:SSS");
String outputStringDate = outputFormat.format(inputDate);
System.out.println(outputStringDate);
}
}