Search Results

Search found 255 results on 11 pages for 'instanceof'.

Page 11/11 | < Previous Page | 7 8 9 10 11 

  • Test-Driven Development Problem

    - by Zeck
    Hi guys, I'm newbie to Java EE 6 and i'm trying to develop very simple JAX-RS application. RESTfull web service working fine. However when I ran my test application, I got the following. What have I done wrong? Or am i forget any configuration? Of course i'm create a JNDI and i'm using Netbeans 6.8 IDE. In finally, thank you for any advise. My Entity: @Entity @Table(name = "BOOK") @NamedQueries({ @NamedQuery(name = "Book.findAll", query = "SELECT b FROM Book b"), @NamedQuery(name = "Book.findById", query = "SELECT b FROM Book b WHERE b.id = :id"), @NamedQuery(name = "Book.findByTitle", query = "SELECT b FROM Book b WHERE b.title = :title"), @NamedQuery(name = "Book.findByDescription", query = "SELECT b FROM Book b WHERE b.description = :description"), @NamedQuery(name = "Book.findByPrice", query = "SELECT b FROM Book b WHERE b.price = :price"), @NamedQuery(name = "Book.findByNumberofpage", query = "SELECT b FROM Book b WHERE b.numberofpage = :numberofpage")}) public class Book implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "ID") private Integer id; @Basic(optional = false) @Column(name = "TITLE") private String title; @Basic(optional = false) @Column(name = "DESCRIPTION") private String description; @Basic(optional = false) @Column(name = "PRICE") private double price; @Basic(optional = false) @Column(name = "NUMBEROFPAGE") private int numberofpage; public Book() { } public Book(Integer id) { this.id = id; } public Book(Integer id, String title, String description, double price, int numberofpage) { this.id = id; this.title = title; this.description = description; this.price = price; this.numberofpage = numberofpage; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getNumberofpage() { return numberofpage; } public void setNumberofpage(int numberofpage) { this.numberofpage = numberofpage; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Book)) { return false; } Book other = (Book) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "com.entity.Book[id=" + id + "]"; } } My Junit test class: public class BookTest { private static EntityManager em; private static EntityManagerFactory emf; public BookTest() { } @BeforeClass public static void setUpClass() throws Exception { emf = Persistence.createEntityManagerFactory("E01R01PU"); em = emf.createEntityManager(); } @AfterClass public static void tearDownClass() throws Exception { em.close(); emf.close(); } @Test public void createBook() { Book book = new Book(); book.setId(1); book.setDescription("Mastering the Behavior Driven Development with Ruby on Rails"); book.setTitle("Mastering the BDD"); book.setPrice(25.9f); book.setNumberofpage(1029); em.persist(book); assertNotNull("ID should not be null", book.getId()); } } My persistence.xml jta-data-sourceBookstoreJNDI And exception is: May 7, 2009 11:10:37 AM org.hibernate.validator.util.Version INFO: Hibernate Validator bean-validator-3.0-JBoss-4.0.2 May 7, 2009 11:10:37 AM org.hibernate.validator.engine.resolver.DefaultTraversableResolver detectJPA INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver. [EL Info]: 2009-05-07 11:10:37.531--ServerSession(13671123)--EclipseLink, version: Eclipse Persistence Services - 2.0.0.v20091127-r5931 May 7, 2009 11:10:40 AM com.sun.enterprise.transaction.JavaEETransactionManagerSimplified initDelegates INFO: Using com.sun.enterprise.transaction.jts.JavaEETransactionManagerJTSDelegate as the delegate May 7, 2009 11:10:43 AM com.sun.enterprise.connectors.ActiveRAFactory createActiveResourceAdapter SEVERE: rardeployment.class_not_found May 7, 2009 11:10:43 AM com.sun.enterprise.connectors.ActiveRAFactory createActiveResourceAdapter SEVERE: com.sun.appserv.connectors.internal.api.ConnectorRuntimeException: Error in creating active RAR at com.sun.enterprise.connectors.ActiveRAFactory.createActiveResourceAdapter(ActiveRAFactory.java:104) at com.sun.enterprise.connectors.service.ResourceAdapterAdminServiceImpl.createActiveResourceAdapter(ResourceAdapterAdminServiceImpl.java:216) at com.sun.enterprise.connectors.ConnectorRuntime.createActiveResourceAdapter(ConnectorRuntime.java:352) at com.sun.enterprise.resource.naming.ConnectorObjectFactory.getObjectInstance(ConnectorObjectFactory.java:106) at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:304) at com.sun.enterprise.naming.impl.SerialContext.getObjectInstance(SerialContext.java:472) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:437) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:569) at javax.naming.InitialContext.lookup(InitialContext.java:396) at org.eclipse.persistence.sessions.JNDIConnector.connect(JNDIConnector.java:110) at org.eclipse.persistence.sessions.JNDIConnector.connect(JNDIConnector.java:94) at org.eclipse.persistence.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:162) at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:584) at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:228) at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:368) at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getServerSession(EntityManagerFactoryImpl.java:151) at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:207) at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:195) at com.entity.BookTest.setUpClass(BookTest.java:31) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) at org.junit.runners.ParentRunner.run(ParentRunner.java:220) at junit.framework.JUnit4TestAdapter.run(JUnit4TestAdapter.java:39) at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:515) at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1031) at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:888) Caused by: java.lang.ClassNotFoundException: com.sun.gjc.spi.ResourceAdapter at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at com.sun.enterprise.connectors.ActiveRAFactory.createActiveResourceAdapter(ActiveRAFactory.java:96) ... 32 more [EL Severe]: 2009-05-07 11:10:43.937--ServerSession(13671123)--Local Exception Stack: Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.0.0.v20091127-r5931): org.eclipse.persistence.exceptions.ValidationException Exception Description: Cannot acquire data source [BookstoreJNDI]. Internal Exception: javax.naming.NamingException: Lookup failed for 'BookstoreJNDI' in SerialContext ,orb'sInitialHost=localhost,orb'sInitialPort=3700 [Root exception is javax.naming.NamingException: Failed to look up ConnectorDescriptor from JNDI [Root exception is com.sun.appserv.connectors.internal.api.ConnectorRuntimeException: Error in creating active RAR]] at org.eclipse.persistence.exceptions.ValidationException.cannotAcquireDataSource(ValidationException.java:451) at org.eclipse.persistence.sessions.JNDIConnector.connect(JNDIConnector.java:116) at org.eclipse.persistence.sessions.JNDIConnector.connect(JNDIConnector.java:94) at org.eclipse.persistence.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:162) at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:584) at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:228) at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:368) at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getServerSession(EntityManagerFactoryImpl.java:151) at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:207) at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:195) at com.entity.BookTest.setUpClass(BookTest.java:31) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) at org.junit.runners.ParentRunner.run(ParentRunner.java:220) at junit.framework.JUnit4TestAdapter.run(JUnit4TestAdapter.java:39) at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:515) at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1031) at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:888) Caused by: javax.naming.NamingException: Lookup failed for 'BookstoreJNDI' in SerialContext ,orb'sInitialHost=localhost,orb'sInitialPort=3700 [Root exception is javax.naming.NamingException: Failed to look up ConnectorDescriptor from JNDI [Root exception is com.sun.appserv.connectors.internal.api.ConnectorRuntimeException: Error in creating active RAR]] at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:442) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:569) at javax.naming.InitialContext.lookup(InitialContext.java:396) at org.eclipse.persistence.sessions.JNDIConnector.connect(JNDIConnector.java:110) ... 23 more Caused by: javax.naming.NamingException: Failed to look up ConnectorDescriptor from JNDI [Root exception is com.sun.appserv.connectors.internal.api.ConnectorRuntimeException: Error in creating active RAR] at com.sun.enterprise.resource.naming.ConnectorObjectFactory.getObjectInstance(ConnectorObjectFactory.java:109) at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:304) at com.sun.enterprise.naming.impl.SerialContext.getObjectInstance(SerialContext.java:472) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:437) ... 26 more Caused by: com.sun.appserv.connectors.internal.api.ConnectorRuntimeException: Error in creating active RAR at com.sun.enterprise.connectors.ActiveRAFactory.createActiveResourceAdapter(ActiveRAFactory.java:104) at com.sun.enterprise.connectors.service.ResourceAdapterAdminServiceImpl.createActiveResourceAdapter(ResourceAdapterAdminServiceImpl.java:216) at com.sun.enterprise.connectors.ConnectorRuntime.createActiveResourceAdapter(ConnectorRuntime.java:352) at com.sun.enterprise.resource.naming.ConnectorObjectFactory.getObjectInstance(ConnectorObjectFactory.java:106) ... 29 more Caused by: java.lang.ClassNotFoundException: com.sun.gjc.spi.ResourceAdapter at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at com.sun.enterprise.connectors.ActiveRAFactory.createActiveResourceAdapter(ActiveRAFactory.java:96) ... 32 more Exception Description: Cannot acquire data source [BookstoreJNDI]. Internal Exception: javax.naming.NamingException: Lookup failed for 'BookstoreJNDI' in SerialContext ,orb'sInitialHost=localhost,orb'sInitialPort=3700 [Root exception is javax.naming.NamingException: Failed to look up ConnectorDescriptor from JNDI [Root exception is com.sun.appserv.connectors.internal.api.ConnectorRuntimeException: Error in creating active RAR]])

    Read the article

  • Slowdowns when reading from an urlconnection's inputstream (even with byte[] and buffers)

    - by user342677
    Ok so after spending two days trying to figure out the problem, and reading about dizillion articles, i finally decided to man up and ask to for some advice(my first time here). Now to the issue at hand - I am writing a program which will parse api data from a game, namely battle logs. There will be A LOT of entries in the database(20+ million) and so the parsing speed for each battle log page matters quite a bit. The pages to be parsed look like this: http://api.erepublik.com/v1/feeds/battle_logs/10000/0. (see source code if using chrome, it doesnt display the page right). It has 1000 hit entries, followed by a little battle info(lastpage will have <1000 obviously). On average, a page contains 175000 characters, UTF-8 encoding, xml format(v 1.0). Program will run locally on a good PC, memory is virtually unlimited(so that creating byte[250000] is quite ok). The format never changes, which is quite convenient. Now, I started off as usual: //global vars,class declaration skipped public WebObject(String url_string, int connection_timeout, int read_timeout, boolean redirects_allowed, String user_agent) throws java.net.MalformedURLException, java.io.IOException { // Open a URL connection java.net.URL url = new java.net.URL(url_string); java.net.URLConnection uconn = url.openConnection(); if (!(uconn instanceof java.net.HttpURLConnection)) { throw new java.lang.IllegalArgumentException("URL protocol must be HTTP"); } conn = (java.net.HttpURLConnection) uconn; conn.setConnectTimeout(connection_timeout); conn.setReadTimeout(read_timeout); conn.setInstanceFollowRedirects(redirects_allowed); conn.setRequestProperty("User-agent", user_agent); } public void executeConnection() throws IOException { try { is = conn.getInputStream(); //global var l = conn.getContentLength(); //global var } catch (Exception e) { //handling code skipped } } //getContentStream and getLength methods which just return'is' and 'l' are skipped Here is where the fun part began. I ran some profiling (using System.currentTimeMillis()) to find out what takes long ,and what doesnt. The call to this method takes only 200ms on avg public InputStream getWebPageAsStream(int battle_id, int page) throws Exception { String url = "http://api.erepublik.com/v1/feeds/battle_logs/" + battle_id + "/" + page; WebObject wobj = new WebObject(url, 10000, 10000, true, "Mozilla/5.0 " + "(Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)"); wobj.executeConnection(); l = wobj.getContentLength(); // global variable return wobj.getContentStream(); //returns 'is' stream } 200ms is quite expected from a network operation, and i am fine with it. BUT when i parse the inputStream in any way(read it into string/use java XML parser/read it into another ByteArrayStream) the process takes over 1000ms! for example, this code takes 1000ms IF i pass the stream i got('is') above from getContentStream() directly to this method: public static Document convertToXML(InputStream is) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(is); doc.getDocumentElement().normalize(); return doc; } this code too, takes around 920ms IF the initial InputStream 'is' is passed in(dont read into the code itself - it just extracts the data i need by directly counting the characters, which can be done thanks to the rigid api feed format): public static parsedBattlePage convertBattleToXMLWithoutDOM(InputStream is) throws IOException { // Point A BufferedReader br = new BufferedReader(new InputStreamReader(is)); LinkedList ll = new LinkedList(); String str = br.readLine(); while (str != null) { ll.add(str); str = br.readLine(); } if (((String) ll.get(1)).indexOf("error") != -1) { return new parsedBattlePage(null, null, true, -1); } //Point B Iterator it = ll.iterator(); it.next(); it.next(); it.next(); it.next(); String[][] hits_arr = new String[1000][4]; String t_str = (String) it.next(); String tmp = null; int j = 0; for (int i = 0; t_str.indexOf("time") != -1; i++) { hits_arr[i][0] = t_str.substring(12, t_str.length() - 11); tmp = (String) it.next(); hits_arr[i][1] = tmp.substring(14, tmp.length() - 9); tmp = (String) it.next(); hits_arr[i][2] = tmp.substring(15, tmp.length() - 10); tmp = (String) it.next(); hits_arr[i][3] = tmp.substring(18, tmp.length() - 13); it.next(); it.next(); t_str = (String) it.next(); j++; } String[] b_info_arr = new String[9]; int[] space_nums = {13, 10, 13, 11, 11, 12, 5, 10, 13}; for (int i = 0; i < space_nums.length; i++) { tmp = (String) it.next(); b_info_arr[i] = tmp.substring(space_nums[i] + 4, tmp.length() - space_nums[i] - 1); } //Point C return new parsedBattlePage(hits_arr, b_info_arr, false, j); } I have tried replacing the default BufferedReader with BufferedReader br = new BufferedReader(new InputStreamReader(is), 250000); This didnt change much. My second try was to replace the code between A and B with: Iterator it = IOUtils.lineIterator(is, "UTF-8"); Same result, except this time A-B was 0ms, and B-C was 1000ms, so then every call to it.next() must have been consuming some significant time.(IOUtils is from apache-commons-io library). And here is the culprit - the time taken to parse the stream to string, be it by an iterator or BufferedReader in ALL cases was about 1000ms, while the rest of the code took 0ms(e.g. irrelevant). This means that parsing the stream to LinkedList, or iterating over it, for some reason was eating up a lot of my system resources. question was - why? Is it just the way java is made...no...thats just stupid, so I did another experiment. In my main method I added after the getWebPageAsStream(): //Point A ba = new byte[l]; // 'l' comes from wobj.getContentLength above bytesRead = is.read(ba); //'is' is our URLConnection original InputStream offset = bytesRead; while (bytesRead != -1) { bytesRead = is.read(ba, offset - 1, l - offset); offset += bytesRead; } //Point B InputStream is2 = new ByteArrayInputStream(ba); //Now just working with 'is2' - the "copied" stream The InputStream-byte[] conversion took again 1000ms - this is the way many ppl suggested to read an InputStream, and stil it is slow. And guess what - the 2 parser methods above (convertToXML() and convertBattlePagetoXMLWithoutDOM(), when passed 'is2' instead of 'is' took, in all 4 cases, under 50ms to complete. I read a suggestion that the stream waits for connection to close before unblocking, so i tried using HttpComponentsClient 4.0 (http://hc.apache.org/httpcomponents-client/index.html) instead, but the initial InputStream took just as long to parse. e.g. this code: public InputStream getWebPageAsStream2(int battle_id, int page) throws Exception { String url = "http://api.erepublik.com/v1/feeds/battle_logs/" + battle_id + "/" + page; HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpParams p = new BasicHttpParams(); HttpConnectionParams.setSocketBufferSize(p, 250000); HttpConnectionParams.setStaleCheckingEnabled(p, false); HttpConnectionParams.setConnectionTimeout(p, 5000); httpget.setParams(p); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); l = (int) entity.getContentLength(); return entity.getContent(); } took even longer to process(50ms more for just the network) and the stream parsing times remained the same. Obviously it can be instantiated so as to not create HttpClient and properties every time(faster network time), but the stream issue wont be affected by that. So we come to the center problem - why does the initial URLConnection InputStream(or HttpClient InputStream) take so long to process, while any stream of same size and content created locally is orders of magnitude faster? I mean, the initial response is already somewhere in RAM, and I cant see any good reasong why it is processed so slowly compared to when a same stream is just created from a byte[]. Considering I have to parse million of entries and thousands of pages like that, a total processing time of almost 1.5s/page seems WAY WAY too long. Any ideas? P.S. Please ask in any more code is required - the only thing I do after parsing is make a PreparedStatement and put the entries into JavaDB in packs of 1000+, and the perfomance is ok ~ 200ms/1000entries, prb could be optimized with more cache but I didnt look into it much.

    Read the article

  • how to execute two thread simultaneously in java swing?

    - by jcrshankar
    My aim is to select all the files named with MANI.txt which is present in their respective folders and then load path of the MANI.txt files different location in table. After I load the path in the table,I used to select needed path and modifiying those. To load the MANI.txt files taking more time,because it may present more than 30 times in my workspace or etc. until load the files I want to give alarm to the user with help of ProgessBar.Once the list size has been populated I need to disable ProgressBar. Could anyone please help me out on this? import java.awt.*; import javax.swing.*; import javax.swing.table.*; import java.awt.event.*; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class JTableHeaderCheckBox extends JFrame implements ActionListener { Object colNames[] = {"", "Path"}; Object[][] data = {}; DefaultTableModel dtm; JTable table; JButton but; java.util.List list; public void buildGUI() { dtm = new DefaultTableModel(data,colNames); table = new JTable(dtm); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); int vColIndex = 0; TableColumn col = table.getColumnModel().getColumn(vColIndex); int width = 10; col.setPreferredWidth(width); int vColIndex1 = 1; TableColumn col1 = table.getColumnModel().getColumn(vColIndex1); int width1 = 500; col1.setPreferredWidth(width1); JFileChooser chooser = new JFileChooser(); //chooser.setCurrentDirectory(new java.io.File(".")); chooser.setDialogTitle("Choose workSpace Path"); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setAcceptAllFileFilterUsed(false); if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){ System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory()); System.out.println("getSelectedFile() : " + chooser.getSelectedFile().getAbsolutePath()); } String path= chooser.getSelectedFile().getAbsolutePath(); File folder = new File(path); Here I need progress bar GatheringFiles ob = new GatheringFiles(); list=ob.returnlist(folder); for(int x = 0; x < list.size(); x++) { dtm.addRow(new Object[]{new Boolean(false),list.get(x).toString()}); } JPanel pan = new JPanel(); JScrollPane sp = new JScrollPane(table); TableColumn tc = table.getColumnModel().getColumn(0); tc.setCellEditor(table.getDefaultEditor(Boolean.class)); tc.setCellRenderer(table.getDefaultRenderer(Boolean.class)); tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener())); but = new JButton("REMOVE"); JFrame f = new JFrame(); pan.add(sp); but.move(650, 50); but.addActionListener(this); pan.add(but); f.add(pan); f.setSize(700, 100); f.pack(); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } class MyItemListener implements ItemListener { public void itemStateChanged(ItemEvent e) { Object source = e.getSource(); if (source instanceof AbstractButton == false) return; boolean checked = e.getStateChange() == ItemEvent.SELECTED; for(int x = 0, y = table.getRowCount(); x < y; x++) { table.setValueAt(new Boolean(checked),x,0); } } } public static void main (String[] args) { SwingUtilities.invokeLater(new Runnable(){ public void run(){ new JTableHeaderCheckBox().buildGUI(); } }); } public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource()==but) { System.err.println("table.getRowCount()"+table.getRowCount()); for(int x = 0, y = table.getRowCount(); x < y; x++) { if("true".equals(table.getValueAt(x, 0).toString())) { System.err.println(table.getValueAt(x, 0)); System.err.println(list.get(x).toString()); delete(list.get(x).toString()); } } } } public void delete(String a) { String delete = "C:"; System.err.println(a); try { File inFile = new File(a); if (!inFile.isFile()) { System.out.println("Parameter is not an existing file"); return; } //Construct the new file that will later be renamed to the original filename. File tempFile = new File(inFile.getAbsolutePath() + ".tmp"); BufferedReader br = new BufferedReader(new FileReader(inFile)); PrintWriter pw = new PrintWriter(new FileWriter(tempFile)); String line = null; //Read from the original file and write to the new //unless content matches data to be removed. while ((line = br.readLine()) != null) { System.err.println(line); line = line.replace(delete, " "); pw.println(line); pw.flush(); } pw.close(); br.close(); //Delete the original file if (!inFile.delete()) { System.out.println("Could not delete file"); return; } //Rename the new file to the filename the original file had. if (!tempFile.renameTo(inFile)) System.out.println("Could not rename file"); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } } class CheckBoxHeader extends JCheckBox implements TableCellRenderer, MouseListener { protected CheckBoxHeader rendererComponent; protected int column; protected boolean mousePressed = false; public CheckBoxHeader(ItemListener itemListener) { rendererComponent = this; rendererComponent.addItemListener(itemListener); } public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (table != null) { JTableHeader header = table.getTableHeader(); if (header != null) { rendererComponent.setForeground(header.getForeground()); rendererComponent.setBackground(header.getBackground()); rendererComponent.setFont(header.getFont()); header.addMouseListener(rendererComponent); } } setColumn(column); rendererComponent.setText("Check All"); setBorder(UIManager.getBorder("TableHeader.cellBorder")); return rendererComponent; } protected void setColumn(int column) { this.column = column; } public int getColumn() { return column; } protected void handleClickEvent(MouseEvent e) { if (mousePressed) { mousePressed=false; JTableHeader header = (JTableHeader)(e.getSource()); JTable tableView = header.getTable(); TableColumnModel columnModel = tableView.getColumnModel(); int viewColumn = columnModel.getColumnIndexAtX(e.getX()); int column = tableView.convertColumnIndexToModel(viewColumn); if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) { doClick(); } } } public void mouseClicked(MouseEvent e) { handleClickEvent(e); ((JTableHeader)e.getSource()).repaint(); } public void mousePressed(MouseEvent e) { mousePressed = true; } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } } ****************** import java.io.File; import java.util.*; public class GatheringFiles { public static List returnlist(File folder) { List<File> list = new ArrayList<File>(); List<File> list1 = new ArrayList<File>(); getFiles(folder, list); return list; } private static void getFiles(File folder, List<File> list) { folder.setReadOnly(); File[] files = folder.listFiles(); for(int j = 0; j < files.length; j++) { if( "MANI.txt".equals(files[j].getName())) { list.add(files[j]); } if(files[j].isDirectory()) getFiles(files[j], list); } } }

    Read the article

  • Jdbc - Connect remote Mysql Database error

    - by Guilherme Ruiz
    I'm using JDBC to connect my program to a MySQL database. I already put the port number and yes, my database have permission to access. When i use localhost work perfectly, but when i try connect to a remote MySQL database, show this error on console. java.lang.ExceptionInInitializerError Caused by: java.lang.NumberFormatException: null at java.lang.Integer.parseInt(Integer.java:454) at java.lang.Integer.parseInt(Integer.java:527) at serial.BDArduino.<clinit>(BDArduino.java:25) Exception in thread "main" Java Result: 1 CONSTRUÍDO COM SUCESSO (tempo total: 1 segundo) Thank you in Advance ! MAIN CODE /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package serial; import gnu.io.CommPort; import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * * @author Ruiz */ public class BDArduino extends JFrame { static boolean connected = false; static int aux_sql8 = Integer.parseInt(Sql.getDBinfo("SELECT * FROM arduinoData WHERE id=1", "pin8")); static int aux_sql2 = Integer.parseInt(Sql.getDBinfo("SELECT * FROM arduinoData WHERE id=1", "pin2")); CommPort commPort = null; SerialPort serialPort = null; InputStream inputStream = null; static OutputStream outputStream = null; String comPortNum = "COM10"; int baudRate = 9600; int[] intArray = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; /** * Creates new form ArduinoTest */ public BDArduino() { //super("Arduino Test App"); initComponents(); } class Escrita extends Thread { private int i; public void run() { while (true) { System.out.println("Número :" + i++); } } } //public void actionPerformed(ActionEvent e) { // String arg = e.getActionCommand(); public static void writeData(int a) throws IOException { outputStream.write(a); } public void action(String arg) { System.out.println(arg); Object[] msg = {"Baud Rate: ", "9600", "COM Port #: ", "COM10"}; if (arg == "connect") { if (connected == false) { new BDArduino.ConnectionMaker().start(); } else { closeConnection(); } } if (arg == "disconnect") { serialPort.close(); closeConnection(); } if (arg == "p2") { System.out.print("Pin #2\n"); try { outputStream.write(intArray[0]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p3") { System.out.print("Pin #3\n"); try { outputStream.write(intArray[1]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p4") { System.out.print("Pin #4\n"); try { outputStream.write(intArray[2]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p5") { System.out.print("Pin #5\n"); try { outputStream.write(intArray[3]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p6") { System.out.print("Pin #6\n"); try { outputStream.write(intArray[4]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p7") { System.out.print("Pin #7\n"); try { outputStream.write(intArray[5]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p8") { System.out.print("Pin #8\n"); try { outputStream.write(intArray[6]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p9") { System.out.print("Pin #9\n"); try { outputStream.write(intArray[7]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p10") { System.out.print("Pin #10\n"); try { outputStream.write(intArray[8]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p11") { System.out.print("Pin #11\n"); try { outputStream.write(intArray[9]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p12") { System.out.print("Pin #12\n"); try { outputStream.write(intArray[10]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } if (arg == "p13") { System.out.print("Pin #12\n"); try { outputStream.write(intArray[11]); }//end try catch (IOException e12) { e12.printStackTrace(); System.exit(-1); }//end catch } } //******************************************************* //Arduino Connection *************************************** //****************************************************** void closeConnection() { try { outputStream.close(); } catch (Exception ex) { ex.printStackTrace(); String cantCloseConnectionMessage = "Can't Close Connection!"; JOptionPane.showMessageDialog(null, cantCloseConnectionMessage, "ERROR", JOptionPane.ERROR_MESSAGE); } connected = false; System.out.print("\nDesconectado\n"); String disconnectedConnectionMessage = "Desconectado!"; JOptionPane.showMessageDialog(null, disconnectedConnectionMessage, "Desconectado", JOptionPane.INFORMATION_MESSAGE); }//end closeConnection() void connect() throws Exception { String portName = comPortNum; CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); if (portIdentifier.isCurrentlyOwned()) { System.out.println("Error: Port is currently in use"); String portInUseConnectionMessage = "Port is currently in use!\nTry Again Later..."; JOptionPane.showMessageDialog(null, portInUseConnectionMessage, "ERROR", JOptionPane.ERROR_MESSAGE); } else { commPort = portIdentifier.open(this.getClass().getName(), 2000); if (commPort instanceof SerialPort) { serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); outputStream = serialPort.getOutputStream(); } else { System.out.println("Error: Only serial ports are handled "); String onlySerialConnectionMessage = "Serial Ports ONLY!"; JOptionPane.showMessageDialog(null, onlySerialConnectionMessage, "ERROR", JOptionPane.ERROR_MESSAGE); } }//end else //wait some time try { Thread.sleep(300); } catch (InterruptedException ie) { } }//end connect //******************************************************* //*innerclasses****************************************** //******************************************************* public class ConnectionMaker extends Thread { public void run() { //try to make a connection try { connect(); } catch (Exception ex) { ex.printStackTrace(); System.out.print("ERROR: Cannot connect!"); String cantConnectConnectionMessage = "Cannot Connect!\nCheck the connection settings\nand/or your configuration\nand try again!"; JOptionPane.showMessageDialog(null, cantConnectConnectionMessage, "ERROR", JOptionPane.ERROR_MESSAGE); } //show status serialPort.notifyOnDataAvailable(true); connected = true; //send ack System.out.print("\nConnected\n"); String connectedConnectionMessage = "Conectado!"; JOptionPane.showMessageDialog(null, connectedConnectionMessage, "Conectado", JOptionPane.INFORMATION_MESSAGE); }//end run }//end ConnectionMaker /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { btnp2 = new javax.swing.JButton(); btncon = new javax.swing.JButton(); btndesc = new javax.swing.JButton(); btnp3 = new javax.swing.JButton(); btnp4 = new javax.swing.JButton(); btnp5 = new javax.swing.JButton(); btnp9 = new javax.swing.JButton(); btnp6 = new javax.swing.JButton(); btnp7 = new javax.swing.JButton(); btnp8 = new javax.swing.JButton(); btn13 = new javax.swing.JButton(); btnp10 = new javax.swing.JButton(); btnp11 = new javax.swing.JButton(); btnp12 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); btnp2.setText("2"); btnp2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp2MouseClicked(evt); } }); btncon.setText("Conectar"); btncon.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnconMouseClicked(evt); } }); btndesc.setText("Desconectar"); btndesc.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btndescMouseClicked(evt); } }); btnp3.setText("3"); btnp3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp3MouseClicked(evt); } }); btnp4.setText("4"); btnp4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp4MouseClicked(evt); } }); btnp5.setText("5"); btnp5.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp5MouseClicked(evt); } }); btnp9.setText("9"); btnp9.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp9MouseClicked(evt); } }); btnp6.setText("6"); btnp6.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp6MouseClicked(evt); } }); btnp7.setText("7"); btnp7.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp7MouseClicked(evt); } }); btnp8.setText("8"); btnp8.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp8MouseClicked(evt); } }); btn13.setText("13"); btn13.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btn13MouseClicked(evt); } }); btnp10.setText("10"); btnp10.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp10MouseClicked(evt); } }); btnp11.setText("11"); btnp11.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp11MouseClicked(evt); } }); btnp12.setText("12"); btnp12.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnp12MouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(btncon) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btndesc)) .addGroup(layout.createSequentialGroup() .addComponent(btnp6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp8, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp9, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(btnp10, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp11, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp12, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btn13, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(btnp2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnp5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(20, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btncon) .addComponent(btndesc)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnp2) .addComponent(btnp3) .addComponent(btnp4) .addComponent(btnp5)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnp6) .addComponent(btnp7) .addComponent(btnp8) .addComponent(btnp9)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnp10) .addComponent(btnp11) .addComponent(btnp12) .addComponent(btn13)) .addGap(22, 22, 22)) ); pack(); }// </editor-fold> private void btnp2MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p2"); } private void btnconMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("connect"); } private void btndescMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("disconnect"); } private void btnp3MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p3"); } private void btnp4MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p4"); } private void btnp5MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here action("p5"); } private void btnp9MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p9"); } private void btnp6MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p6"); } private void btnp7MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p7"); } private void btnp8MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p8"); } private void btn13MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p13"); } private void btnp10MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p10"); } private void btnp11MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p11"); } private void btnp12MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: action("p12"); } /** * @param args the command line arguments */ public static void main(String args[]) throws IOException { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new BDArduino().setVisible(true); } }); //} while (true) { // int sql8 = Integer.parseInt(Sql.getDBinfo("SELECT * FROM arduinoData WHERE id=1", "pin8")); if (connected == true && sql8 != aux_sql8) { aux_sql8 = sql8; if(sql8 == 1){ writeData(2); }else{ writeData(3); } } int sql2 = Integer.parseInt(Sql.getDBinfo("SELECT * FROM arduinoData WHERE id=1", "pin2")); if (connected == true && sql2 != aux_sql2) { aux_sql2 = sql2; if(sql2 == 1){ writeData(4); }else{ writeData(5); } } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } // Variables declaration - do not modify private javax.swing.JButton btn13; private javax.swing.JButton btncon; private javax.swing.JButton btndesc; private javax.swing.JButton btnp10; private javax.swing.JButton btnp11; private javax.swing.JButton btnp12; private javax.swing.JButton btnp2; private javax.swing.JButton btnp3; private javax.swing.JButton btnp4; private javax.swing.JButton btnp5; private javax.swing.JButton btnp6; private javax.swing.JButton btnp7; private javax.swing.JButton btnp8; private javax.swing.JButton btnp9; // End of variables declaration }

    Read the article

  • Thread not behaving correctly

    - by ivor
    Hello, I wonder if anyone can help me to understand where I could be going wrong with this code; Basically I'm working on a turorial and calling the class below from another class - and it is getting the following error; Exception in thread "Thread-1" java.lang.NullPointerException at org.newdawn.spaceinvaders.TCPChat.run(TCPChat.java:322) at java.lang.Thread.run(Unknown Source) I realise the error is beibg flagged in another class- but I have tested the other class with a small class which sets up a separate thread - and it works fine, but as soon as I try and implement a new thread in this class - it causes all sorts of problems. Am I setting up the thread correctly in this class? Basically I can set up a thread in this class, with a test loop and it's fine, but when I bring in the functionality of the rest of the game it sometimes hangs, or does not display at all. Any suggestions on where I could be going wrong would be greatly appreciated. Thanks for looking. package org.newdawn.spaceinvaders; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferStrategy; import java.util.ArrayList; import java.util.Scanner; import java.awt.*;//maybe not needed import javax.swing.*;//maybenot needed import java.util.Random; //import java.io.*; /** * The main hook of our game. This class with both act as a manager * for the display and central mediator for the game logic. * * Display management will consist of a loop that cycles round all * entities in the game asking them to move and then drawing them * in the appropriate place. With the help of an inner class it * will also allow the player to control the main ship. * * As a mediator it will be informed when entities within our game * detect events (e.g. alient killed, played died) and will take * appropriate game actions. * * @author Kevin Glass */ public class Game extends Canvas implements Runnable{ /** The stragey that allows us to use accelerate page flipping */ private BufferStrategy strategy; /** True if the game is currently "running", i.e. the game loop is looping */ private boolean gameRunning = true; /** The list of all the entities that exist in our game */ private ArrayList entities = new ArrayList(); /** The list of entities that need to be removed from the game this loop */ private ArrayList removeList = new ArrayList(); /** The entity representing the player */ private Entity ship; /** The speed at which the player's ship should move (pixels/sec) */ private double moveSpeed = 300; /** The time at which last fired a shot */ private long lastFire = 0; /** The interval between our players shot (ms) */ private long firingInterval = 500; /** The number of aliens left on the screen */ private int alienCount; /** The number of levels progressed */ private double levelCount; /** high score for the user */ private int highScore; /** high score for the user */ private String player = "bob"; //private GetUserInput getPlayer; /** The list of entities that need to be removed from the game this loop */ /** The message to display which waiting for a key press */ private String message = ""; /** True if we're holding up game play until a key has been pressed */ private boolean waitingForKeyPress = true; /** True if the left cursor key is currently pressed */ private boolean leftPressed = false; /** True if the right cursor key is currently pressed */ private boolean rightPressed = false; /** True if we are firing */ private boolean firePressed = false; /** True if game logic needs to be applied this loop, normally as a result of a game event */ private boolean logicRequiredThisLoop = false; //private Thread cThread = new Thread(this); //public Thread t = new Thread(this); //private Thread g = new Thread(this); void setHighscore(int setHS) { highScore = setHS; } public int getHighscore() { return highScore; } public void setPlayer(String setPlayer) { player = setPlayer; } public String getPlayer() { return player; } public void run() { //setup(); System.out.println("hello im running bob"); /*int count = 1; do { System.out.println("Count is: " + count); count++; try{Thread.sleep(1);} catch(InterruptedException e){} } while (count <= 2000000);*/ //Game g =new Game(); //Game g = this; // Start the main game loop, note: this method will not // return until the game has finished running. Hence we are // using the actual main thread to run the game. //setup(); //this.gameLoop(); //try{thread.sleep(1);} //catch{InterruptedException e} } /** * Construct our game and set it running. */ public Game () { //Thread t = new Thread(this);//set up new thread for invaders game //t.run();//run the run method of the game //Game g =new Game(); //setup(); //Thread t = new Thread(this); //thread.start(); //SwingUtilities.invokeLater(this); Thread er = new Thread(this); er.start(); } public void setup(){ //initialise highscore setHighscore(0); // create a frame to contain our game JFrame container = new JFrame("Space Invaders 101"); // get hold the content of the frame and set up the resolution of the game JPanel panel = (JPanel) container.getContentPane(); panel.setPreferredSize(new Dimension(800,600)); //panel.setLayout(null); // setup our canvas size and put it into the content of the frame setBounds(0,0,800,600); panel.add(this); // Tell AWT not to bother repainting our canvas since we're // going to do that our self in accelerated mode setIgnoreRepaint(true); // finally make the window visible container.pack(); container.setResizable(false); container.setVisible(true); // add a listener to respond to the user closing the window. If they // do we'd like to exit the game container.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //cThread.interrupt(); System.exit(0); } }); // add a key input system (defined below) to our canvas // so we can respond to key pressed addKeyListener(new KeyInputHandler()); // request the focus so key events come to us requestFocus(); // create the buffering strategy which will allow AWT // to manage our accelerated graphics createBufferStrategy(2); strategy = getBufferStrategy(); // initialise the entities in our game so there's something // to see at startup initEntities(); } /** * Start a fresh game, this should clear out any old data and * create a new set. */ private void startGame() { // clear out any existing entities and intialise a new set entities.clear(); initEntities(); //initialise highscore setHighscore(0); // blank out any keyboard settings we might currently have leftPressed = false; rightPressed = false; firePressed = false; } /** * Initialise the starting state of the entities (ship and aliens). Each * entitiy will be added to the overall list of entities in the game. */ //private void initEntities() { public void initEntities() { Random randomAlien = new Random(); // create the player ship and place it roughly in the center of the screen //ship = new ShipEntity(this,"sprites/ship.gif",370,550);//orignal ship = new ShipEntity(this,"sprites/ship.gif",700,300);//changed postioning to right hand side entities.add(ship); // create a block of aliens (5 rows, by 12 aliens, spaced evenly) alienCount = 0; levelCount = 1.02; for (int row=0;row<7;row++) {//altered number of rows for (int x=0;x<5;x++) { int r = randomAlien.nextInt(100);//loop added to produce random aliens if (r < 50){ //Entity alien = new AlienEntity(this,"sprites/alien.gif",/*100+*/(x*50),(50)+row*30); Entity alien = new AlienEntity(this,"sprites/alien.gif",100+(x*90),(12)+row*85); entities.add(alien); alienCount++; } } } } //private void initEntities() { public void initAlienEntities() { Random randomAlien = new Random(); // create the player ship and place it roughly in the center of the screen //ship = new ShipEntity(this,"sprites/ship.gif",370,550);//orignal //ship = new ShipEntity(this,"sprites/ship.gif",700,300);//changed postioning to right hand side //entities.add(ship); // create a block of aliens (5 rows, by 12 aliens, spaced evenly) alienCount = 0; levelCount = levelCount + 0.10;//this increases the speed on every level for (int row=0;row<7;row++) {//altered number of rows for (int x=0;x<5;x++) { int r = randomAlien.nextInt(100);//loop added to produce random aliens if (r < 50){//randome check to show alien //Entity alien = new AlienEntity(this,"sprites/alien.gif",/*100+*/(x*50),(50)+row*30); Entity alien = new AlienEntity(this,"sprites/alien.gif",-250+(x*90),(12)+row*85); entities.add(alien); alienCount++; } } } advanceAlienSpeed(levelCount); } /** * Notification from a game entity that the logic of the game * should be run at the next opportunity (normally as a result of some * game event) */ public void updateLogic() { logicRequiredThisLoop = true; } /** * Remove an entity from the game. The entity removed will * no longer move or be drawn. * * @param entity The entity that should be removed */ public void removeEntity(Entity entity) { removeList.add(entity); } /** * Notification that the player has died. */ public void notifyDeath() { message = "Oh no! They got you, try again?"; waitingForKeyPress = true; } /** * Notification that the player has won since all the aliens * are dead. */ public void notifyWin() { message = "Well done! You Win!"; waitingForKeyPress = true; } /** * Notification that an alien has been killed */ public void notifyAlienKilled() { // reduce the alient count, if there are none left, the player has won! alienCount--; if (alienCount == 0) { //notifyWin();win not relevant here... this.initAlienEntities();//call fresh batch of aliens } // if there are still some aliens left then they all need to get faster, so // speed up all the existing aliens advanceAlienSpeed(1.30); } public void advanceAlienSpeed(double speed) { // if there are still some aliens left then they all need to get faster, so // speed up all the existing aliens for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); if (entity instanceof AlienEntity) { // speed up by 2% entity.setHorizontalMovement(entity.getHorizontalMovement() * speed); //entity.setVerticalMovement(entity.getVerticalMovement() * 1.02); } } } /** * Attempt to fire a shot from the player. Its called "try" * since we must first check that the player can fire at this * point, i.e. has he/she waited long enough between shots */ public void tryToFire() { // check that we have waiting long enough to fire if (System.currentTimeMillis() - lastFire < firingInterval) { return; } // if we waited long enough, create the shot entity, and record the time. lastFire = System.currentTimeMillis(); ShotEntity shot = new ShotEntity(this,"sprites/shot.gif",ship.getX()+10,ship.getY()-30); entities.add(shot); } /** * The main game loop. This loop is running during all game * play as is responsible for the following activities: * <p> * - Working out the speed of the game loop to update moves * - Moving the game entities * - Drawing the screen contents (entities, text) * - Updating game events * - Checking Input * <p> */ public void gameLoop() { long lastLoopTime = System.currentTimeMillis(); // keep looping round til the game ends while (gameRunning) { // work out how long its been since the last update, this // will be used to calculate how far the entities should // move this loop long delta = System.currentTimeMillis() - lastLoopTime; lastLoopTime = System.currentTimeMillis(); // Get hold of a graphics context for the accelerated // surface and blank it out Graphics2D g = (Graphics2D) strategy.getDrawGraphics(); g.setColor(Color.black); g.fillRect(0,0,800,600); // cycle round asking each entity to move itself if (!waitingForKeyPress) { for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.move(delta); } } // cycle round drawing all the entities we have in the game for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.draw(g); } // brute force collisions, compare every entity against // every other entity. If any of them collide notify // both entities that the collision has occured for (int p=0;p<entities.size();p++) { for (int s=p+1;s<entities.size();s++) { Entity me = (Entity) entities.get(p); Entity him = (Entity) entities.get(s); if (me.collidesWith(him)) { me.collidedWith(him); him.collidedWith(me); } } } // remove any entity that has been marked for clear up entities.removeAll(removeList); removeList.clear(); // if a game event has indicated that game logic should // be resolved, cycle round every entity requesting that // their personal logic should be considered. if (logicRequiredThisLoop) { //g.drawString("Press any key",(800-g.getFontMetrics().stringWidth("Press any key"))/2,300); for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.doLogic(); } logicRequiredThisLoop = false; } // if we're waiting for an "any key" press then draw the // current message //show highscore at top of screen //show name at top of screen g.setColor(Color.white); g.drawString("Player : "+getPlayer()+" : Score : "+getHighscore(),20,20); if (waitingForKeyPress) { g.setColor(Color.white); g.drawString(message,(800-g.getFontMetrics().stringWidth(message))/2,250); g.drawString("Press any key",(800-g.getFontMetrics().stringWidth("Press any key"))/2,300); } // finally, we've completed drawing so clear up the graphics // and flip the buffer over g.dispose(); strategy.show(); // resolve the movement of the ship. First assume the ship // isn't moving. If either cursor key is pressed then // update the movement appropraitely ship.setVerticalMovement(0);//set to vertical movement if ((leftPressed) && (!rightPressed)) { ship.setVerticalMovement(-moveSpeed);//**took out setHorizaontalMOvement } else if ((rightPressed) && (!leftPressed)) { ship.setVerticalMovement(moveSpeed);//**took out setHorizaontalMOvement } // if we're pressing fire, attempt to fire if (firePressed) { tryToFire(); } // finally pause for a bit. Note: this should run us at about // 100 fps but on windows this might vary each loop due to // a bad implementation of timer try { Thread.sleep(10); } catch (Exception e) {} } } /** * A class to handle keyboard input from the user. The class * handles both dynamic input during game play, i.e. left/right * and shoot, and more static type input (i.e. press any key to * continue) * * This has been implemented as an inner class more through * habbit then anything else. Its perfectly normal to implement * this as seperate class if slight less convienient. * * @author Kevin Glass */ private class KeyInputHandler extends KeyAdapter { /** The number of key presses we've had while waiting for an "any key" press */ private int pressCount = 1; /** * Notification from AWT that a key has been pressed. Note that * a key being pressed is equal to being pushed down but *NOT* * released. Thats where keyTyped() comes in. * * @param e The details of the key that was pressed */ public void keyPressed(KeyEvent e) { // if we're waiting for an "any key" typed then we don't // want to do anything with just a "press" if (waitingForKeyPress) { return; } // if (e.getKeyCode() == KeyEvent.VK_LEFT) { ////leftPressed = true; ///} //// if (e.getKeyCode() == KeyEvent.VK_RIGHT) { //rightPressed = true; if (e.getKeyCode() == KeyEvent.VK_UP) { leftPressed = true; } if (e.getKeyCode() == KeyEvent.VK_DOWN) { rightPressed = true; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { firePressed = true; } } /** * Notification from AWT that a key has been released. * * @param e The details of the key that was released */ public void keyReleased(KeyEvent e) { // if we're waiting for an "any key" typed then we don't // want to do anything with just a "released" if (waitingForKeyPress) { return; } if (e.getKeyCode() == KeyEvent.VK_UP) {//changed from VK_LEFT leftPressed = false; } if (e.getKeyCode() == KeyEvent.VK_DOWN) {//changed from VK_RIGHT rightPressed = false; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { firePressed = false; } } /** * Notification from AWT that a key has been typed. Note that * typing a key means to both press and then release it. * * @param e The details of the key that was typed. */ public void keyTyped(KeyEvent e) { // if we're waiting for a "any key" type then // check if we've recieved any recently. We may // have had a keyType() event from the user releasing // the shoot or move keys, hence the use of the "pressCount" // counter. if (waitingForKeyPress) { if (pressCount == 1) { // since we've now recieved our key typed // event we can mark it as such and start // our new game waitingForKeyPress = false; startGame(); pressCount = 0; } else { pressCount++; } } // if we hit escape, then quit the game if (e.getKeyChar() == 27) { //cThread.interrupt(); System.exit(0); } } } /** * The entry point into the game. We'll simply create an * instance of class which will start the display and game * loop. * * @param argv The arguments that are passed into our game */ //public static void main(String argv[]) { //Game g =new Game(); // Start the main game loop, note: this method will not // return until the game has finished running. Hence we are // using the actual main thread to run the game. //g.gameLoop(); //} }

    Read the article

< Previous Page | 7 8 9 10 11