Tomcat not logging to file - java

Hi wrote my own little Logger class to write log output into files, the class looks like this:
public class Logger {
private String prefix;
private String pathToLogFiles = "/tmp/sos/logs/";
private String infoLog;
private String errorLog;
private boolean doLogtoFile;
public Logger(String prefix, Class classname, boolean logToFile) {
this.prefix = "[" + prefix + "]";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
this.infoLog = this.pathToLogFiles + "info_" + sdf.format(now) + ".log";
this.errorLog = this.pathToLogFiles + "error_" + sdf.format(now) + ".log";
this.doLogtoFile = logToFile;
System.out.println("Will log to: " + this.infoLog + " and " + this.errorLog);
}
public void info(String message) {
String logmessage = prefix + " INFO " + message;
if( this.doLogtoFile ) {
try {
Files.write(Paths.get(infoLog), logmessage.getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
System.out.println(prefix + message);
}
} else {
System.out.println(prefix + message);
}
}
public void error(String message) {
String logmessage = prefix + " ERROR " + message;
if( this.doLogtoFile ) {
try {
Files.write(Paths.get(errorLog), logmessage.getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
System.out.println(prefix + message);
}
} else {
System.out.println(prefix + message);
}
}
}
Permissions of the directory and subdirectories are all set up correctly and owned by the tomcat user. However I don't receive any logoutput, nor are the log files even created.
Could anyone see what could be going wrong?
Strangely enough I am not getting any Exception
Many thanks for any help

Related

How to read values from properties file and use it in final class

Here is my final class "Constants"
#Component
public final class Constants {
#Value("${db2.schema}")
private static String Schema;
public static final String STUDENT_TABLE = Schema + ".Student";
}
I have db2.schema in my properties file :
db2.schema = ${DB2_SCHEMA}
DB2_SCHEMA = D5677ESB
#Value can not be used with static fields
You can use like:
...
public class Constants {
public static final String NewOrder = "neworder";
public static final String POST = "POST";
public static final String CONTENT_TYPE = "Content-Type";
public static final String APPLICATION_TYPE = "application/json";
public static final String ACCEPT = "Accept";
public static final String CART_URL = PropsUtil.get("order.inquiry.search.insertCartDataURL");
}
...
** or check this code:**
...
public String getPropValues() throws IOException {
try {
Properties prop = new Properties();
String propFileName = "config.properties";
inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
Date time = new Date(System.currentTimeMillis());
// get the property value and print it out
String user = prop.getProperty("user");
String company1 = prop.getProperty("company1");
String company2 = prop.getProperty("company2");
String company3 = prop.getProperty("company3");
result = "Company List = " + company1 + ", " + company2 + ", " + company3;
System.out.println(result + "\nProgram Ran on " + time + " by user=" + user);
} catch (Exception e) {
System.out.println("Exception: " + e);
} finally {
inputStream.close();
}
return result;
} ...

Have problem with understanding threads and changing variable in multiple threads

I am trying to restrict the amount of clients on my server,so i just sending message from my server when it is full and print it in my client by ending process for him.But as i use multiple threads i cant stop my writeMessage thread
Tried AtomicBoolean,but i didnt work
public class Client {
private static final Logger LOGGER = LogManager.getLogger();
private BufferedReader consoleReader;
private String name;
private String address;
private int port;
private Thread writeMessage, readMessage;
private ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
private LocalTime dTime = zonedDateTime.toLocalTime();
private Net net;
private AtomicBoolean running = new AtomicBoolean(true);
public Client(String address, int port) {
this.address = address;
this.port = port;
net = new Net(address, port);
consoleReader = new BufferedReader(new InputStreamReader(System.in));
printName();
readMessage();
writeMessage();
}
private void printName() {
System.out.println("Print your name:");
try {
name = consoleReader.readLine();
while (NameValidator.nameIsValid(name)) {
System.out.println("Name should contain more than 1 letter");
name = consoleReader.readLine();
}
net.send(name + "\n");
} catch (IOException e) {
LOGGER.error(e);
}
}
private void readMessage() {
readMessage = new Thread(() -> {
String str = net.receive();
while (net.isConnected()) {
if ("full".equals(str)) {
System.out.println("server is full");
running.set(false);
break;
} else {
System.out.println(str);
str = net.receive();
}
}
net.offService();
}, "readMessage");
readMessage.start();
}
private void writeMessage() {
writeMessage = new Thread(() -> {
while (running.get()) {
String userWord;
try {
String time = dTime.getHour() + ":" + dTime.getMinute() + ":" + dTime.getSecond();
userWord = consoleReader.readLine();
if (userWord.equals("quit")) {
net.send(userWord + "\n");
ClientAmountGenerator.decrement();
running.set(false);
} else {
net.send("(" + time + ") " + name + " says : " + userWord + "\n");
}
} catch (IOException e) {
LOGGER.error(e);
}
}
net.offService();
}, "writeMessage");
writeMessage.start();
}
}
I want to change running to "false",so the writeMessage thread wont work if it gets message "full" from the server

Cannot read documents as Java classes

I am using ArangoDB 3.1.23 and the ArangoDB Java driver 4.2.2. I am using Eclipse and Maven. I am having troubles to read documents as Java classes, as it is explained here. I followed the tutorial, and wrote the following test code.
As you can see, reading documents as BaseDocument or VelocyPack works, but reading them as Java classes returns a null.
public static void main(String[] args) {
class MyObject {
private String key;
private String name;
private int age;
public MyObject(String name, int age) {
this();
this.name = name;
this.age = age;
}
public MyObject() {
super();
}
}
final String dbName = "testdb";
final String collName = "testCollection";
ArangoDB arangoDB = new ArangoDB.Builder().user("root").password("").build();
// Delete existing database
try{
System.out.println("Deleted existing " + dbName + " database: " + arangoDB.db(dbName).drop());
} catch (Exception e) {
System.err.println("Error while deleting database " + dbName);
}
// Test database creation
try {
arangoDB.createDatabase(dbName);
System.out.println("Created database " + dbName);
} catch (Exception e) {
System.err.println("Did not create database " + dbName);
}
// Test collection creation
try {
arangoDB.db(dbName).createCollection(collName);
System.out.println("Created collection " + collName);
} catch (Exception e) {
System.err.println("Did not create collection " + collName);
}
// Test custom class document insertion
String key1 = null;
try {
MyObject myObject = new MyObject("Homer", 38);
key1 = arangoDB.db(dbName).collection(collName).insertDocument(myObject).getKey();
System.out.println("Inserted new document as MyObject. key: " + myObject.key + ", " + key1);
} catch (Exception e) {
System.err.println("Did not insert new document");
}
// Test BaseDocument class document insertion
String key2 = null;
try {
BaseDocument myBaseDocument = new BaseDocument();
myBaseDocument.addAttribute("name", "Paul");
myBaseDocument.addAttribute("age", 23);
key2 = arangoDB.db(dbName).collection(collName).insertDocument(myBaseDocument).getKey();
System.out.println("Inserted new document as BaseDocument. key: " + myBaseDocument.getKey() + ", " + key2);
} catch (Exception e) {
System.err.println("Did not insert new document");
}
// Test read as VPackSlice
String keyToRead1 = key1;
VPackSlice doc1 = arangoDB.db(dbName).collection(collName).getDocument(keyToRead1, VPackSlice.class);
if (doc1 != null)
System.out.println("Open document " + keyToRead1 + " VPackSlice: " + doc1.get("name").getAsString() + " " + doc1.get("age").getAsInt());
else
System.err.println("Could not open the document " + keyToRead1 + " using VPackSlice");
// Test read as BaseDocument
String keyToRead2 = key1;
BaseDocument doc2 = arangoDB.db(dbName).collection(collName).getDocument(keyToRead2, BaseDocument.class);
if (doc2 != null)
System.out.println("Open document " + keyToRead2 + " as BaseDocument: " + doc2.getAttribute("name") + " " + doc2.getAttribute("age"));
else
System.err.println("Could not open the document " + keyToRead2 + " as BaseDocument");
// Test read as MyObject
String keyToRead3 = key1;
MyObject doc3 = arangoDB.db(dbName).collection(collName).getDocument(keyToRead3, MyObject.class);
if (doc3 != null)
System.out.println("Open document " + keyToRead3 + " as MyObject: " + doc3.name + " " + doc3.age);
else
System.err.println("Could not open the document " + keyToRead3 + " as MyObject");
}
Result:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Deleted existing testdb database: true
Created database testdb
Created collection testCollection
Inserted new document as MyObject. key: null, 3510088
Inserted new document as BaseDocument. key: 3510092, 3510092
Open document 3510088 VPackSlice: Homer 38
Open document 3510088 as BaseDocument: Homer 38
Could not open the document 3510088 as MyObject
I was able to get your example to work by moving the MyObject to it's own file. I think it might be due to the inline object as I tried adding the annotation and getters/setters inline and that didn't work either. Like so:
import com.arangodb.entity.DocumentField;
import com.arangodb.entity.DocumentField.Type;
public class MyObject {
#DocumentField(Type.KEY)
private String key;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private String name;
private int age;
public MyObject(String name, int age) {
this();
this.name = name;
this.age = age;
}
public MyObject() {
super();
}
}
And
// Test read as MyObject
String keyToRead3 = key1;
MyObject doc3 = arangoDB.db(dbName).collection(collName).getDocument(keyToRead3, MyObject.class);
if (doc3 != null)
System.out.println("Open document " + keyToRead3 + " as MyObject: " + doc3.getName() + " " + doc3.getAge());
else
System.err.println("Could not open the document " + keyToRead3 + " as MyObject");
Which produces
Inserted new document as MyObject. key: 7498620, 7498620
Inserted new document as BaseDocument. key: 7498624, 7498624
Open document 7498620 VPackSlice: Homer 38
Open document 7498620 as BaseDocument: Homer 38
Open document 7498620 as MyObject: Homer 38

Testng to print result pass/ fail

Here, I am trying to print the results of testcases...
But whatever I do the test reult prints only as 16...
I want it to print as success or pass/ fail
It would be a great help if you could post a example.
public class EdiitAttendancePunchesByDepartment {
public EdiitAttendancePunchesByDepartment() {
}
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#BeforeMethod
public void setUp() {
}
#AfterMethod
public void tearDown() {
}
Boolean t = true;
#Test(priority = 0,dataProvider = "globalcfg")
public void global(String propid, String propvalue) throws IOException {
ConfigurationBean cfgbean = new ConfigurationBean();
for (ConfigurationModel cc : cfgbean.getConfigurationList()) {
if (cc.getPropertyId().equals(propid)) {
cc.setPropertyId(propid);
cc.setPropertyValue(propvalue);
System.out.println("Propid : " + cc.getPropertyId() + " value : " + cc.getPropertyValue());
}
}
File output = new File("D:/data/kishore/Edit_punches_output.xls");
FileWriter writes = new FileWriter(output.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(writes);
bw.write("EmpID-Date-Punch_Times-PayDay-Total_IN_Hours-OT-TEST_ID-Leave_Type");
bw.close();
cfgbean.setCreateButtonFlag(Boolean.FALSE);
cfgbean.setUpdateButtonFlag(Boolean.TRUE);
cfgbean.updateConfiguration();
cfgbean.retrieveConfiguration();
for (ConfigurationModel cc : cfgbean.getConfigurationList()) {
if (cc.getPropertyId().equals(propid)) {
System.out.println("Propid Out Put : " + cc.getPropertyId() + " value Out Put: " + cc.getPropertyValue());
}
}
System.out.println("Global Config running>>>>>>>>>>>>>>>");
boolean tr=Reporter.getCurrentTestResult().isSuccess();
System.out.println("Check<><><><><><><><><><><><><><><><><><><><>"+tr);
if(tr==true){
System.out.println("Result /////////////////////////////////////"+tr);
}
System.out.println("Test result>>>>>>>>>>>>>> "+Reporter.getCurrentTestResult().getStatus());
}
#Test(priority = 1,dataProvider = "viewpunches")
public void testviewpunches(String cmpcode, String orgcode, String Empid, String Empname, String deptname, Integer compgrpid,
String date, String Time1, String Time2, String type, String typeid) {
EditEmpTimeSheetBean bean = new EditEmpTimeSheetBean();
bean.setCmpCode(cmpcode);
bean.setOrgCode(orgcode);
try {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date1 = format.parse(date);
Date time1 = format1.parse(Time1);
Date time3 = format1.parse(Time2);
SimpleDateFormat op = new SimpleDateFormat("dd/MM/yyyy");
bean.setTimeSheetDate(date1);
bean.setEmpCompGroupId(compgrpid);
bean.setDepartmentName(deptname);
bean.setEmployeeCode(Empid);
bean.setEmployeeName(Empname);
bean.setDialogFlag(Boolean.TRUE);
bean.viewTimeSheetDetailByDepartment();
EmployeeDTO dto = new EmployeeDTO();
EmployeeService service = new EmployeeServiceImpl();
dto = service.retrieveEmployee(bean.getCmpCode(), bean.getOrgCode(), bean.getEmployeeCode());
if (dto == null) {
File output = new File("D:/data/kishore/Edit_punches_output.xls");
FileWriter write_new = new FileWriter(output, true);
BufferedWriter bw_new = new BufferedWriter(write_new);
bw_new.write("\n" + bean.getEmployeeCode() + "- NO record found - - - - -" + typeid);
bw_new.close();
System.out.println("Invalid Employee Code");
} else {
System.out.println("Valid code");
}
for (EmpWorkLogModel cc : bean.getEmpWorkLogArray()) {
if (cc.getEmployeeCode().equals(Empid)) {
cc.onChange();
List<LogTimeModel> kl = new ArrayList<LogTimeModel>();
LogTimeModel m = new LogTimeModel();
LogTimeModel mn = new LogTimeModel();
m.setPunchTimes(time1);
if (type.equalsIgnoreCase("insert")) {
m.setOpFlag(Constant.OP_FLAG_INSERT);
}
if (type.equalsIgnoreCase("update")) {
m.setOpFlag(Constant.OP_FLAG_UPDATE);
}
if (type.equalsIgnoreCase("delete")) {
m.setOpFlag(Constant.OP_FLAG_DELETE);
}
mn.setPunchTimes(time3);
if (type.equalsIgnoreCase("insert")) {
mn.setOpFlag(Constant.OP_FLAG_INSERT);
}
if (type.equalsIgnoreCase("update")) {
mn.setOpFlag(Constant.OP_FLAG_UPDATE);
}
if (type.equalsIgnoreCase("delete")) {
mn.setOpFlag(Constant.OP_FLAG_DELETE);
}
if (type.equalsIgnoreCase("CHANGE")) {
}
kl.add(m);
kl.add(mn);
cc.setPunchList(kl);
System.out.println("punch time>>>>>>>>>>>>>>>>>XXXXXXXXX>>>>>>>>>>>>XXXXXXXXXX " + mn.getPunchTimes() + " " + cc.getPunchTime() + " " + cc.getFromDate());
System.out.println("Emp ID : " + cc.getEmployeeCode() + " \nPunch time : " + cc.getPunchTimes() + " \nPay Day : " + cc.getPayDay() + " \nIN hours: " + cc.getWorkedTime());
} else {
System.out.println("\n\nNo Records found for : " + cc.getEmployeeCode());
}
}System.out.println("Test result>>>>>>>>>>>>>> "+Reporter.getCurrentTestResult().getStatus());
bean.updateLogTime();
testview(bean.getEmployeeCode(), bean.getEmployeeName(), bean.getShiftId(), date, typeid);
} catch (Exception e) {
System.out.println(" Error :" + e);
e.printStackTrace();
}
}
This is the output i receive
sessionFactory1 org.hibernate.internal.SessionFactoryImpl#196a6ac
sessionFactory1 SessionStatistics[entity count=0collection count=0]
Propid : com.rgs.payroll.enableDynamicWeekOff value : N Propid Out Put
: com.rgs.payroll.enableDynamicWeekOff value Out Put: N Global Config
running> Check<><><><><><><><><><>false Test result>>>>>>>>>>>>>> 16
Remove pass fail decision making code from ur test case and use the below code:
#AfterMethod
public void tearDown(ITestResult result) {
if (result.getStatus() == ITestResult.FAILURE) {
System.out.println(result.getMethod().getMethodName()+ " is failed");
//do something here.
}
}
16 means "STARTED".
It's the only value you can expect into the test itself.
TestNG will only determine the value after the end of the method.
You can try to print the result from the #AfterMethod method.

inStream.read in serial communications

I'm trying to monitor temperature from a remote device using a TC65 modem. To request, 'C' has to be sent with a carriage return at the end. The problem is, I only get this on my phone: "This is test sms. The current temperature is " without the temperature I requested. I tried communicating with the thermostat using HyperTeminal without a problem.
Could you help me with instream.read? The output is double (accurate by two decimals).
Here's my code. Thanks.
package example.rs232demo;
import javax.microedition.midlet.*;
import java.io.*;
import javax.microedition.io.*;
import com.siemens.icm.io.*;
public class RS232Demo extends MIDlet {
CommConnection commConn;
InputStream inStream;
OutputStream outStream;
private ATCommand ATC;
public static String phone = "+97455781868";
public static String message = "This is test sms.";
/**
* RS232Demo - default constructor
*/
public RS232Demo() {
//System.out.println("RS232Demo: Constructor");
//System.out.println("Available COM-Ports: " + System.getProperty("microedition.commports"));
try {
//String strCOM = "comm:com0;blocking=on;baudrate=115200";
String strCOM = "comm:com0;blocking=on;baudrate=9600;bitsperchar=7;parity=even";
commConn = (CommConnection)Connector.open(strCOM);
//System.out.println("CommConnection(" + strCOM + ") opened");
//System.out.println("Real baud rate: " + commConn.getBaudRate());
inStream = commConn.openInputStream();
outStream = commConn.openOutputStream();
//System.out.println("InputStream and OutputStream opened");
} catch(IOException e) {
//System.out.println(e);
notifyDestroyed();
}
}
/**
* startApp()
*/
public void startApp() throws MIDletStateChangeException {
int ch = 0;
//System.out.println("RS232Demo: startApp");
//System.out.println("Looping back received data, leave with 'Q'...");
try {
outStream.write('C');
outStream.write('\r');
ch = inStream.read();
} catch(IOException e) {
//System.out.println(e);
}
try
{
this.ATC = new ATCommand(false);
}
catch (ATCommandFailedException ex)
{
ex.printStackTrace();
}
send_Simple_SMS(phone, message, ch);
try
{
this.ATC.release();
}
catch(ATCommandFailedException ex)
{
ex.printStackTrace();
}
destroyApp(true);
}
public void pauseApp() {
//System.out.println("RS232Demo: pauseApp()");
}
public int send_Simple_SMS(String phone, String message, int ch)
{
int res = -1;
String AT = "";
String response = "";
synchronized (System.out)
{
}
if(ATC==null){return res;}
try
{
synchronized (ATC)
{
ATC.send("AT+CMGF=1\r");
ATC.send("AT+IFC=1,1\r");
response = "";
response = ATC.send("AT+CMGS=?\r");
if (response.trim().indexOf("OK") < 0)
{
return res;
}
response = ATC.send("AT+CMGS=" + phone + '\r' + '\n');
//System.out.println("Sending.");
response = ATC.send(message + "The current temperature is " + (char)ch + '\032');
//System.out.println("Sent.");
if (response.trim().indexOf("OK") >= 0)
{
res = 0;
}
ATC.notifyAll();
}
}
catch (ATCommandFailedException ex)
{
ex.printStackTrace();
res = -1;
}
return res;
}
public void destroyApp(boolean cond) {
//System.out.println("RS232Demo: destroyApp(" + cond + ")");
try {
inStream.close();
outStream.close();
commConn.close();
//System.out.println("Streams and connection closed");
} catch(IOException e) {
//System.out.println(e);
}
notifyDestroyed();
}
}
Problem is here:
response = ATC.send(message + "The current temperature is " + (char)ch + '\032');
It converts ch to corrensponding character, not to number string.
Try the following:
response = ATC.send(message + "The current temperature is " + ch + '\032');

Categories