JDBC database java using vector of vectors - jdbc

Does someone can help my by creating an database query with vectors?
I want to query the Lieferranten Table of the nordwind database and showing it on a JTable.
My problem is how to show data sets in the jTable1?
This is my previous code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;
public class Anzeige extends JFrame {
private JTable jTable1 = new JTable(5, 5);
private DefaultTableModel jTable1Model = (DefaultTableModel) jTable1.getModel();
private JScrollPane jTable1ScrollPane = new JScrollPane(jTable1);
public Anzeige (String title) {
super (title);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
int frameWidth = 676;
int frameHeight = 467;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
Container cp = getContentPane();
cp.setLayout(null);
// Anfang Komponenten
jTable1ScrollPane.setBounds(72, 56, 521, 289);
jTable1.getColumnModel().getColumn(0).setHeaderValue("Title 1");
jTable1.getColumnModel().getColumn(1).setHeaderValue("Title 2");
jTable1.getColumnModel().getColumn(2).setHeaderValue("Title 3");
jTable1.getColumnModel().getColumn(3).setHeaderValue("Title 4");
jTable1.getColumnModel().getColumn(4).setHeaderValue("Title 5");
cp.add(jTable1ScrollPane);
// Ende Komponenten
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new Anzeige("Anzeige");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection dbConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/nordwind", "root", "");
Statement statement = dbConn.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM Lieferranten");
Vector vector = new Vector();
while (results.next()) {
String s1 = results.getString(2);
String s2 = results.getString(5);
System.out.println(s1 + "\n" + s2);
System.out.println(results.getString(2) + " " + results.getString(5));
Vector data = new Vector();
data.add(results.getString(1));
data.add(results.getString(2));
vector.add(data);
}
//results.close();
statement.close();
dbConn.close();
}
catch (InstantiationException e) {
System.err.println("Error in Instantiation!");
}
catch (ClassNotFoundException e) {
System.err.println("Class not found!");
}
catch (IllegalAccessException e) {
System.err.println("Access denied!");
}
catch (SQLException e) {
System.err.println("SQL Error!");
}
}
}

I assume that you will get five column values as you had added five column titles. After that use addRow(java.util.Vector) method of DefaultTableModel to insert row in jTable1.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;
public class Anzeige extends JFrame {
private JTable jTable1 = new JTable(5, 5);
private DefaultTableModel jTable1Model = (DefaultTableModel) jTable1.getModel();
private JScrollPane jTable1ScrollPane = new JScrollPane(jTable1);
public Anzeige (String title) {
super (title);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
int frameWidth = 676;
int frameHeight = 467;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
Container cp = getContentPane();
cp.setLayout(null);
// Anfang Komponenten
jTable1ScrollPane.setBounds(72, 56, 521, 289);
jTable1.getColumnModel().getColumn(0).setHeaderValue("Title 1");
jTable1.getColumnModel().getColumn(1).setHeaderValue("Title 2");
jTable1.getColumnModel().getColumn(2).setHeaderValue("Title 3");
jTable1.getColumnModel().getColumn(3).setHeaderValue("Title 4");
jTable1.getColumnModel().getColumn(4).setHeaderValue("Title 5");
cp.add(jTable1ScrollPane);
// Ende Komponenten
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new Anzeige("Anzeige");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection dbConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/nordwind", "root", "");
Statement statement = dbConn.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM Lieferranten");
while (results.next()) {
String s1 = results.getString(2);
String s2 = results.getString(5);
System.out.println(s1 + "\n" + s2);
System.out.println(results.getString(2) + " " + results.getString(5));
Vector data = new Vector();
data.add(results.getString(1));
data.add(results.getString(2));
data.add(results.getString(3));
data.add(results.getString(4));
data.add(results.getString(5));
jTable1Model.addRow(data);
}
//results.close();
statement.close();
dbConn.close();
}
catch (InstantiationException e) {
System.err.println("Error in Instantiation!");
}
catch (ClassNotFoundException e) {
System.err.println("Class not found!");
}
catch (IllegalAccessException e) {
System.err.println("Access denied!");
}
catch (SQLException e) {
System.err.println("SQL Error!");
}
}
}

