Search Results

Search found 2946 results on 118 pages for 'ex umbris'.

Page 4/118 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Parsing csv line to Java objects

    - by Noobling
    I was wondering if someone here could help me, I can't find a solution for my problem and I have tried everything. What I am trying to do is read and parse lines in a csv file into java objects and I have succeeded in doing that but after it reads all the lines it should insert the lines into the database but it only inserts the 1st line the entire time and I don't no why. When I do a print it shows that it is reading all the lines and placing them in the objects but as soon as I do the insert it wants to insert only the 1st line. Please see my code below: public boolean lineReader(File file){ BufferedReader br = null; String line= ""; String splitBy = ","; storeList = new ArrayList<StoreFile>(); try { br = new BufferedReader(new FileReader(file)); while((line = br.readLine())!=null){ line = line.replace('|', ','); //split on pipe ( | ) String[] array = line.split(splitBy, 14); //Add values from csv to store object //Add values from csv to storeF objects StoreFile StoreF = new StoreFile(); if (array[0].equals("H") || array[0].equals("T")) { return false; } else { StoreF.setRetailID(array[1].replaceAll("/", "")); StoreF.setChain(array[2].replaceAll("/","")); StoreF.setStoreID(array[3].replaceAll("/", "")); StoreF.setStoreName(array[4].replaceAll("/", "")); StoreF.setAddress1(array[5].replaceAll("/", "")); StoreF.setAddress2(array[6].replaceAll("/", "")); StoreF.setAddress3(array[7].replaceAll("/", "")); StoreF.setProvince(array[8].replaceAll("/", "")); StoreF.setAddress4(array[9].replaceAll("/", "")); StoreF.setCountry(array[10].replaceAll("/", "")); StoreF.setCurrency(array[11].replaceAll("/", "")); StoreF.setAddress5(array[12].replaceAll("/", "")); StoreF.setTelNo(array[13].replaceAll("/", "")); //Add stores to list storeList.add(StoreF); } } //print list stores in file printStoreList(storeList); executeStoredPro(storeList); } catch (Exception ex) { nmtbatchservice.NMTBatchService2.LOG.error("An exception accoured: " + ex.getMessage(), ex); //copy to error folder //email } return false; } public void printStoreList(List<StoreFile> storeListToPrint) { for(int i = 0; i <storeListToPrint.size();i++){ System.out.println( storeListToPrint.get(i).getRetailID() + storeListToPrint.get(i).getChain() + storeListToPrint.get(i).getStoreID() + storeListToPrint.get(i).getStoreName() + storeListToPrint.get(i).getAddress1() + storeListToPrint.get(i).getAddress2() + storeListToPrint.get(i).getAddress3() + storeListToPrint.get(i).getProvince() + storeListToPrint.get(i).getAddress4() + storeListToPrint.get(i).getCountry() + storeListToPrint.get(i).getCurrency() + storeListToPrint.get(i).getAddress5() + storeListToPrint.get(i).getTelNo()); } } public void unzip(String source, String destination) { try { ZipFile zipFile = new ZipFile(source); zipFile.extractAll(destination); deleteStoreFile(source); } catch (ZipException ex) { nmtbatchservice.NMTBatchService2.LOG.error("Error unzipping file : " + ex.getMessage(), ex); } } public void deleteStoreFile(String directory) { try { File file = new File(directory); file.delete(); } catch (Exception ex) { nmtbatchservice.NMTBatchService2.LOG.error("An exception accoured when trying to delete file " + directory + " : " + ex.getMessage(), ex); } } public void executeStoredPro(List<StoreFile> storeListToInsert) { Connection con = null; CallableStatement st = null; try { String connectionURL = MSSQLConnectionURL; Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); con = DriverManager.getConnection(connectionURL, MSSQLUsername, MSSQLPassword); for(int i = 0; i <storeListToInsert.size();i++){ st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay@RetailStores WHERE StoreID = " + storeListToInsert.get(i).getStoreID() + " AND RetailID = "+ storeListToInsert.get(i).getRetailID() + ")" + " UPDATE tblPay@RetailStores " + " SET RetailID = '" + storeListToInsert.get(i).getRetailID() + "'," + " StoreID = '" + storeListToInsert.get(i).getStoreID() + "'," + " StoreName = '" + storeListToInsert.get(i).getStoreName() + "'," + " TestStore = 0," + " Address1 = '" + storeListToInsert.get(i).getAddress1() + "'," + " Address2 = '" + storeListToInsert.get(i).getAddress2() + "'," + " Address3 = '" + storeListToInsert.get(i).getAddress3() + "'," + " Address4 = '" + storeListToInsert.get(i).getAddress4() + "'," + " Address5 = '" + storeListToInsert.get(i).getAddress5() + "'," + " Province = '" + storeListToInsert.get(i).getProvince() + "'," + " TelNo = '" + storeListToInsert.get(i).getTelNo() + "'," + " Enabled = 1" + " ELSE " + " INSERT INTO tblPay@RetailStores ( [RetailID], [StoreID], [StoreName], [TestStore], [Address1], [Address2], [Address3], [Address4], [Address5], [Province], [TelNo] , [Enabled] ) " + " VALUES " + "('" + storeListToInsert.get(i).getRetailID() + "'," + "'" + storeListToInsert.get(i).getStoreID() + "'," + "'" + storeListToInsert.get(i).getStoreName() + "'," + "0," + "'" + storeListToInsert.get(i).getAddress1() + "'," + "'" + storeListToInsert.get(i).getAddress2() + "'," + "'" + storeListToInsert.get(i).getAddress3() + "'," + "'" + storeListToInsert.get(i).getAddress4() + "'," + "'" + storeListToInsert.get(i).getAddress5() + "'," + "'" + storeListToInsert.get(i).getProvince() + "'," + "'" + storeListToInsert.get(i).getTelNo() + "'," + "1)"); st.executeUpdate(); } con.close(); } catch (Exception ex) { nmtbatchservice.NMTBatchService2.LOG.error("Error executing Stored proc with error : " + ex.getMessage(), ex); nmtbatchservice.NMTBatchService2.mailingQueue.addToQueue(new Mail("[email protected]", "Service Email Error", "An error occurred during Store Import failed with error : " + ex.getMessage())); } } Any advise would be appreciated. Thanks

    Read the article

  • Help with my application please! Can’t open image(s) with error: External component has thrown an ex

    - by Brandon
    I have an application written in C# I believe and it adds images to a SQL Server 2005 Database. It requires .NET 3.5 to be installed on my computer. I installed .NET 3.5 and setup a database. It runs fine but then once it gets to image 100 when running on one computer, It stops and gives me this error: Can't open image(s) with error: External component has thrown an exception.... When I run the program on my own computer I am able to reach 300 images but then it stops after 300 images and gives me Can't open image(s) with error: External component has thrown an exception.... error once again. please help!

    Read the article

  • Auto-creating a "link" table between 2 main tables (ex table EmployeeProject from Employee and Project tables)

    - by user573382
    Hello! I have these 2 tables, Medication containing: IDMedication, IDCategory, Name, and Supplier, containing: IDSupplier, Name. I want to automatically create a relationship table, MedicationSupplier, containing: IDMedication and IDSupplier as keys, Price, and Quantity. My idea was to have a main page where i request the following data: (Medication)Name, IDCAtegory, (Supplier)Name, Price, Quantity. I'm not sure if i'm doing the right thing here. So this is what i'm receiveing in the .php where i do the insert: $Denumire=$_POST['Denumire']; //Medication Name $IDCategorie=$_POST['IDCategorie']; //IDCategory $Nume=$_POST['Nume']; //Supplier Name $Pret=$_POST['Pret']; //Price $Stoc=$_POST['Stoc']; //Quantity And this is my insert: $q_produse = "INSERT INTO produse VALUES ('','$IDCategorie','$Denumire')"; $q_prodfurniz = "INSERT INTO produsfurnizor VALUES ('','$IDFurnizor','$Pret','$Stoc')"; mysql_query($q_produse) or die($error); mysql_query($q_prodfurniz) or die($error); mysql_close(); My main problem at the moment is that i don't know how to insert IDMedication in the relationship table. Any help / suggestions of improving my code would be greatly appreciated. Thanks!

    Read the article

  • Get rid the slash in URL (ex. something.com/dogs)

    - by jbenes
    I recently purchased the domain name simply.do. I want to use it as a URL shortening service, but I don't like have to do simply.do/something. Can I remove the slash or replace it with a difference symbol? If this helps, I am using a server running Nginx and I will not switch to Apache. Thanks! I would also appreciate any feedback on the domain name. I was hoping to sell simply.do/insurance, simply.do/religion, etc. to various companies. Do you think there is a way I could sell these parts on an auction website? Thanks!

    Read the article

  • How to have PHP and mod_wsgi python app on the same domain?

    - by Lazik
    I am using apache with mod_wsgi (python3) on ubuntu 12.04. I have a python app (bottle) which is at www.mysite.com/ In my python app I have routes like www.mysite.com/abbb?q=blab I would like a path www.mysite.com/forum to resolve to a php app (simple machine forums) Ideally I would like to use apache to handle the forum part and pass it to php (instead of coding it in the python app). Don't know if it's possible. I'm new to this, I have read https://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#The_Apache_Alias_Directive but I don't understand how to use it. Here is my apache conf for the mod_wsgi app, I don't know how to specify the PHP portion. <VirtualHost *:80> ServerName www.ex.com ServerAlias ex.com *.ex.com RewriteEngine On RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}$1 [R=301,L] WSGIDaemonProcess ex user=www-data group=www-data processes=1 threads=5 WSGIScriptAlias / /var/www/vhosts/ex/app.wsgi <Directory /var/www/vhosts/ex> WSGIProcessGroup ex WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory> </VirtualHost>

    Read the article

  • Netbeans with Oracle connection java.lang.ClassNotFoundException

    - by Attilah
    I use NetBeans 6.5 . When I try to run the following code : package com.afrikbrain.numeroteur16; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author */ public class NumeroteurTest { public NumeroteurTest() { } public void doIt() throws ClassNotFoundException{ try { Class.forName("oracle.jdbc.OracleDriver"); Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","user","pwd"); String newNUMERO = new Numeroteur16("MATCLI", connection).numeroter(); System.out.println("NUMERO GENERE : "+newNUMERO.toString()); } catch (SQLException ex) { Logger.getLogger(NumeroteurTest.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } catch (NumException ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } } public static void main(String[] args){ try { new NumeroteurTest().doIt(); } catch (ClassNotFoundException ex) { Logger.getLogger(NumeroteurTest.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Driver not found."); } } } when running it, I get this error : java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver 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:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:252) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:169) at com.afrikbrain.numeroteur16.NumeroteurTest.doIt(NumeroteurTest.java:27) at com.afrikbrain.numeroteur16.NumeroteurTest.main(NumeroteurTest.java:45) Driver not found. how do I solve this problem ?

    Read the article

  • Should java try blocks be scoped as tightly as possible?

    - by isme
    I've been told that there is some overhead in using the Java try-catch mechanism. So, while it is necessary to put methods that throw checked exception within a try block to handle the possible exception, it is good practice performance-wise to limit the size of the try block to contain only those operations that could throw exceptions. I'm not so sure that this is a sensible conclusion. Consider the two implementations below of a function that processes a specified text file. Even if it is true that the first one incurs some unnecessary overhead, I find it much easier to follow. It is less clear where exactly the exceptions come from just from looking at statements, but the comments clearly show which statements are responsible. The second one is much longer and complicated than the first. In particular, the nice line-reading idiom of the first has to be mangled to fit the readLine call into a try block. What is the best practice for handling exceptions in a funcion where multiple exceptions could be thrown in its definition? This one contains all the processing code within the try block: void processFile(File f) { try { // construction of FileReader can throw FileNotFoundException BufferedReader in = new BufferedReader(new FileReader(f)); // call of readLine can throw IOException String line; while ((line = in.readLine()) != null) { process(line); } } catch (FileNotFoundException ex) { handle(ex); } catch (IOException ex) { handle(ex); } } This one contains only the methods that throw exceptions within try blocks: void processFile(File f) { FileReader reader; try { reader = new FileReader(f); } catch (FileNotFoundException ex) { handle(ex); return; } BufferedReader in = new BufferedReader(reader); String line; while (true) { try { line = in.readLine(); } catch (IOException ex) { handle(ex); break; } if (line == null) { break; } process(line); } }

    Read the article

  • Trouble accessing fields of a serialized object in Java

    - by typoknig
    I have instantized a class that implements Serializable and I am trying to stream that object like this: try{ Socket socket = new Socket("localhost", 8000); ObjectOutputStream toServer = new ObjectOutputStream(socket.getOutputStream()); toServer.writeObject(myObject); } catch (IOException ex) { System.err.println(ex); } All good so far right? Then I am trying to read the fields of that object like this: //This is an inner class class HandleClient implements Runnable{ private ObjectInputStream fromClient; private Socket socket; // This socket was established earlier try { fromClient = new ObjectInputStream(socket.getInputStream()); GetField inputObjectFields = fromClient.readFields(); double myFristVariable = inputObjectFields.get("myFirstVariable", 0); int mySecondVariable = inputObjectFields.get("mySecondVariable", 0); //do stuff } catch (IOException ex) { System.err.println(ex); } catch (ClassNotFoundException ex) { System.err.println(ex); } finally { try { fromClient.close(); } catch (Exception ex) { ex.printStackTrace(); } } } But I always get the error: java.io.NotActiveException: not in call to readObject This is my first time streaming objects instead of primitive data types, what am I doing wrong? BONUS When I do get this working correctly, is the ENTIRE CLASS passed with the serialized object (i.e. will I have access to the methods of the object's class)? My reading suggests that the entire class is passed with the object, but I have been unable to use the objects methods thus far. How exactly do I call on the object's methods? In addition to my code above I also experimented with the readObject method, but I was probably using it wrong too because I couldn't get it to work. Please enlighten me.

    Read the article

  • Preserving original StackTrace/LineNumbers in .NET Exceptions

    - by Sam
    Understanding the difference between throw ex and throw, why is the original StackTrace preserved in this example: static void Main(string[] args) { try { LongFaultyMethod(); } catch (System.Exception ex) { Console.WriteLine(ex.StackTrace); } } static void LongFaultyMethod() { try { int x = 20; SomethingThatThrowsException(x); } catch (Exception) { throw; } } static void SomethingThatThrowsException(int x) { int y = x / (x - x); } But not in this one: static void Main(string[] args) { try { LongFaultyMethod(); } catch (System.Exception ex) { Console.WriteLine(ex.StackTrace); } } static void LongFaultyMethod() { try { int x = 20; int y = x / (x - 20); } catch (Exception) { throw; } } The second scenario is producing the same output as throw ex would? In both cases, one expects to see the line number where y is initialized.

    Read the article

  • How are exceptions allocated on the stack caught beyond their scope?

    - by John Doe
    In the following code, the stack-based variable 'ex' is thrown and caught in a function beyond the scope in which ex was declared. This seems a bit strange to me, since (AFAIK) stack-based variables cannot be used outside the scope in which they were declared (the stack is unwound). void f() { SomeKindOfException ex(...); throw ex; } void g() { try { f(); } catch (SomeKindOfException& ex) { //Handling code... } } I've added a print statement to SomeKindOfException's destructor and it shows that ex is destructed once it goes out of scope in f() but then it's caught in g() and destructed again once it goes out of scope there as well. Any help?

    Read the article

  • GetdataBy date doesn't work Why?

    - by vp789
    I am trying to pull the data by date in vb.net. It is not throwing the error nor giving any result. Whereas It shows the results in table adapter configuration wizard when I try through query builder. I am using date time picker in the form. But I have formatted the date in the database as date.I am puzzled. Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click Try Dim dt As Date = CDate(tspTextDate.Text) Me.Bank_transactionsTableAdapter.GetDataByDate(dt) 'Catch ex As Exception Catch ex As FormatException MessageBox.Show("date is wrong", "Entry Error") Catch ex As SqlException MessageBox.Show("SQL Server error#" & ex.Number _ & ":" & ex.Message, ex.GetType.ToString) End Try End Sub rows of data BT102 4/5/2010 BKS 200.00 1200.00 1400.00 BT103 4/5/2010 BKS 200.00 1400.00 1600.00 BT105 4/6/2010 BKS 200.00 1800.00 1800.00

    Read the article

  • installing ubuntu ,properly

    - by gcc
    While / after install ubuntu , to get proper&full ubuntu what will we consider ? In other words, What should we do or what should we not do ? ex : just after the installation complete , you should call update-manager because ubuntu is not fully ready to work other program namely wine. So many people does not know and they think everything is completed when ubuntu-cd finish its job ex : you must look your computer , are there any driver-confliction ex : while installing ubuntu, if you have other system, you shouldont reside both system in same harddisk partion. Ex: windows and ubuntu system is in "c" Feel free , when you suggest something

    Read the article

  • Threads are facing deadlock in socket program [migrated]

    - by ankur.trapasiya
    I am developing one program in which a user can download a number of files. Now first I am sending the list of files to the user. So from the list user selects one file at a time and provides path where to store that file. In turn it also gives the server the path of file where does it exist. I am following this approach because I want to give stream like experience without file size limitation. Here is my code.. 1) This is server which gets started each time I start my application public class FileServer extends Thread { private ServerSocket socket = null; public FileServer() { try { socket = new ServerSocket(Utils.tcp_port); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void run() { try { System.out.println("request received"); new FileThread(socket.accept()).start(); } catch (IOException ex) { ex.printStackTrace(); } } } 2) This thread runs for each client separately and sends the requested file to the user 8kb data at a time. public class FileThread extends Thread { private Socket socket; private String filePath; public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public FileThread(Socket socket) { this.socket = socket; System.out.println("server thread" + this.socket.isConnected()); //this.filePath = filePath; } @Override public void run() { // TODO Auto-generated method stub try { ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); try { //************NOTE filePath=(String) ois.readObject(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } File f = new File(this.filePath); byte[] buf = new byte[8192]; InputStream is = new FileInputStream(f); BufferedInputStream bis = new BufferedInputStream(is); ObjectOutputStream oos = new ObjectOutputStream( socket.getOutputStream()); int c = 0; while ((c = bis.read(buf, 0, buf.length)) > 0) { oos.write(buf, 0, c); oos.flush(); // buf=new byte[8192]; } oos.close(); //socket.shutdownOutput(); // client.shutdownOutput(); System.out.println("stop"); // client.shutdownOutput(); ois.close(); // Thread.sleep(500); is.close(); bis.close(); socket.close(); } catch (IOException ex) { ex.printStackTrace(); } } } NOTE: here filePath represents the path of the file where it exists on the server. The client who is connecting to the server provides this path. I am managing this through sockets and I am successfully receiving this path. 3) FileReceiverThread is responsible for receiving the data from the server and constructing file from this buffer data. public class FileReceiveThread extends Thread { private String fileStorePath; private String sourceFile; private Socket socket = null; public FileReceiveThread(String ip, int port, String fileStorePath, String sourceFile) { this.fileStorePath = fileStorePath; this.sourceFile = sourceFile; try { socket = new Socket(ip, port); System.out.println("receive file thread " + socket.isConnected()); } catch (IOException ex) { ex.printStackTrace(); } } @Override public void run() { try { ObjectOutputStream oos = new ObjectOutputStream( socket.getOutputStream()); oos.writeObject(sourceFile); oos.flush(); // oos.close(); File f = new File(fileStorePath); OutputStream os = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(os); byte[] buf = new byte[8192]; int c = 0; //************ NOTE ObjectInputStream ois = new ObjectInputStream( socket.getInputStream()); while ((c = ois.read(buf, 0, buf.length)) > 0) { // ois.read(buf); bos.write(buf, 0, c); bos.flush(); // buf = new byte[8192]; } ois.close(); oos.close(); // os.close(); bos.close(); socket.close(); //Thread.sleep(500); } catch (IOException ex) { ex.printStackTrace(); } } } NOTE : Now the problem that I am facing is at the first time when the file is requested the outcome of the program is same as my expectation. I am able to transmit any size of file at first time. Now when the second file is requested (e.g. I have sent file a,b,c,d to the user and user has received file a successfully and now he is requesting file b) the program faces deadlock at this situation. It is waiting for socket's input stream. I put breakpoint and tried to debug it but it is not going in FileThread's run method second time. I could not find out the mistake here. Basically I am making a LAN Messenger which works on LAN. I am using SWT as UI framework.

    Read the article

  • Problems installing LYNC on non-domain controler

    - by Trikks
    I have two servers in this set up. AD and EX, the domain is called mydomain.net The AD is a Windows 2008 Server (32 bit) with Active Directory installed AD only has it's own ip in the DNS-servers list AD.mydomain.net does resolve correctly in the dns EX is a Windows 2008 R2 that is connected to the mydomain.net-domain EX only DNS server is the ip of the ad.mydomain.net There are no firewalls running between the two servers When trying to install Lync 2010 on the EX server I get the following error "Not available :Failure occurred attempting to check the schema state.Please ensure Active Directory is reachable." I can control the AD from EX, also login to it and do successful checks like netdom query /domain:mydomain.net fsmo ...that resolves correctly I suspect there is something fundamentally wrong with my setup, maybe Lync need a 2k8 R2 ad?

    Read the article

  • Feed Reader Fix

    - by Geertjan
    In the FeedReader sample (available in the New Projects window), there's this piece of code: private static Feed getFeed(Node node) { InstanceCookie ck = node.getLookup().lookup(InstanceCookie.class); if (ck == null) { throw new IllegalStateException("Bogus file in feeds folder: " + node.getLookup().lookup(FileObject.class)); } try { return (Feed) ck.instanceCreate(); } catch (ClassNotFoundException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } return null; } Since 7.1, for some reason, the above doesn't work. What does work, and is simpler, is this, instead of the above: private static Feed getFeed(Node node) { Feed f = FileUtil.getConfigObject("RssFeeds/sample.instance", Feed.class); if (f == null) { throw new IllegalStateException("Bogus file in feeds folder: " + node.getLookup().lookup(FileObject.class)); } return f; } So, the code needs to be fixed in the sample.

    Read the article

  • How do I put different textures on different walls? LWJGL

    - by lehermj
    So far I have it so you are running around in a box, but all of the walls are the same texture! I've loaded up other textures for the walls (I want the walls a different texture than the floor) but it seems as if its being ignored... Here's my code: int floorTexture = glGenTextures(); { InputStream in = null; try { in = new FileInputStream("floor.png"); PNGDecoder decoder = new PNGDecoder(in); ByteBuffer buffer = BufferUtils.createByteBuffer(4 * decoder.getWidth() * decoder.getHeight()); decoder.decode(buffer, decoder.getWidth() * 4, Format.RGBA); buffer.flip(); glBindTexture(GL_TEXTURE_2D, floorTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, decoder.getWidth(), decoder.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); glBindTexture(GL_TEXTURE_2D, floorTexture); } catch (FileNotFoundException ex) { System.err.println("Failed to find the texture files."); ex.printStackTrace(); Display.destroy(); System.exit(1); } catch (IOException ex) { System.err.println("Failed to load the texture files."); ex.printStackTrace(); Display.destroy(); System.exit(1); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } int wallTexture = glGenTextures(); { InputStream in = null; try { in = new FileInputStream("walls.png"); PNGDecoder decoder = new PNGDecoder(in); ByteBuffer buffer = BufferUtils.createByteBuffer(4 * decoder.getWidth() * decoder.getHeight()); decoder.decode(buffer, decoder.getWidth() * 4, Format.RGBA); buffer.flip(); glBindTexture(GL_TEXTURE_2D, wallTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, decoder.getWidth(), decoder.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); glBindTexture(GL_TEXTURE_2D, wallTexture); } catch (FileNotFoundException ex) { System.err.println("Failed to find the texture files."); ex.printStackTrace(); Display.destroy(); System.exit(1); } catch (IOException ex) { System.err.println("Failed to load the texture files."); ex.printStackTrace(); Display.destroy(); System.exit(1); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } int ceilingDisplayList = glGenLists(1); glNewList(ceilingDisplayList, GL_COMPILE); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(-gridSize, ceilingHeight, -gridSize); glTexCoord2f(gridSize * 10 * tileSize, 0); glVertex3f(gridSize, ceilingHeight, -gridSize); glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize); glVertex3f(gridSize, ceilingHeight, gridSize); glTexCoord2f(0, gridSize * 10 * tileSize); glVertex3f(-gridSize, ceilingHeight, gridSize); glEnd(); glEndList(); int wallDisplayList = glGenLists(1); glNewList(wallDisplayList, GL_COMPILE); glBegin(GL_QUADS); // North wall glTexCoord2f(0, 0); glVertex3f(-gridSize, floorHeight, -gridSize); glTexCoord2f(0, gridSize * 10 * tileSize); glVertex3f(gridSize, floorHeight, -gridSize); glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize); glVertex3f(gridSize, ceilingHeight, -gridSize); glTexCoord2f(gridSize * 10 * tileSize, 0); glVertex3f(-gridSize, ceilingHeight, -gridSize); // West wall glTexCoord2f(0, 0); glVertex3f(-gridSize, floorHeight, -gridSize); glTexCoord2f(gridSize * 10 * tileSize, 0); glVertex3f(-gridSize, ceilingHeight, -gridSize); glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize); glVertex3f(-gridSize, ceilingHeight, +gridSize); glTexCoord2f(0, gridSize * 10 * tileSize); glVertex3f(-gridSize, floorHeight, +gridSize); // East wall glTexCoord2f(0, 0); glVertex3f(+gridSize, floorHeight, -gridSize); glTexCoord2f(gridSize * 10 * tileSize, 0); glVertex3f(+gridSize, floorHeight, +gridSize); glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize); glVertex3f(+gridSize, ceilingHeight, +gridSize); glTexCoord2f(0, gridSize * 10 * tileSize); glVertex3f(+gridSize, ceilingHeight, -gridSize); // South wall glTexCoord2f(0, 0); glVertex3f(-gridSize, floorHeight, +gridSize); glTexCoord2f(gridSize * 10 * tileSize, 0); glVertex3f(-gridSize, ceilingHeight, +gridSize); glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize); glVertex3f(+gridSize, ceilingHeight, +gridSize); glTexCoord2f(0, gridSize * 10 * tileSize); glVertex3f(+gridSize, floorHeight, +gridSize); glEnd(); glEndList(); int floorDisplayList = glGenLists(1); glNewList(floorDisplayList, GL_COMPILE); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(-gridSize, floorHeight, -gridSize); glTexCoord2f(0, gridSize * 10 * tileSize); glVertex3f(-gridSize, floorHeight, gridSize); glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize); glVertex3f(gridSize, floorHeight, gridSize); glTexCoord2f(gridSize * 10 * tileSize, 0); glVertex3f(gridSize, floorHeight, -gridSize); glEnd(); glEndList();

    Read the article

  • Configurable Values in Enum

    - by Omer Akhter
    I often use this design in my code to maintain configurable values. Consider this code: public enum Options { REGEX_STRING("Some Regex"), REGEX_PATTERN(Pattern.compile(REGEX_STRING.getString()), false), THREAD_COUNT(2), OPTIONS_PATH("options.config", false), DEBUG(true), ALWAYS_SAVE_OPTIONS(true), THREAD_WAIT_MILLIS(1000); Object value; boolean saveValue = true; private Options(Object value) { this.value = value; } private Options(Object value, boolean saveValue) { this.value = value; this.saveValue = saveValue; } public void setValue(Object value) { this.value = value; } public Object getValue() { return value; } public String getString() { return value.toString(); } public boolean getBoolean() { Boolean booleanValue = (value instanceof Boolean) ? (Boolean) value : null; if (value == null) { try { booleanValue = Boolean.valueOf(value.toString()); } catch (Throwable t) { } } // We want a NullPointerException here return booleanValue.booleanValue(); } public int getInteger() { Integer integerValue = (value instanceof Number) ? ((Number) value).intValue() : null; if (integerValue == null) { try { integerValue = Integer.valueOf(value.toString()); } catch (Throwable t) { } } return integerValue.intValue(); } public float getFloat() { Float floatValue = (value instanceof Number) ? ((Number) value).floatValue() : null; if (floatValue == null) { try { floatValue = Float.valueOf(value.toString()); } catch (Throwable t) { } } return floatValue.floatValue(); } public static void saveToFile(String path) throws IOException { FileWriter fw = new FileWriter(path); Properties properties = new Properties(); for (Options option : Options.values()) { if (option.saveValue) { properties.setProperty(option.name(), option.getString()); } } if (DEBUG.getBoolean()) { properties.list(System.out); } properties.store(fw, null); } public static void loadFromFile(String path) throws IOException { FileReader fr = new FileReader(path); Properties properties = new Properties(); properties.load(fr); if (DEBUG.getBoolean()) { properties.list(System.out); } Object value = null; for (Options option : Options.values()) { if (option.saveValue) { Class<?> clazz = option.value.getClass(); try { if (String.class.equals(clazz)) { value = properties.getProperty(option.name()); } else { value = clazz.getConstructor(String.class).newInstance(properties.getProperty(option.name())); } } catch (NoSuchMethodException ex) { Debug.log(ex); } catch (InstantiationException ex) { Debug.log(ex); } catch (IllegalAccessException ex) { Debug.log(ex); } catch (IllegalArgumentException ex) { Debug.log(ex); } catch (InvocationTargetException ex) { Debug.log(ex); } if (value != null) { option.setValue(value); } } } } } This way, I can save and retrieve values from files easily. The problem is that I don't want to repeat this code everywhere. Like as we know, enums can't be extended; so wherever I use this, I have to put all these methods there. I want only to declare the values and that if they should be persisted. No method definitions each time; any ideas?

    Read the article

  • Java exception handling in non sequential tasks (pattern/good practice)

    - by Hernán Eche
    There are some task that should't be done in parallel, (for example opening a file, reading, writing, and closing, there is an order on that...) But... Some task are more like a shoping list, I mean they could have a desirable order but it's not a must..example in communication or loading independient drivers etc.. For that kind of tasks, I would like to know a java best practice or pattern for manage exceptions.. The java simple way is: getUFO { try { loadSoundDriver(); loadUsbDriver(); loadAlienDetectorDriver(); loadKeyboardDriver(); } catch (loadSoundDriverFailed) { doSomethingA; } catch (loadUsbDriverFailed) { doSomethingB; } catch (loadAlienDetectorDriverFailed) { doSomethingC; } catch (loadKeyboardDriverFailed) { doSomethingD; } } But what about having an exception in one of the actions but wanting to try with the next ones?? I've thought this approach, but don't seem to be a good use for exceptions I don't know if it works, doesn't matter, it's really awful!! getUFO { Exception ex=null; try { try{ loadSoundDriver(); }catch (Exception e) { ex=e; } try{ loadUsbDriver(); }catch (Exception e) { ex=e; } try{ loadAlienDetectorDriver(); }catch (Exception e) { ex=e; } try{ loadKeyboardDriver() }catch (Exception e) { ex=e; } close the file; if(ex!=null) { throw ex; } } catch (loadSoundDriverFailed) { doSomethingA; } catch (loadUsbDriverFailed) { doSomethingB; } catch (loadAlienDetectorDriverFailed) { doSomethingC; } catch (loadKeyboardDriverFailed) { doSomethingD; } } seems not complicated to find a better practice for doing that.. I still didn't thanks for any advice

    Read the article

  • Handling exceptions in Prism 4 modules

    - by marcellscarlett
    I've gone through a number of threads here about this topic with no success. It seems that in the App.xaml.cs of our WPF application, handling DispatcherUnhandledExceptions and AppDomain.CurrentDomain.UnhandledException don't catch everything. In this specific instance we have 7 prism modules. My exception handling code is below (almost identical for UnhandledException): private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { try { var ex = e.Exception.InnerException ?? e.Exception; var logManager = new LogManager(); logManager.Error(ex); if (!EventLog.SourceExists(ex.Source)) EventLog.CreateEventSource(ex.Source, "AppName"); EventLog.WriteEntry(ex.Source, ex.InnerException.ToString()); var emb = new ExceptionMessageBox(ex); emb.ShowDialog(); e.Handled = true; } catch (Exception) { } } The problem seems to be the unhandled exceptions occurring in the modules. They aren't caught by the code above and they cause the application to crash without logging or displaying any sort of message. Does anyone have experience with this?

    Read the article

  • Quartz scheduler is failing to start the cron job

    - by Amit
    Hi I am using Quartz scheduler to trigger a cron which needs to perform a host of activities. My Code for the same is as follow: In the init() method of my InitServlet class, I am defining my TimerServer public class InitServlet extends HttpServlet { public void init(ServletConfig config) throws ServletException { try { System.out.println("Starting the CRON"); //Set the DSO Handler CRON TimerServer task = TimerServer.getInstance(); task.setTask(); } catch (Exception ex) { System.out.println("Failed to start the cron"); ex.printStackTrace(); } } In my TimerServer class I have the following methods public void setTask() { try{ this.setSubscriptionDailyJob(); } catch(SchedulerException ex) { log.error("SchedulerException: "+ex.getMessage(), ex); } private void setSubscriptionDailyJob() throws SchedulerException { log.info("Step 1 "); Scheduler scheduler = schedulerFactory.getScheduler(); log.info("Step 2 "); JobDetail subscriptionJob = new JobDetail("subscription", "subscriptiongroup", SubscriptionDaily.class); log.info("Step 3 "); // Initiate CronTrigger with its name and group name CronTrigger subscriptionCronTrigger = new CronTrigger("subscriptionCronTrigger", "subscriptionTriggerGroup"); try { log.info("Subscription cron: "+Constants.SUBSCRIPTION_CRON); // setup CronExpression CronExpression cexp = new CronExpression(Constants.SUBSCRIPTION_CRON); // Assign the CronExpression to CronTrigger subscriptionCronTrigger.setCronExpression(cexp); } catch (Exception ex) { log.warn("Exception: "+ex.getMessage(), ex); } scheduler.scheduleJob(subscriptionJob, subscriptionCronTrigger); scheduler.start(); } In my SubscriptionDaily class : public class SubscriptionDaily implements Job { public void execute(JobExecutionContext arg0) throws JobExecutionException { //Actions to be performed } } Now checking my logs, I am getting Step 1, Step 2 but not further. My code is getting stucked at the TimerServer class itself. Logs wrt to Scheduler are : 17:24:43 INFO [TimerServer]: Step 1 17:24:43 INFO [SimpleThreadPool]: Job execution threads will use class loader of thread: http-8080-1 17:24:43 INFO [SchedulerSignalerImpl]: Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl 17:24:43 INFO [QuartzScheduler]: Quartz Scheduler v.1.6.5 created. 17:24:43 INFO [RAMJobStore]: RAMJobStore initialized. 17:24:43 INFO [StdSchedulerFactory]: Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties' 17:24:43 INFO [StdSchedulerFactory]: Quartz scheduler version: 1.6.5 17:24:43 INFO [TimerServer]: Step 2 I think a log entry is missing : [QuartzScheduler]: Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started. Please help.

    Read the article

  • How to send audio stream via UDP in java?

    - by Nob Venoda
    Hi to all :) I have a problem, i have set MediaLocator to microphone input, and then created Player. I need to grab that sound from the microphone, encode it to some lower quality stream, and send it as a datagram packet via UDP. Here's the code, i found most of it online and adapted it to my app: public class AudioSender extends Thread { private MediaLocator ml = new MediaLocator("javasound://44100"); private DatagramSocket socket; private boolean transmitting; private Player player; TargetDataLine mic; byte[] buffer; private AudioFormat format; private DatagramSocket datagramSocket(){ try { return new DatagramSocket(); } catch (SocketException ex) { return null; } } private void startMic() { try { format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000.0F, 16, 2, 4, 8000.0F, true); DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); mic = (TargetDataLine) AudioSystem.getLine(info); mic.open(format); mic.start(); buffer = new byte[1024]; } catch (LineUnavailableException ex) { Logger.getLogger(AudioSender.class.getName()).log(Level.SEVERE, null, ex); } } private Player createPlayer() { try { return Manager.createRealizedPlayer(ml); } catch (IOException ex) { return null; } catch (NoPlayerException ex) { return null; } catch (CannotRealizeException ex) { return null; } } private void send() { try { mic.read(buffer, 0, 1024); DatagramPacket packet = new DatagramPacket( buffer, buffer.length, InetAddress.getByName(Util.getRemoteIP()), 91); socket.send(packet); } catch (IOException ex) { Logger.getLogger(AudioSender.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void run() { player = createPlayer(); player.start(); socket = datagramSocket(); transmitting = true; startMic(); while (transmitting) { send(); } } public static void main(String[] args) { AudioSender as = new AudioSender(); as.start(); } } And only thing that happens when I run the receiver class, is me hearing this Player from the sender class. And I cant seem to see the connection between TargetDataLine and Player. Basically, I need to get the sound form player, and somehow convert it to bytes[], therefore I can sent it as datagram. Any ideas? Everything is acceptable, as long as it works :)

    Read the article

  • How to use parallel execution in a shell script?

    - by eSKay
    I have a C shell script that does something like this: #!/bin/csh gcc example.c -o ex gcc combine.c -o combine ex file1 r1 <-- 1 ex file2 r2 <-- 2 ex file3 r3 <-- 3 #... many more like the above combine r1 r2 r3 final \rm r1 r2 r3 Is there some way I can make lines 1, 2 and 3 run in parallel instead of one after the another?

    Read the article

  • How to verify if the private key matches with the certificate..?

    - by surendhar_s
    I have the private key stored as .key file.. -----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQD5YBS6V3APdgqaWAkijIUHRK4KQ6eChSaRWaw9L/4u8o3T1s8J rUFHQhcIo5LPaQ4BrIuzHS8yzZf0m3viCTdZAiDn1ZjC2koquJ53rfDzqYxZFrId 7a4QYUCvM0gqx5nQ+lw1KoY/CDAoZN+sO7IJ4WkMg5XbgTWlSLBeBg0gMwIDAQAB AoGASKDKCKdUlLwtRFxldLF2QPKouYaQr7u1ytlSB5QFtIih89N5Avl5rJY7/SEe rdeL48LsAON8DpDAM9Zg0ykZ+/gsYI/C8b5Ch3QVgU9m50j9q8pVT04EOCYmsFi0 DBnwNBRLDESvm1p6NqKEc7zO9zjABgBvwL+loEVa1JFcp5ECQQD9/sekGTzzvKa5 SSVQOZmbwttPBjD44KRKi6LC7rQahM1PDqmCwPFgMVpRZL6dViBzYyWeWxN08Fuv p+sIwwLrAkEA+1f3VnSgIduzF9McMfZoNIkkZongcDAzjQ8sIHXwwTklkZcCqn69 qTVPmhyEDA/dJeAK3GhalcSqOFRFEC812QJAXStgQCmh2iaRYdYbAdqfJivMFqjG vgRpP48JHUhCeJfOV/mg5H2yDP8Nil3SLhSxwqHT4sq10Gd6umx2IrimEQJAFNA1 ACjKNeOOkhN+SzjfajJNHFyghEnJiw3NlqaNmEKWNNcvdlTmecObYuSnnqQVqRRD cfsGPU661c1MpslyCQJBAPqN0VXRMwfU29a3Ve0TF4Aiu1iq88aIPHsT3GKVURpO XNatMFINBW8ywN5euu8oYaeeKdrVSMW415a5+XEzEBY= -----END RSA PRIVATE KEY----- And i extracted public key from ssl certificate file.. Below is the code i tried to verify if private key matches with ssl certificate or not.. I used the modulus[i.e. private key get modulus==public key get modulus] to check if they are matching.. And this seems to hold only for RSAKEYS.. But i want to check for other keys as well.. Is there any other alternative to do the same..?? private static boolean verifySignature(File serverCertificateFile, File serverCertificateKey) { try { byte[] certificateBytes = FileUtils.readFileToByteArray(serverCertificateFile); //byte[] keyBytes = FileUtils.readFileToByteArray(serverCertificateKey); RandomAccessFile raf = new RandomAccessFile(serverCertificateKey, "r"); byte[] buf = new byte[(int) raf.length()]; raf.readFully(buf); raf.close(); PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(buf); KeyFactory kf; try { kf = KeyFactory.getInstance("RSA"); RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(kspec); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream(certificateBytes); //Generate Certificate in X509 Format X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); RSAPublicKey publicKey = (RSAPublicKey) cert.getPublicKey(); in.close(); return privKey.getModulus() == publicKey.getModulus(); } catch (NoSuchAlgorithmException ex) { logger.log(Level.SEVERE, "Such algorithm is not found", ex); } catch (CertificateException ex) { logger.log(Level.SEVERE, "certificate exception", ex); } catch (InvalidKeySpecException ex) { Logger.getLogger(CertificateConversion.class.getName()).log(Level.SEVERE, null, ex); } } catch (IOException ex) { logger.log(Level.SEVERE, "Signature verification failed.. This could be because the file is in use", ex); } return false; } And the code isn't working either.. throws invalidkeyspec exception

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >