I'm developing a Java project, a log analyzer, that imports any kind of log informations in a universal way.
Actually, I divided any log sheet in a Log class instance, and any sheet line in a Event class instance.
The problem is: Log read all the sheet, and instance an Event with every read line, putting it in a LinkedHashSet.
When Event gets constructed, it takes - depending on which Log type is it in - all the informations (such as the time the event happened).
Everything works flawlessly, except for getting Date/Time from event string.
In fact, without any kind of error, Log's adding Event cycle, stops.
Deleting every Time-related line, I correctly manage to get everything: with them, it stops, without any error, but making me getting only bunch of lines, instead of the thousands I should get.
Here you can find Log and Event classes, and even the method that gets Time from event and the last line of Event the manage to get Time and the first one that doesn't.
Log:
public class Log {
/** LogType assigned to log file */
private LogType type;
/** filename associated to log file*/
private String name;
/** path associated to log file */
private String path;
private LinkedHashSet<Evento> events;
/**
* Log constructor:
* #param path points to file which create log instance from
* #param type is the LogType type associated with the rising Log
* #param bInitialize indicates if Log has to initialize events list
*/
public Log(String path, LogType type, boolean bInitialize) {
String[] pathComponents = path.split("/");
this.path = path;
this.type = type;
this.name = pathComponents[pathComponents.length - 1];
populateEvents();
}
public LinkedHashSet<Evento> getEvents() {
return events;
}
/** type field getter */
public LogType getType() {
return type;
}
/** name field getter */
public String getName() {
return name;
}
/** path field getter */
public String getPath() {
return path;
}
/** #return path field */
public String toString() {
return path;
}
public TreeSet<Utente> getUsers() {
TreeSet<Utente> users = new TreeSet<Utente>();
for (Evento event : events)
users.add(event.getUser());
return users;
}
private void populateEvents() {
events = new LinkedHashSet<Evento>();
try {
File file = new File(path);
FileInputStream fInputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fInputStream.read(data);
fInputStream.close();
String[] eventsRead = new String(data, "UTF-8").split("\n");
for (String event : eventsRead)
events.add(new Evento(event, type));
} catch (Exception e) {
// Nothing really needed.
}
}
/** name field setter */
public void setName(String name) {
this.name = name;
}
/**
* Requests that the file or directory denoted by this abstract
* pathname be deleted when the virtual machine terminates.
*/
public void setToDeleted() {
new File(path).deleteOnExit();
}
}
Event:
public class Evento implements Comparable<Evento> {
private LocalDateTime time;
private LogType type;
private String event;
private Utente user;
public Evento(String event, LogType type) {
this.event = event;
this.type = type;
time = type.getAssociatedLoader().getTimeFromLine(event);
user = type.getAssociatedLoader().getUserFromLine(event);
}
public boolean equals(Evento comparedEvent) {
return event.equals(comparedEvent.getEvent());
}
#Override
public int compareTo(Evento comparedEvent) {
return event.compareTo(comparedEvent.getEvent());
}
public LocalDateTime getTime() {
return time;
}
public String getEvent() {
return event;
}
public Utente getUser() {
return user;
}
#Override
public String toString() {
return event;
}
}
getTimeFromLine() method:
#Override
public LocalDateTime getTimeFromLine(String line) {
String clockString = line.split("\t")[2];
return LocalDateTime.of(Integer.parseInt(clockString.substring(0,4)),
Integer.parseInt(clockString.substring(6,7)),
Integer.parseInt(clockString.substring(9,10)),
Integer.parseInt(clockString.substring(11,13)),
Integer.parseInt(clockString.substring(15,16)),
Integer.parseInt(clockString.substring(17,19)));
}
Lines example (first correctly working, not the latter):
142\twestchester.gov\t2006-03-20 03:55:57\t1\thttp://www.westchestergov.com
142\tspace.comhttp\t2006-03-24 20:51:24\t\t
You should not swallow exceptions - if you had let it propagate you would have got a fairly self explanatory exception message that would have helped you find the problem!
java.time.DateTimeException: Invalid value for DayOfMonth (valid values 1 - 28/31): 0
So one of your clockString.substring() does not use the right indices
Your getTimeFromLine method is unnecessary complicated and I would recommend to use a DateTimeFormatter instead of parsing the string manually
Suggested replacement:
private static final DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public LocalDateTime getTimeFromLine(String line) {
String clockString = line.split("\t")[2];
return LocalDateTime.parse(clockString, fmt);
}
Related
so when i clicking the Messages tabPane containing the Jtree, this is the preview in my java swing which seems fine.
pict 1 (loading the message)
pict 2. (done)
when i click any of the checkboxes in the JTree it should be either loading(checking) or unloading(unchecking) the messages in the message list with the swingworker running to see the progress. But what happen is after i click the checkboxes (of any condition), yes the swingworker running and giving the loading/unloading progress, but after that, i get this:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException:
Cannot invoke "model.Message.getContents()" because "message" is null
and make the message lists is unclickable, which were clickable before i attempted to click the checkboxes in the JTree.
at the moment i dont need JTree in my purpose for learning swing, so I'm not really taking into account about this JTree lesson, but i need this to be fixed so i can keep go along with the tutorial. that's why i'm not quite sure which code are problematic and needed to put in this thread. So i'm very sorry if my question is not clear. if there still anything i have to put at this thread, please ask me i'll be happy to put it here.
this the class that mentioned in exception
public class MessagePanel extends JPanel implements ProgressDialogListener{
public MessagePanel(JFrame parent) {
messageListModel = new DefaultListModel();
messageList = new JList(messageListModel);
messageList.setCellRenderer(new MessageListRenderer());
messageList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
Message message = (Message)messageList.getSelectedValue();
textPanel.setText(message.getContents());
}
});
}
this is the class and method that related with the above class
public class MessageListRenderer implements ListCellRenderer {
private JPanel panel;
private JLabel label;
private Color selectedColor,normalColor;
public MessageListRenderer() {
//some ui settings
}
#Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
Message message = (Message)value;
label.setText(message.getTitle());
panel.setBackground(cellHasFocus ? selectedColor: normalColor);
return panel;
}
}
===================
public class TextPanel extends JPanel{
public void setText(String text) {
textArea.setText(text);
}
}
===================
public class Message {
private String title,contents;
public Message(String title, String contents) {
super();
this.title = title;
this.contents = contents;
}
public String getTitle() {return title;}
public void setTitle(String title) {this.title = title;}
public String getContents() {return contents;}
public void setContents(String contents) {this.contents = contents;}
}
Your Message class constructor requires two parameters (of: String, String) in order to create an instance of Message. I have no clue what you are currently using to create you Message instances nor do I know what is storing those instances. You do need to keep track of them otherwise you will loose them to JVM Garbage Collection.
I think perhaps you may want to modify your Message Class a little so that you can internally (or externally) store your Message instances and easily access any one of those instances when required, for example:
public class Message {
// A List Interface object to hold Message instances.
private static java.util.List<Message> messageInstances = new java.util.ArrayList<>();
// The OS System's New-Line character to use for console writing.
private final static String ls = System.lineSeparator();
// Instance member variables
private String title;
private String contents;
/**
* Constructor #1
* Does Nothing but adds the instance to the messageInstances List!
* Relies on Setters to fill instance member variables.
*/
public Message() {
messageInstances.add((this));
}
/**
* Constructor #2
* Contains parameters of which the arguments will fill instance member
* variables listed within the Parameters list below.
*
* #param title (String) The Message Title.<br>
*
* #param contents (String) The message content related to the above title.
*/
public Message(String title, String contents) {
super();
this.title = title;
this.contents = contents;
messageInstances.add((this));
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
public static java.util.List<Message> getMessageInstances() {
return messageInstances;
}
/**
* Removes one (or more) Message instances from the messageInstances List.
* This method must be supplied at least one integer index value of the
* Message instance to remove otherwise a Warning is displayed within the
* console window. Several index values can be supplied providing they are
* delimited with a comma or all desired Message Instance index values to
* remove are supplied within a Single Dimensional int[] Array.<br><br>
*
* <b>Valid uses of this class method:</b><pre>
*
* removeMessageInstance(0, 4, 2, 16);
*
* OR
*
* int[] indexes = {0, 4, 2, 16};
* removeMessageInstance(indexes);</pre>
*
* #param instanceIndexes
*/
public static void removeMessageInstance(int... instanceIndexes) {
int[] iIndex = null;
if (instanceIndexes.length == 0) {
System.err.println("Message.removeMessageInstance() method Warning!" + ls
+ "Require an index value of the Message Instance to remove!" + ls
+ "Ignoring Removal call!" );
return;
}
iIndex = new int[instanceIndexes.length];
System.arraycopy(instanceIndexes, 0, iIndex, 0, instanceIndexes.length);
for (int i = 0; i < iIndex.length; i++) {
if(iIndex[i] < 0 || iIndex[i] > messageInstances.size()) {
System.err.println("Message.removeMessageInstance() method Warning!" + ls
+ "The supplied Message Instance index value (" + iIndex[i] + ") is invalid!" + ls
+ "Ignoring Removal call for Message Instance at Index " + iIndex[i] + "!");
continue;
}
messageInstances.remove(iIndex[i]);
}
}
#Override
public String toString() {
return new StringBuilder("").append(title).append(" | ")
.append(contents).toString();
}
}
Do whatever it is you do to create Message instances.
Now, in your MessagePanel class within the ListSelectionListener:
public void valueChanged(ListSelectionEvent e) {
String title = messageList.getSelectedValue().toString(); // toString() may not be required.
List<Message> messages = Message.getMessageInstances();
for (Message msg : messages) {
if (msg.getTitle().equalsIgnoreCase(title)) {
textPanel.setText(msg.getContents());
break;
}
}
}
How does one set a temporary variable of date before it is updated? I would like to compare my initial date before it is updated.
Update: More code
* #hibernate.class table="t3sstations"
* #hibernate.join name="rgnjoin" table="stnregions" optional="true"
* #hibernate.join-key column="idstn"
*/
public class Station extends BaseSiteChildCFKObject implements Convertible, Comparable<Station> {
private static final long serialVersionUID = -2056063261398467275L;
protected final Log log = LogFactory.getLog(getClass());
private Project stationProject;
private Date project_startdate;
private Date date_initial;
Table it grabs from SQL using hibernate. It grabs the project's date from the column project_startdate. I want to compare the date that it is initially with the new/updated date. It updates the same value throughout the class.
/**
* #return
* #hibernate.many-to-one column="idproject" not-null="false"
* class="org.unavco.pbo.mdm.model.Project"
*/
#Required
public Project getStationProject() {
return stationProject;
}
public void setStationProject(Project stationProject) {
this.stationProject = stationProject;
}
/**
* #return
* #hibernate.property column="project_startdate"
*/
public Date getProject_startdate() {
return project_startdate;
}
public void setProject_startdate(Date project_startdate) {
this.project_startdate = project_startdate;
}
#AssertTrue
private boolean validateProjectDate() {
project_initialdate = new Date(project_startdate);
if (project_startdate.before(this.project_initialdate)){
return false;
}
if (project_startdate.before(this.stationProject.getStart_date())) {
return false;
}
if (this.stationProject.getEnd_date() != null) {
if (this.project_startdate.after(this.stationProject.getEnd_date())) {
return false;
}
}
return true;
}
So I don't think I found a temporary value holder but I did define the initial date as another variable inside the initializer. By placing it here, I save the date before it is changed and updated via hibernate.
public Station() {
super();
Date date_initial = this.project_startdate;
}
At the top of the class called Station. From there I also defined the getter and setter for date initial.
public Date getDate_initial(){
return date_initial;
}
public void setDate_initial(Date date_initial) {
this.date_initial = date_initial;
}
From there it accurately compares the initial date to the updated date. If it is safe then it continues to save. Otherwise it displays an error message to the user.
I am making a program that returns the output in a long string variable. The data in the string is constantly changing based on what the user enters in the GUI. My question is, how do I take this and store it inside of my linked list? I have looked at a few examples, but the class I was provided with for my class is a little different, and I haven't been able to find something to specifically fix my problem.
Controller Code:
public class RentGameDialogController extends RentalStoreGUIController implements Initializable{
/** TextField Objects **/
#FXML private TextField nameField, rentedOnField, dueBackField;
/** String for NameField **/
String name, rentedOn, dueBack;
/** Game ComboBox ID's **/
#FXML private ObservableList<GameType> cbGameOptions;
#FXML private ComboBox<GameType> cbGame;
/** Console ComboBox ID's **/
#FXML private ObservableList<PlayerType> cbConsoleOptions;
#FXML private ComboBox<PlayerType> cbConsole;
/** GameType object **/
private GameType game;
/** PlayerType Object **/
private PlayerType console;
/** Button ID's **/
#FXML Button cancel, addToCart;
/** Counter for calculating total **/
int gameCounter;
/** Stage for closing GUI **/
private Stage currentStage;
private MyLinkedList list = new MyLinkedList();
#Override
public void initialize(URL location, ResourceBundle resources) {
/** Select Console **/
cbConsoleOptions = FXCollections.observableArrayList();
for (PlayerType p : PlayerType.values()) { cbConsoleOptions.addAll(p); }
cbConsole.getItems().addAll(cbConsoleOptions);
/** Select Game **/
cbGameOptions = FXCollections.observableArrayList();
for (GameType g : GameType.values()){ cbGameOptions.addAll(g); }
cbGame.getItems().addAll(cbGameOptions);
}
public String getName(){
name = nameField.getText();
try {
String[] firstLast = name.split(" ");
String firstName = firstLast[0];
String lastName = firstLast[1];
} catch (Exception e){
e.printStackTrace();
}
return name;
}
public String getGame() {
return cbGame.getSelectionModel().getSelectedItem().toString();
}
public String getConsole() {
return cbConsole.getSelectionModel().getSelectedItem().toString();
}
public String getRentedOn() throws ParseException {
rentedOn = rentedOnField.getText();
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date rentedOnDate = format.parse(rentedOn);
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.setTime(rentedOnDate);
try {
cal.getTime();
} catch (Exception e) {
rentedOnField.setText("ERROR");
}
return rentedOn;
}
public String getDueBack() throws ParseException {
dueBack = dueBackField.getText();
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date dueBackDate = format.parse(dueBack);
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.setTime(dueBackDate);
try {
cal.getTime();
} catch (Exception e) {
dueBackField.setText("ERROR");
}
return dueBack;
}
/*************************************
* This is the method to call the other
* String methods so their output can be
* put into my main GUI
*
*
* #return
* #throws ParseException
*************************************/
public String storePurchaseData() throws ParseException {
gameCounter++;
String toList = getName() + " | " + getGame() + " | " + getConsole() + " | " +
getRentedOn() + " | " + getDueBack();
//Add 'toList' to the linked list here if possible
return toList;
}
#FXML
public void handleCancelButtonAction () {
currentStage = (Stage) cancel.getScene().getWindow();
currentStage.close();
}
#FXML
public void addToCartButton () throws ParseException {
appendTextArea(storePurchaseData());
currentStage = (Stage) cancel.getScene().getWindow();
currentStage.close();
}}
This code is for my controller. It launches a basic GUI, then I can pull the data from all of the fields I made, convert them to Strings and can then print them in one long chain of text. I would like to store the string into my linked list class.
Linked List code:
public class MyLinkedList<E> implements Serializable {
private DNode<E> top;
public int size;
public MyLinkedList() {
top = null;
size = 0;
}
}
I am very new to linked lists and I am trying to understand them, does this code make sense? Do I need to add anything to, say, save the String that I am storing into a text file?
Thank you in advance
Without getting into your game code at all, it looks like your MyLinkedList class takes a type parameter E - You haven't shown the code for DNode but it also takes the E type. If you can specify this to be a String then the nodes of MyLinkedList can be populated with Strings as you desire.
DNode<String> myFirstNode = new DNode<>(null, null, "nodeData");
MyLinkedList<String> list = new MyLinkedList<>(myFirstNode);
This assumes that the MyLinkedList class also has a constructor that takes a DNode to initialize its head, and that DNode looks something like this.
I have a class that holds contact data; wrapped in a respective class. I recently changed my Photo setup from being a simple byte[] to being a wrapped class as well, but the instantitaion is a little different and now won't serialize/wrap properly.
My other classes wrap properly such as "number":{"log.PhoneNumber":{"number":"123-456-7890"}} but if I feed in a new photo (ie: new Photo("DEADBEEF")) I just get "photo":"DEADBEEF". This is causing problems with the deserializer too.
public class ContactInfo {
#JsonProperty("name") private Name m_name = null;
#JsonProperty("number") private PhoneNumber m_number = null;
#JsonProperty("email") private Email m_email = null;
#JsonProperty("photo") private Photo m_photo = null;
#JsonCreator
public ContactInfo(#JsonProperty("name") Name name,
#JsonProperty("number") PhoneNumber number,
#JsonProperty("email") Email email,
#JsonProperty("photo") Photo photo) {
/** Set vars **/
}
#JsonTypeInfo(use=Id.CLASS, include=As.WRAPPER_OBJECT)
static public class Photo {
private byte[] m_decodedBase64 = null;
public Photo(byte[] encodedBase64) {
m_decodedBase64 = Base64.decodeBase64(encodedBase64);
}
#JsonCreator
public Photo(#JsonProperty("photoData")String encodedBase64) {
m_decodedBase64 = Base64.decodeBase64(encodedBase64);
}
#JsonProperty("photoData")
public String getEncodedPhoto() {
return Base64.encodeBase64String(m_decodedBase64);
}
public byte[] getDecodedData() {
return m_decodedBase64;
}
}
}
What am I doing wrong?
Just figured out what it was. In the ContactInfo class there was a simple accessor function to get the encodedData.
public String getPhoto() {
return m_photo.getEncodedPhoto();
}
By simple putting it on ignore (or simply change it to return the object itself, which I might do),
#JsonIgnore
public String getPhoto() {
return m_photo.getEncodedPhoto();
}
The serializer stopped trying to read from it. I wish there was a way to set the serializer engine to be more "explicit declaration" for properties instead of "serialize everything that seems to match the member variables."
This question already has answers here:
Validation Error: Value is not valid
(3 answers)
Closed 7 years ago.
I have been trying to solve this problem all day, I googled a lot, I found answers but I can not understand why this is not working for me, I tried everything that I thought.
I have primefaces selectOneListbox:
<p:selectOneListbox id="idCrawledDataSelectMenu"
required="true"
value="#{crawlerCorpusTreatmentBean.corpusId}"
converter="crawledDataConverter"
style="height: 200px; width: 500px;">
<f:selectItems id="idCrawledDataItems"
value="#{crawlerCorpusTreatmentBean.crawledDataList}"
var="crawledData"
itemLabel="#{crawledData.url}"
itemValue="#{crawledData}"/>
</p:selectOneListbox>
I have a converter:
#FacesConverter(value = "crawledDataConverter")
public class CrawledDataConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
return s;
}
#Override
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
if (o instanceof CrawlerCorpusData) {
CrawlerCorpusData data = (CrawlerCorpusData) o;
return data.getId();
}
return null;
}
}
I there is my managed bean where I form my crawledDataList object.
#ManagedBean(name="crawlerCorpusTreatmentAction")
#RequestScoped
public class CrawlerCorpusTreatmentAction extends BaseAction implements Serializable {
/**
* Logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(CrawlerCorpusTreatmentAction.class);
/**
* Processes continue action of crawled corpus treatment request.
*
* #return success if action was success, otherwise - failure
*/
public String processContinue() {
CrawlerCorpusTreatmentBean corpusTreatmentBean = getBean(Beans.CRAWLER_CORPUS_TREATMENT_BEAN);
try {
CrawlerInfoWrapper crawlerInfoWrapper = createCrawlerInfoWrapper();
List<CrawledData> crawledDataList = crawlerInfoWrapper.getCrawledData(corpusTreatmentBean.getCorpusDomain());
List<CrawlerCorpusData> corpusDataList = BeanUtils.convertCrawledDataFromPojo(crawledDataList);
corpusTreatmentBean.setCrawledDataList(corpusDataList);
return ACTION_SUCCESS;
} catch (SystemException e) {
String errorMessage = MessageFactory.getErrorString(MessageFactory.ERROR_SYSTEM_ERROR);
LOGGER.error(errorMessage, e);
addErrorMessage(errorMessage + e.getMessage());
return ACTION_FAILURE;
} catch (CrawlerInfoException e) {
String errorMessage = MessageFactory.getErrorString(MessageFactory.ERROR_CRAWLER_INFO_ERROR);
LOGGER.error(errorMessage, e);
addErrorMessage(errorMessage + e.getMessage());
return ACTION_FAILURE;
}
}
public String processChooseCorpus() {
CrawlerCorpusTreatmentBean corpusTreatmentBean = getBean(Beans.CRAWLER_CORPUS_TREATMENT_BEAN);
corpusTreatmentBean.getCorpusId();
return ACTION_SUCCESS;
}
My CrawlerCorpusData object:
public class CrawlerCorpusData {
private String id;
private String url;
public String getId() {
return id;
}
public CrawlerCorpusData() {
}
public CrawlerCorpusData(String id, String url) {
this.id = id;
this.url = url;
}
public void setId(String id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
#Override
public boolean equals(Object obj) {
if (!(obj instanceof CrawlerCorpusData)) {
return false;
}
CrawlerCorpusData data = (CrawlerCorpusData) obj;
return this.id == data.getId();
}
}
I tried using List<SelectItem>, tried to use selectOneMenu, tried to use without converter, any success :(
Can someone tell me what am I missing here?
Values provided by selectItems should match the manipulated value, crawlerCorpusTreatmentBean.corpusId in your case. I would try
itemValue="#{crawledData.id}"
You should not be needing any converter in p:selectOneListbox, the default numeric one should do I believe. A converter would be necessary if you wanted to manipulate a full object value, like crawlerCorpusTreatmentBean.crawledData for example. Such object cannot be serialized in an obvious way and you need to provide a custom object<->string conversion.
EDIT: If the corrected markup does not work, it may mean the items list is lost between requests. It is stored in corpusTreatmentBean, so this bean should have scope wider than request, for example View. Alternatively the list can be recreated in each request by moving processContinue logic to corpusTreatmentBean #PostConstruct for example.