Related

when i start .jar app on mac do nothing

I have made a simple JavaFx application, wich read/write the txt file (the code is below). I have tested it on windows platform (7 and higher).
After i gave app my friend for test on Mac. But when we run it, just do nothing. The GUI did not appear.
I tried run it through terminal (just "drug and drop" the icon to terminal, then enter in teminal. I don't know did i do right?) and terminal returned message "Permission denied". Can somebody explain what is require to run application, and what is not permitted exactly?
I found the similar question there but it have not answer...
Code:
import javafx.application.*;
import javafx.concurrent.Task;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.Label;
import javafx.scene.control.SplitPane;
import javafx.scene.text.Font;
import javafx.stage.*;
import javafx.scene.layout.*;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class Main extends Application {
static Properties props;
static double fontSize;
static String charsetName;
static long mills;
static String delimiter;
static String pathToDictionary;
static String pathErrLog;
static {
String pathFileProps = System.getProperty("user.dir") + "\\props.txt";
props = new Properties();
try {
FileInputStream fis = new FileInputStream(pathFileProps);
props.load(fis);
fontSize = Double.parseDouble(props.getProperty("Font"));
charsetName = props.getProperty("Charset");
mills = Long.parseLong(props.getProperty("mills"));
delimiter = props.getProperty("delimiter");
pathToDictionary = props.getProperty("dict.path");
fis.close();
} catch (IOException e) {
try {
props.put("Font", "20");
props.put("Charset", "UTF-8");
props.put("mills", "1000");
props.put("delimiter", "\t");
props.put("dict.path", System.getProperty("user.dir") + "\\dict.txt");
System.out.println("dictPath:" + System.getProperty("user.dir") + "\\dict.txt");
System.setProperty("file.encoding", "UTF-8");
FileOutputStream fos = new FileOutputStream(pathFileProps);
props.store(fos
, "Props description:" + "\n" +
"Font" + "\t\t" + "size of font's words " + "\n" +
"Charset" + "\t" + "charset of file-dictionary" + "\n" +
"mills" + "\t\t" + "per animations in milliseconds" + "\n" +
"delimiter" + "\t" + "delimiter between a pair words in string: eng<->rus \"<->\" is delimiter there." + "\n" +
"dict.path" + "\t" + "path to file-dictionary. Use \"/\"-symbol in path. Ex: C:/temp/dict.txt" + "\n" +
"\t\t\t" + "Use only eng symbols to set path!" + "\n" +
"\tYou can change only values!\n");
fos.close();
System.exit(0);
} catch (IOException e1) {
errPrint(e1,"Ошибка создания файла: " + pathFileProps + "\n");
}
}
}
ArrayList<String> dictionary = new ArrayList<>();
public static void errPrint(Exception exc, String note) {
if (pathErrLog == null) {
pathErrLog = System.getProperty("user.dir") + "\\errors.log";
}
try {
PrintWriter outFile = new PrintWriter(new FileWriter(pathErrLog, true));
outFile.println(note);
exc.printStackTrace(outFile);
outFile.close();
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
launch(args);
}
public void init() throws IOException {
try {
BufferedReader reader = new BufferedReader(new FileReader(pathToDictionary));
int cnt = 0;
while (reader.ready()) {
String line = new String(reader.readLine().getBytes(), Charset.forName(charsetName));
dictionary.add(line);
}
} catch (FileNotFoundException e) {
errPrint(e,"Не найден файл " + pathToDictionary);
} catch (IOException e) {
errPrint(e,"Ошибка чтения файла " + pathToDictionary);
}
}
public void start(Stage myStage) {
myStage.setTitle("WordsLearner");
SplitPane sp = new SplitPane();
sp.setOrientation(Orientation.VERTICAL);
Label labelUp = new Label();
Label labelDw = new Label();
labelUp.setFont(new Font(fontSize));
labelDw.setFont(new Font(fontSize));
Scene scene = new Scene(sp, 600, 200);
myStage.setScene(scene);
final StackPane sp1 = new StackPane();
sp1.getChildren().add(labelUp);
sp1.setAlignment(Pos.BOTTOM_CENTER);
final StackPane sp2 = new StackPane();
sp2.getChildren().add(labelDw);
sp2.setAlignment(Pos.TOP_CENTER);
final boolean[] flag = {true};
sp.setOnMouseClicked(event -> {
Task<Void> task = new Task<Void>() {
#Override
public Void call() throws Exception {
if (flag[0]) {
flag[0] = false;
final String[] str = new String[1];
final String[] eng = new String[1];
final String[] rus = new String[1];
while (true) {
Platform.runLater(() -> {
try {
str[0] = dictionary.get(ThreadLocalRandom.current().nextInt(0, dictionary.size()));
eng[0] = str[0].split(delimiter)[0];
rus[0] = str[0].split(delimiter)[1];
labelUp.setText(eng[0]);
labelDw.setText(rus[0]);
} catch (Exception e) {
System.exit(-1);
}
});
Thread.sleep(mills);
}
}
return null;
}
};
new Thread(task).start();
});
sp.getItems().addAll(sp1, sp2);
sp.setDividerPositions(0.5f, 0.5f);
myStage.show();
}
public void stop() {
System.exit(0);
}
}

Replace current JScrollPane to another JScrollPane in JPanel

I would like to change my current JScrollpane to a new one. I would like it to change after I pressed my button and the method actionPerformed is called.
The problem I currently have is that it only paints the Jscroll at the beginning of the application, when i want to change it, it dosent work.(When the application is running).
What I do is:
In the beginning of the application I make a new JscrollPane and this one is empty. If the button is pressed: Show another JscrollPane with content.
if(btnPressed == true){
//set current empty jscroll pane to a filled one.
jscrollpane = View.createScrollPlane();
//View.createScrollPlane = This method fills the JscrollPane with text.
}
else { //show a empty one
jscrollpane = new JscrollPane();
}
I have tried:
- remove
- add
- revalidate
- repaint
And also:
JscrollPane.setViewPortView(JscrollPane);
I've looked to CardLayout but I would rather not and it dosent allow me since only empty containers can be changed to CardLayout. Currently its on GridBagLayout.
Thanks in advance
RE-edit: the Create-UI method dosent change the current empty Jscrollpanel to the new one. It only initialise it once (at the beginning) but dosent update the Jscroll panel. (when i tried to put it on false) it worked, the boolean did change to true but dosent update the jscroll panel.
package readDataPluginPackage;
import com.change_vision.jude.api.inf.AstahAPI;
import com.change_vision.jude.api.inf.project.ProjectAccessor;
import javafx.embed.swing.JFXPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
public class Application {
JPanel mainJPanel;
private JPanel leftJPanel;
private JPanel rightJPanel;
private JButton btnSynchronise;
private JButton btnPreview;
private JScrollPane JScrollPaneReport;
public JScrollPane JScrollPanePreview;
private boolean btnPreviewClicked = false;
public Application() {
$$$setupUI$$$();
btnPreview.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btnPreviewClicked = true;
JOptionPane.showMessageDialog(null, "Showing..." + btnPreviewClicked);
// ShowXMLFileView showXMLFileView = new ShowXMLFileView();
// JScrollPanePreview = showXMLFileView.createLabelPane();
// if (btnPreview.isEnabled()) {
// ShowXMLFileView showXMLFileView = new ShowXMLFileView();
// JScrollPanePreview = showXMLFileView.createLabelPane();
JOptionPane.showMessageDialog(null, "XML File Preview has been updated.");
createUIComponents();
// JScrollPanePreview.revalidate();
// JScrollPanePreview.repaint();
JOptionPane.showMessageDialog(null, "Components are created again.");
}
// }
});
btnSynchronise.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Synchronising...");
}
});
}
public static void main(String[] args) {
try {
//Save Astah Project as XML File
ProjectAccessor prjAccessor = AstahAPI.getAstahAPI().getProjectAccessor();
prjAccessor.open("C:\\Users\\delina\\generated\\test.asta");
prjAccessor.exportXMI("C:\\Users\\delina\\generatedXMI\\temp.xml");
prjAccessor.close();
//Show the most recent version of the xml file of the Astah Project
ReadXMLFile rd = new ReadXMLFile();
rd.showXMLFileLines();
} catch (Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("Application");
frame.setContentPane(new Application().mainJPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void createUIComponents() {
if (btnPreviewClicked == true) {
// ShowXMLFileView showXMLFileView = new ShowXMLFileView();
// JScrollPanePreview = showXMLFileView.createLabelPane();
// JScrollPanePreview.setViewportView(JScrollPanePreview);
leftJPanel.remove(JScrollPanePreview);
ShowXMLFileView showXMLFileView = new ShowXMLFileView();
JScrollPane JScrollPanePreview = showXMLFileView.createLabelPane();
leftJPanel.add(JScrollPanePreview);
JScrollPanePreview.revalidate();
JScrollPanePreview.repaint();
JOptionPane.showMessageDialog(null, "JScrollPanel changed");
} else {
JScrollPanePreview = new JScrollPane();
}
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* #noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
mainJPanel = new JPanel();
mainJPanel.setLayout(new GridBagLayout());
leftJPanel = new JPanel();
leftJPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc;
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
mainJPanel.add(leftJPanel, gbc);
btnSynchronise = new JButton();
btnSynchronise.setText("Synchronise");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
leftJPanel.add(btnSynchronise, gbc);
btnPreview = new JButton();
btnPreview.setText("Preview");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
leftJPanel.add(btnPreview, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
leftJPanel.add(JScrollPanePreview, gbc);
JScrollPanePreview.setBorder(BorderFactory.createTitledBorder("XML File Preview"));
rightJPanel = new JPanel();
rightJPanel.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
mainJPanel.add(rightJPanel, gbc);
JScrollPaneReport = new JScrollPane();
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
rightJPanel.add(JScrollPaneReport, gbc);
JScrollPaneReport.setBorder(BorderFactory.createTitledBorder("Synchronise report"));
}
/**
* #noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return mainJPanel;
}
}
package readDataPluginPackage;
import com.change_vision.jude.api.inf.project.ProjectAccessor;
import com.change_vision.jude.api.inf.project.ProjectAccessorFactory;
import com.change_vision.jude.api.inf.project.ProjectEvent;
import com.change_vision.jude.api.inf.project.ProjectEventListener;
import com.change_vision.jude.api.inf.ui.IPluginExtraTabView;
import com.change_vision.jude.api.inf.ui.ISelectionListener;
import javax.swing.*;
import java.awt.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ShowUserInterface extends JPanel implements IPluginExtraTabView, ProjectEventListener {
public ShowUserInterface() {
initComponents();
}
private void initComponents() {
setLayout(new BorderLayout());
add(createLabelPane());
addProjectEventListener();
}
private void addProjectEventListener() {
try {
ProjectAccessor projectAccessor = ProjectAccessorFactory.getProjectAccessor();
projectAccessor.addProjectEventListener(this);
} catch (ClassNotFoundException e) {
e.getMessage();
}
}
private Container createLabelPane() {
JLabel label = new JLabel("AuguSoft Synchronise");
JScrollPane pane = new JScrollPane(label);
Method privateMethod = null;
Application app = null;
Object o = null;
JComponent jComponent = null;
try {
app = new Application();
privateMethod = Application.class.getDeclaredMethod("$$$setupUI$$$");
privateMethod.setAccessible(true);
o = privateMethod.invoke(app);
jComponent = app.$$$getRootComponent$$$();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return jComponent;
}
#Override
public void projectChanged(ProjectEvent e) {
}
#Override
public void projectClosed(ProjectEvent e) {
}
#Override
public void projectOpened(ProjectEvent e) {
}
#Override
public void addSelectionListener(ISelectionListener listener) {
}
#Override
public Component getComponent() {
return this;
}
#Override
public String getDescription() {
return "Show AuguSoft Synchronise here";
}
#Override
public String getTitle() {
return "AuguSoft View";
}
public void activated() {
}
public void deactivated() {
}
}
So, with doing nothing else but looking at you code, I noticed that in your createUIComponents method, you are shadowing the JScrollPanePreview property...
public class Application {
//...
public JScrollPane JScrollPanePreview;
//...
public Application() {..}
private void createUIComponents() {
if (btnPreviewClicked == true) {
//...
leftJPanel.remove(JScrollPanePreview);
ShowXMLFileView showXMLFileView = new ShowXMLFileView();
JScrollPane JScrollPanePreview = showXMLFileView.createLabelPane();
//...
} else {
JScrollPanePreview = new JScrollPane();
}
}
This means that the next time you come to replace the JScrollPanePreview, you won't have the correct reference to remove it.
To my mind (and I don't have you full code base or intention), I'd simply replace the JScrollPanePreview view port (besides, I'm not sure how you can assign a Container to a JScrollPane anyway :P)
private void createUIComponents() {
if (btnPreviewClicked == true) {
JScrollPanePreview.setViewportView(showXMLFileView.createLabelPane());
} else {
JScrollPanePreview = new JScrollPane();
}
}
Just as an observation ;)

How to display a clob data more than 66k in text field in oracle forms 12g

I don't know how to put clob data which is of more than 66k in Oracle Forms.
The text field will take a long data type and that too not more than 66k. I have a clob data and wanted to display.
The easiest way to display this is too make a forms bean (PJC).
Then you can display it in a JTextPane which is big enough.
You can then make a function that gives you piece of 32000 characters from the clob and give them to the bean.
package be.axi.oracle.forms.jpc;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.BadLocationException;
import oracle.forms.handler.IHandler;
import oracle.forms.properties.ID;
import oracle.forms.ui.CustomEvent;
import oracle.forms.ui.VBean;
/**
* A TextArea to get more than 64k texts
* #author Francois Degrelle
* #version 1.1
*/
public class BigTextArea extends VBean implements FocusListener, KeyListener
{
private static final long serialVersionUID = 1L;
public final static ID ADDTEXT = ID.registerProperty("ADD_TEXT");
public final static ID VALUE = ID.registerProperty("VALUE");
public final static ID SHOW = ID.registerProperty("SHOW");
public final static ID CLEAR = ID.registerProperty("CLEAR");
public final static ID GETTEXT = ID.registerProperty("GET_TEXT");
public final static ID GETLENGTH = ID.registerProperty("GET_LENGTH");
public final static ID pLostFocus = ID.registerProperty("BEAN_QUITTED");
private IHandler m_handler;
private int iStart = 0 ;
private int iChunk = 8192 ;
private StringBuffer sb = new StringBuffer();
protected JTextPane jtp = new JTextPane();
public BigTextArea()
{
super();
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
}
catch (Exception ex)
{
ex.printStackTrace();
}
JScrollPane ps = new JScrollPane(jtp);
ps.setBorder(null);
add(ps);
ps.setVisible(true);
}
public void init(IHandler handler)
{
m_handler = handler;
super.init(handler);
addFocusListener(this);
jtp.addFocusListener(this);
jtp.addKeyListener(this);
}
public boolean setProperty(ID property, Object value)
{
//
// add text to the TextArea
//
if (property == ADDTEXT)
{
sb.append(value.toString()) ;
printMemory();
return true;
}
//
// display the whole text
//
else if(property == SHOW)
{
jtp.setText(sb.toString());
jtp.setCaretPosition(0);
sb = new StringBuffer();
System.gc();
printMemory();
return true ;
}
//
// clear the TextArea
//
else if(property == CLEAR) {
jtp.setText("");
return true ;
}
else
{
return super.setProperty(property, value);
}
}
/*-----------------------------------*
* Get the result string from Forms *
*-----------------------------------*/
public Object getProperty(ID pId)
{
//
// returns the text length
//
if (pId == GETLENGTH)
{
return "" + jtp.getText().length();
}
//
// returns the chunks
//
else if (pId == GETTEXT) {
String s = "" ;
int iLen = jtp.getText().length() ;
while (iStart < iLen)
{
try{
if(iStart+iChunk <= iLen) s = jtp.getText(iStart,iChunk);
else s = jtp.getText(iStart,iLen-iStart);
iStart += iChunk ;
return s ;
}
catch (BadLocationException ble) { ble.printStackTrace(); return ""; }
}
iStart = 0 ;
return "" ;
}
else
{
return super.getProperty(pId);
}
} // getProperty()
/*--------------------------*
* handle the focus events *
*--------------------------*/
public void focusGained(FocusEvent e)
{
if (e.getComponent() == this)
{
// put the focus on the component
jtp.requestFocus();
}
try
{
m_handler.setProperty(FOCUS_EVENT, e);
}
catch ( Exception ex )
{
;
}
}
public void focusLost(FocusEvent e)
{
CustomEvent ce = new CustomEvent(m_handler, pLostFocus);
dispatchCustomEvent(ce);
}
/*--------------------------*
* Handle the Key listener *
*--------------------------*/
public void keyPressed(KeyEvent e)
{
/*
** Allows TAB key to exit the item
** and continue the standard Forms navigation
*/
if ( (e.getKeyCode() == KeyEvent.VK_TAB) )
{
try
{
m_handler.setProperty(KEY_EVENT, e);
}
catch ( Exception ex )
{
}
}
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
// utility to output the memory available
private void printMemory() {
System.out.println("Java memory in use = "
+ (Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory()));
}
}

Check for broken links using java code and link is not getting redirect

This code will check my link is broken or not and validateWebResourceUrl method will return 0 status .even if i get 200 status my link couldn't redirect to mozilla firefox when i call my api call.Below code will show u my api cal.
#RequestMapping(method = RequestMethod.POST, value = "/validate/fburl")
public ModelAndView validateFbLink(HttpServletRequest request,#RequestParam(value="key", required=true) String key ,#RequestParam(value = "link") String link, HttpServletResponse response) throws Exception {
ModelAndView jsonmodel = new ModelAndView("rest/model");
jsonmodel.addObject("model", httpFrameBreakChecker.validateHttpLink(link, key));
return jsonmodel;
}
This api call will go to check the link is broken or not ,if not it will go to redirect.I am trying to find the broken links and i am getting status 200 for that link but that link is not redirecting.Below is my code.
package org.ednovo.gooru.util;
import org.springframework.stereotype.Component;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebResponse;
#Component
public class HttpFrameBreakChecker extends LinkChecker {
#Override
public Integer validateHttpLink(String resourceUrl, String key) {
Integer status = null;
status = validateWebResourceUrl(resourceUrl, getPageTesterPath());
putResourceStatus(status, key);
return status;
}
public synchronized Integer validateWebResourceUrl(String webURL, String pageTesterURL) {
WebClient webClient = null;
WebResponse webResponse = null;
try {
webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
webClient.setCssEnabled(false);
webClient.setThrowExceptionOnScriptError(false);
webResponse = webClient.getPage(webURL).getWebResponse();
int i = webResponse.getStatusCode();
logger.info(i+"");
if (webResponse.getStatusCode() != 200) {
return null;
}
String urlToCheck = webURL + pageTesterURL;
// Now check if the page has a frame breaker.
webResponse = webClient.getPage(urlToCheck).getWebResponse();
int status = webResponse.getStatusCode();
logger.info(status+""+"frame");
String pageURL = webResponse.getWebRequest().getUrl().toString();
int validationStatus = (urlToCheck.equals(pageURL) && status == 200) ? 0 : 1;
logger.info(validationStatus+ " return statement of validateWebResourceUrl ");
return validationStatus;
} catch (Exception exception) {
logger.error("ERROR : Unable to start web driver : " + exception.getMessage());
return null;
} finally {
try {
if (webClient != null) {
webClient.closeAllWindows();
}
} catch (Exception ex) {
}
}
}
#Override
public void commitPage() {
if (resources.size() > 0) {
String resourcesString = getxStream().toXML(resources);
postData(getApiPath(), "/resource/urls/update/frameBreaker/" + getGlobalJobKey(), resourcesString);
postData(getSearchApiPath(), "/search/resource/update/index/" + getGlobalJobKey(), resourcesString );
}
}
#Override
public String getType() {
return "FB";
}
}
And Below code will show you the LinkChecker class.
package org.ednovo.gooru.util;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.restlet.data.Form;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public abstract class LinkChecker extends BaseComponent {
private int pageSize = 100;
private Map<String, String> configSettings;
private XStream xStream = new XStream(new DomDriver());
protected Map<Integer, List<String>> resources = new HashMap<Integer, List<String>>();
private String listResponse = null;
private Map<Long, String> resourceUrls = null;
public final synchronized void execute() {
reset();
ClientResource configResource = null;
Representation representation = null;
try {
configResource = createClientResource(getApiPath() + "/config-settings");
representation = configResource.get();
String settingsText = representation.getText();
configSettings = (Map<String, String>) xStream.fromXML(settingsText);
if (isLinkCheckerSchedulerEnabled()) {
run();
}
} catch (Exception exception) {
logger.error(exception.getMessage());
} finally {
releaseClientResources(configResource, representation);
}
}
public void run() throws Exception {
reset();
int page = 0;
while (true) {
++page;
listResponse = null;
resourceUrls = null;
final int currentPage = page;
ClientResourceExecuter clientResourceExecuter = new ClientResourceExecuter() {
#Override
public void run(ClientResource clientResource, Representation representation) throws Exception {
reset();
clientResource = createClientResource(getSearchApiPath() +"/search/resource-url-check?category="+getType()+"&pageSize="+pageSize+"&format=xml");
representation = clientResource.get();
listResponse = representation.getText();
if (listResponse != null || listResponse.length() > 1) {
try {
resourceUrls = (Map<Long, String>) xStream.fromXML(listResponse);
} catch (Exception ex) {
logger.error("Conversion of json to list failed in " + getType() + " validation");
}
logger.warn("Validating " + getType() + " Urls of Page : " + currentPage + " with size : " + (resourceUrls != null ? resourceUrls.size() : 0));
validateResourceUrls(resourceUrls);
}
}
};
clientResourceExecuter = null;
listResponse = null;
if (resourceUrls == null || resourceUrls.size() == 0) {
break;
}
if (getType().equals("HTTP") && page >= 5) {
break;
}else if (getType().equals("FB") && page >= 1) {
break;
}
}
}
public Integer validateHttpLink(String link, String key) {
URL url = null;
URLConnection connection = null;
HttpURLConnection httpConnection = null;
Integer responseCode = null;
try {
url = new URL(link);
connection = url.openConnection();
connection.connect();
httpConnection = (HttpURLConnection) connection;
httpConnection.setConnectTimeout(60000);
responseCode = httpConnection.getResponseCode();
if (responseCode != 200) {
logger.error("Url Checker validation fails for resource : " + link + " : " + responseCode);
}
} catch (MalformedURLException e) {
logger.error("Error in link checker : " + link + " Message : " + e.getMessage());
return 404;
} catch (IOException e) {
logger.error("Error in link checker : " + link + " Message : " + e.getMessage());
return 404;
} catch (Exception ex) {
logger.error("Error in link checker : " + link + " Message : " + ex.getMessage());
return null;
} finally {
try {
if (httpConnection != null) {
httpConnection.disconnect();
}
} catch (Exception ex) {
}
}
return responseCode;
}
protected void postData(String path, String url, String data) {
Form form = new Form();
form.add("data", data);
createAndRunClientResource(path, url, form);
}
public void validateResourceUrls(Map<Long, String> resourceUrls) throws Exception {
if (resourceUrls.size() > 0) {
Iterator<?> iterator = resourceUrls.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Long, String> entry = (Map.Entry<Long, String>) iterator.next();
String resourceUrl = entry.getValue();
if (getType().equals("FB")) {
Thread.sleep(1000);
} else {
Thread.sleep(900);
}
logger.debug("Validating " + getType() + " url - " + resourceUrl);
Integer status = validateHttpLink(resourceUrl, entry.getKey()+"");
putResourceStatus(status, entry.getKey()+"");
}
commitPage();
}
}
public void commitPage() throws Exception {
if (resources.size() > 0) {
String resourcesString = getxStream().toXML(resources);
postData(getApiPath(), "/resource/urls/checker/update/" + getGlobalJobKey(), resourcesString);
//postData(getSearchApiPath(), "/search/resource/update/index/" + getGlobalJobKey(), resourcesString);
}
}
public void putResourceStatus(Integer status, String resourceId) {
if (status == null) {
status = -99;
}
List<String> resourceIds = null;
if (resources.containsKey(status)) {
resourceIds = resources.get(status);
} else {
resourceIds = new ArrayList<String>();
resources.put(status, resourceIds);
}
resourceIds.add(resourceId);
}
public void reset() {
resources.clear();
}
public boolean isLinkCheckerSchedulerEnabled() {
if (configSettings != null && configSettings.containsKey("urlChecker.scheduler.enabled")) {
return configSettings.get("urlChecker.scheduler.enabled").equals("true") ? true : false;
} else {
return false;
}
}
public abstract String getType();
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public XStream getxStream() {
return xStream;
}
public static void main(String args[]) {
}
}

How to use accesslog_parser.pl Kannel access log parser?

I have found kannel access log parser accesslog_parser.pl in utils folder.
How to use this file for parse.
Also i want convert kannel_access.log in csv format. Please help me.
Assuming Kannel log is at /var/log/kannel/access.log
This should do
cat /var/log/kannel/access.log |accesslog_parser.pl
May be an old question but I'd like to share this small tool a wrote in java for parsing kannel log files and outputing the results in csv format:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.StringTokenizer;
/**
*
* #author bashizip
*/
public class KannelLogsParser {
static String fileName;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// fileName = args[0];
fileName = "access_kannel.txt";
String allLines = readLines(fileName);
parseAndWriteToCsv(allLines);
}
static String readLines(String fileName) {
BufferedReader br = null;
String sCurrentLine = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(
new FileReader(fileName));
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return sb.toString();
}
private static void parseAndWriteToCsv(String allLines) throws IOException {
String[] lines = allLines.split("\n");
System.out.println("lines to parse : " + lines.length);
StringTokenizer st;
StringBuilder output = new StringBuilder();
output.append("DATE;Heure;sent;SMS; SMSC; SVC; ACT; BINF; FID; from; to; flags; msg;;udh"+"\n");
int count = 0;
for (String line : lines) {
count++;
System.out.println("Parsing ..." + 100 * count / lines.length + "%");
st = new StringTokenizer(line, " ");
while (st.hasMoreTokens()) {
String currentToken = st.nextToken();
boolean messageToken = false;
boolean afterMessageToken = false;
if (currentToken.startsWith("[")) {
System.out.println(currentToken);
messageToken = currentToken.startsWith("[msg");
try {
currentToken = currentToken.substring(currentToken.indexOf(":") + 1, currentToken.indexOf("]"));
} catch (Exception e) {
System.err.println(e.getMessage());
messageToken = true;
currentToken = currentToken.substring(currentToken.indexOf(":") + 1);
}
}
currentToken = currentToken.replace("[", "");
currentToken = currentToken.replace("]", "");
output.append(currentToken);
if (!messageToken) {
output.append(";");
} else if (afterMessageToken) {
afterMessageToken = false;
output.append(" ");
} else {
output.append(" ");
afterMessageToken = true;
}
}
output.append("\n");
}
Files.write(Paths.get(fileName + ".csv"), output.toString().getBytes());
System.out.println("Output CVS file: " + fileName + ".csv");
System.out.println("Finished !");
}
}
Hope it can help someone one day :-)

Resources