Search Results

Search found 13011 results on 521 pages for 'catch block'.

Page 82/521 | < Previous Page | 78 79 80 81 82 83 84 85 86 87 88 89  | Next Page >

  • Unable to upload large files on FTP using Apache commons-net-3.1

    - by Nitin
    I am trying to upload the one large file ( more than 8 MB) using storeFile(remote, local) method of FTPClient but it results false.It get uploaded with some extra bytes.Following is the code with Output: public class Main { public static void main(String[] args) { FTPClient client = new FTPClient(); FileInputStream fis = null; try { client.connect("208.106.181.143"); client.setFileTransferMode(client.BINARY_FILE_TYPE); client.login("abc", "java"); int reply = client.getReplyCode(); System.out.println("Received Reply from FTP Connection:" + reply); if(FTPReply.isPositiveCompletion(reply)){ System.out.println("Connected Success"); } client.changeWorkingDirectory("/"+"Everbest"+"/"); client.makeDirectory("ETPSupplyChain5.3-EvbstSP3"); client.changeWorkingDirectory("/"+"Everbest"+"/"+"ETPSupplyChain5.3-EvbstSP3"+"/"); FTPFile[] names = client.listFiles(); String filename = "E:\\Nitin\\D-Drive\\Installer.rar"; fis = new FileInputStream(filename); boolean result = client.storeFile("Installer.rar", fis); int replyAfterupload = client.getReplyCode(); System.out.println("Received Reply from FTP Connection replyAfterupload:" + replyAfterupload); System.out.println("result:"+result); for (FTPFile name : names) { System.out.println("Name = " + name); } client.logout(); fis.close(); client.disconnect(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } o/p: Received Reply from FTP Connection:230 Connected Success 32 /Everbest/ETPSupplyChain5.3-EvbstSP3 Received Reply from FTP Connection replyAfterupload:150 result:false

    Read the article

  • Encrypt a hex string in java.

    - by twintwins
    I would like to ask for any suggestions about my problem. I need to encrypt a hexadecimal string. I must not to use the built-in functions of java because it doesn't work in my server. In short, I have to hard code an algorithm or any means of encrypting the message. Anyone who could help me with this? thanks a lot! here is the code. public Encrypt(SecretKey key, String algorithm) { try { ecipher = Cipher.getInstance(algorithm); dcipher = Cipher.getInstance(algorithm); ecipher.init(Cipher.ENCRYPT_MODE, key); dcipher.init(Cipher.DECRYPT_MODE, key); } catch (NoSuchPaddingException e) { System.out.println("EXCEPTION: NoSuchPaddingException"); } catch (NoSuchAlgorithmException e) { System.out.println("EXCEPTION: NoSuchAlgorithmException"); } catch (InvalidKeyException e) { System.out.println("EXCEPTION: InvalidKeyException"); } } public void useSecretKey(String secretString) { try { SecretKey desKey = KeyGenerator.getInstance("DES").generateKey(); SecretKey blowfishKey = KeyGenerator.getInstance("Blowfish").generateKey(); SecretKey desedeKey = KeyGenerator.getInstance("DESede").generateKey(); Encrypt desEncrypter = new Encrypt(desKey, desKey.getAlgorithm()); Encrypt blowfishEncrypter = new Encrypt(blowfishKey, blowfishKey.getAlgorithm()); Encrypt desedeEncrypter = new Encrypt(desedeKey, desedeKey.getAlgorithm()); desEncrypted = desEncrypter.encrypt(secretString); blowfishEncrypted = blowfishEncrypter.encrypt(secretString); desedeEncrypted = desedeEncrypter.encrypt(secretString); } catch (NoSuchAlgorithmException e) {} } those are the methods i used. no problem if it is run as an application but then when i put it to my server which is the glassfish server an exception occured and it says no such algorithm.

    Read the article

  • Javascript hide/show classes with checkbox

    - by Christina
    I am just learning javascript, so please bear with me! I want to be able to use checkboxes to choose to hide/show div classes (to basically filter the amount of info being shown). It is done in this... but I'm try to figure out something much simpler (since I don't need to dynamically generate the checkbox options.) I came across this example: The Javascript: function showMe (it, box) { var vis = (box.checked) ? "block" : "none"; document.getElementById(it).style.display = vis; } The HTML <form> <input type="checkbox" checked="checked" value="value1" onclick="showMe('div1', this)" />value1 <input type="checkbox" checked="checked" value="value2" onclick="showMe('div2', this)" />value2 <input type="checkbox" checked="checked" value="value3" onclick="showMe('div3', this)" />value3 </form> <div id="div1" style="display:block">Show Div 1</div> <div id="div2" style="display:block">Show Div 2</div> <div id="div3" style="display:block">Show Div 3</div> </body> </html> But it only works for div ids, not classes. Any idea on how I can work this? Thanks in advance if you can help me out!

    Read the article

  • Stopping and Play button for Audio (Android)

    - by James Rattray
    I have this problem, I have some audio I wish to play... And I have two buttons for it, 'Play' and 'Stop'... Problem is, after I press the stop button, and then press the Play button, nothing happens. -The stop button stops the song, but I want the Play button to play the song again (from the start) Here is my code: final MediaPlayer mp = MediaPlayer.create(this, R.raw.megadeth); And then the two public onclicks: (For playing...) button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on click button.setText("Playing!"); try { mp.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mp.start(); // } }); And for stopping the track... final Button button2 = (Button) findViewById(R.id.cancel); button2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mp.stop(); mp.reset(); } }); Can anyone see the problem with this? If so could you please fix it... (For suggest) Thanks alot... James

    Read the article

  • Do I need Response.End() in ASP.Net 2.0

    - by Hamish Grubijan
    Hi, I am just starting with ASP.Net. I copied a ex-co-worker's code (from .Net 1.1 era) and it has a Response.End(); in case of an error. There is also a: catch (Exception ex) { Response.Write(ex.Message); Response.End(); } at the end of Page_Load(object sender, System.EventArgs e) which always appends "Thread was aborted." or something like that at the end. I suspect that this worked differently before, or the error conditions were not tested very well. Anyhow, I was able to stop using Response.End(); in case when I do not like the GET parameters, and use return; instead. It seemed to do the right think in a simple case. Is this Ok in general? There are some problems with the code I copied, but I do not want to do a rewrite; I just want to get it running first and find wrinkles later. The Response.End(); caused a mental block for me, however, so I want to figure it out. I want to keep the catch all clause just in case, at least for now. I could also end the method with: catch (System.Threading.ThreadAbortException) { Response.End(); } catch (Exception ex) { Response.Write(ex.Message); Response.End(); } but that just seems extremely stupid, once you think about all of the exceptions being generated. Please give me a few words of wisdom. Feel free to ask if something is not clear. Thanks! P.S. Ex-coworker was not fired and is a good coder - one more reason to reuse his example.

    Read the article

  • help on ejb stateless datagram and message driven beans

    - by Kemmal
    i have a client thats sending a message to the ejbserver using UDP, i want the server(stateless bean) to echo back this message to the client but i cant seem to do this. or can i implement the same logic by using JMS? please help and enlighten. this is just a test, in the end i want a midp to be sending the message to the ejb using datagrams. here is my code. @Stateless public class SessionFacadeBean implements SessionFacadeRemote { public SessionFacadeBean() { } public static void main(String[] args) { DatagramSocket aSocket = null; byte[] buffer = null; try { while(true) { DatagramPacket request = new DatagramPacket(buffer, buffer.length); aSocket.receive(request); DatagramPacket reply = new DatagramPacket(request.getData(), request.getLength(), request.getAddress(), request.getPort()); aSocket.send(reply); } } catch (SocketException e) { System.out.println("Socket: " + e.getMessage()); } catch (IOException e) { System.out.println("IO: " + e.getMessage()); } finally { if(aSocket != null) aSocket.close(); } } } and the client: public static void main(String[] args) { DatagramSocket aSocket = null; try { aSocket = new DatagramSocket(); byte [] m = "Test message!".getBytes(); InetAddress aHost = InetAddress.getByName("localhost"); int serverPort = 6789; DatagramPacket request = new DatagramPacket(m, m.length, aHost, serverPort); aSocket.send(request); byte[] buffer = new byte[1000]; DatagramPacket reply = new DatagramPacket(buffer, buffer.length); aSocket.receive(reply); System.out.println("Reply: " + new String(reply.getData())); } catch (SocketException e) { System.out.println("Socket: " + e.getMessage()); } catch (IOException e) { System.out.println("IO: " + e.getMessage()); } finally { if(aSocket != null) aSocket.close(); } } please help.

    Read the article

  • How do I get save (no exclamation point) semantics in an ActiveRecord transaction?

    - by James A. Rosen
    I have two models: Person and Address which I'd like to create in a transaction. That is, I want to try to create the Person and, if that succeeds, create the related Address. I would like to use save semantics (return true or false) rather than save! semantics (raise an ActiveRecord::StatementInvalid or not). This doesn't work because the user.save doesn't trigger a rollback on the transaction: class Person def save_with_address(address_options = {}) transaction do self.save address = Address.build(address_options) address.person = self address.save end end end (Changing the self.save call to an if self.save block around the rest doesn't help, because the Person save still succeeds even when the Address one fails.) And this doesn't work because it raises the ActiveRecord::StatementInvalid exception out of the transaction block without triggering an ActiveRecord::Rollback: class Person def save_with_address(address_options = {}) transaction do save! address = Address.build(address_options) address.person = self address.save! end end end The Rails documentation specifically warns against catching the ActiveRecord::StatementInvalid inside the transaction block. I guess my first question is: why isn't this transaction block... transacting on both saves?

    Read the article

  • Dataflow Pipeline holding on to memory

    - by Jesse Carter
    I've created a Dataflow pipeline consisting of 4 blocks (which includes one optional block) which is responsible for receiving a query object from my application across HTTP and retrieving information from a database, doing an optional transform on that data, and then writing the information back in the HTTP response. In some testing I've done I've been pulling down a significant amount of data from the database (570 thousand rows) which are stored in a List object and passed between the different blocks and it seems like even after the final block has been completed the memory isn't being released. Ram usage in Task Manager will spike up to over 2 GB and I can observe several large spikes as the List hits each block. The signatures for my blocks look like this: private TransformBlock<HttpListenerContext, Tuple<HttpListenerContext, QueryObject>> m_ParseHttpRequest; private TransformBlock<Tuple<HttpListenerContext, QueryObject>, Tuple<HttpListenerContext, QueryObject, List<string>>> m_RetrieveDatabaseResults; private TransformBlock<Tuple<HttpListenerContext, QueryObject, List<string>>, Tuple<HttpListenerContext, QueryObject, List<string>>> m_ConvertResults; private ActionBlock<Tuple<HttpListenerContext, QueryObject, List<string>>> m_ReturnHttpResponse; They are linked as follows: m_ParseHttpRequest.LinkTo(m_RetrieveDatabaseResults); m_RetrieveDatabaseResults.LinkTo(m_ConvertResults, tuple => tuple.Item2 is QueryObjectA); m_RetrieveDatabaseResults.LinkTo(m_ReturnHttpResponse, tuple => tuple.Item2 is QueryObjectB); m_ConvertResults.LinkTo(m_ReturnHttpResponse); Is it possible that I can set up the pipeline such that once each block is done with the list they no longer need to hold on to it as well as once the entire pipeline is completed that the memory is released?

    Read the article

  • JavaScript Exception/Error Handling Not Working

    - by Seán Hayes
    This might be a little hard to follow. I've got a function inside an object: f_openFRHandler: function(input) { console.debug('f_openFRHandler'); try{ //throw 'foo'; DragDrop.FileChanged(input); //foxyface.window.close(); } catch(e){ console.error(e); jQuery('#foxyface_open_errors').append('<div>Max local storage limit reached, unable to store new images in your browser. Please remove some images and try again.</div>'); } }, inside the try block it calls: this.FileChanged = function(input) { // FileUploadManager.addFileInput(input); console.debug(input); var files = input.files; for (var i = 0; i < files.length; i++) { var file = files[i]; if (!file.type.match(/image.*/)) continue; var reader = new FileReader(); reader.onload = (function(f, isLast) { return function(e) { if (files.length == 1) { LocalStorageManager.addImage(f.name, e.target.result, false, true); LocalStorageManager.loadCurrentImage(); //foxyface.window.close(); } else { FileUploadManager.addFileData(f, e.target.result); // add multiple files to list if (isLast) setTimeout(function() { LocalStorageManager.loadCurrentImage() },100); } }; })(file, i == files.length - 1); reader.readAsDataURL(file); } return true; LocalStorageManager.addImage calls: this.setItem = function(data){ localStorage.setItem('ImageStore', $.json_encode(data)); } localStorage.setItem throws an error if too much local storage has been used. I want to catch that error in f_openFRHandler (first code sample), but it's being sent to the error console instead of the catch block. I tried the following code in my Firebug console to make sure I'm not crazy and it works as expected despite many levels of function nesting: try{ (function(){ (function(){ throw 'foo' })() })() } catch(e){ console.debug(e) } Any ideas?

    Read the article

  • Does Android AsyncTaskQueue or similar exist?

    - by Ben L.
    I read somewhere (and have observed) that starting threads is slow. I always assumed that AsyncTask created and reused a single thread because it required being started inside the UI thread. The following (anonymized) code is called from a ListAdapter's getView method to load images asynchronously. It works well until the user moves the list quickly, and then it becomes "janky". final File imageFile = new File(getCacheDir().getPath() + "/img/" + p.image); image.setVisibility(View.GONE); view.findViewById(R.id.imageLoading).setVisibility(View.VISIBLE); (new AsyncTask<Void, Void, Bitmap>() { @Override protected Bitmap doInBackground(Void... params) { try { Bitmap image; if (!imageFile.exists() || imageFile.length() == 0) { image = BitmapFactory.decodeStream(new URL( "http://example.com/images/" + p.image).openStream()); image.compress(Bitmap.CompressFormat.JPEG, 85, new FileOutputStream(imageFile)); image.recycle(); } image = BitmapFactory.decodeFile(imageFile.getPath(), bitmapOptions); return image; } catch (MalformedURLException ex) { // TODO Auto-generated catch block ex.printStackTrace(); return null; } catch (IOException ex) { // TODO Auto-generated catch block ex.printStackTrace(); return null; } } @Override protected void onPostExecute(Bitmap image) { if (view.getTag() != p) // The view was recycled. return; view.findViewById(R.id.imageLoading).setVisibility( View.GONE); view.findViewById(R.id.image) .setVisibility(View.VISIBLE); ((ImageView) view.findViewById(R.id.image)) .setImageBitmap(image); } }).execute(); I'm thinking that a queue-based method would work better, but I'm wondering if there is one or if I should attempt to create my own implementation.

    Read the article

  • how to restart a Thread?

    - by wizztjh
    It is a RMI Server object , so many sethumanActivity() might be run , how do i make sure the previous changeToFalse thread will be stop or halt before the new changeToFalse run? t. interrupt ? Basically when sethumanActivity() is invoke , the humanActivity will be set to true , but a thread will be run to set it back to false. But I am thinking for how to disable or kill the thread when another sethumanActivity() invoked? public class VitaminDEngine implements VitaminD { public boolean humanActivity = false; changeToFalse cf = new changeToFalse(); Thread t = new Thread(cf); private class changeToFalse implements Runnable{ @Override public void run() { try { Thread.sleep(4000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } humanActivity = false; } } @Override public void sethumanActivity() throws RemoteException { // TODO Auto-generated method stub humanActivity = true; t.start(); } public boolean gethumanActivity() throws RemoteException { // TODO Auto-generated method stub return humanActivity; } } Edited after the help of SOer package smartOfficeJava; import java.rmi.RemoteException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class VitaminDEngine implements VitaminD { public volatile boolean humanActivity = false; changeToFalse cf = new changeToFalse(); ExecutorService service = Executors.newSingleThreadExecutor(); private class changeToFalse implements Runnable{ @Override public void run() { try { Thread.sleep(4000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } humanActivity = false; } } @Override public synchronized void sethumanActivity() throws RemoteException { humanActivity = true; service.submit(cf); } public synchronized boolean gethumanActivity() throws RemoteException { return humanActivity; } }

    Read the article

  • how to use cookies in HttpsURLConnection in android.

    - by sajjoo
    hello guys, actually i am new in Android and now i have to add the cookies in my project. i am using HttpsUrlConnection. here is how i am making request and getting response from a webserver and now i have to add cookies aswell. URL url = new URL(strUrl); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8"); connection.setRequestProperty("Content-Length", ""+ Integer.toString(request.getBytes().length)); connection.setUseCaches (false); connection.setDoInput(true); connection.setDoOutput(true); // send Request... DataOutputStream wr = new DataOutputStream (connection.getOutputStream()); wr.writeBytes (request); wr.flush (); wr.close (); //Get response... DataInputStream is = new DataInputStream(connection.getInputStream()); String line; StringBuffer response = new StringBuffer(); while((line = is.readLine()) != null) { response.append(line); } is.close(); FileLogger.writeFile("Soap.txt", "RESPONSE: " + methodName + "\n" + response); HashMap<String, String> parameters = null; try { parameters = SoapRequest.responseParser(response.toString(), methodName); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } return parameters; any help will be appreciative, thanks

    Read the article

  • How to convert String format dates to Date format dates?

    - by Jani Bela
    I have a string with dates it looks like: "20120316 20120317 20120318" ... I store this dates in this format, but I would like to make a Date array from these numbers with the format 03/16 03/17 03/18 ... So far: String[] DailyDatasOnce2 = DatesOnce.split(" "); DailyDatasOnce = new String[DailyDatasOnce2.length]; for (int i=0;i< (DailyDatasOnce2.length) ;i++){ DailyDatasOnce[i]=DailyDatasOnce2[i]; } datumok = new Date[DailyDatasOnce.length]; for (int i=0;i< (DailyDatasOnce.length) ;i++){ SimpleDateFormat curFormater = new SimpleDateFormat("yyyyMMdd"); java.util.Date dateObj = null; java.util.Date dateObj2 = null; try { dateObj = curFormater.parse(DailyDatasOnce[i]); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } SimpleDateFormat postFormater = new SimpleDateFormat("MM/dd"); String newDateStr = postFormater.format(dateObj); try { dateObj2 = curFormater.parse(newDateStr); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } datumok[i] = dateObj2; } So first I make a string array with the string dates (DailyDatasOnce), maybe that first for loop is useless but i can skip it. Now I make a Date array and I want to put the dates into it. I format the dates to format I want, then I try to convert them to Date format. Until the String newDateStr it is working, I manage to change the type of the date. But I get syntax error: Type mismatch: Cannot convert from java.util.date to java.sql.data. I suspect the problem but if it is not possible, how can i do this?

    Read the article

  • What is the scope of TRANSACTION in Sql server

    - by Shantanu Gupta
    I was creating a stored procedure and i got stuck in the writing methodology of me and my collegue. I am using SQL Server 2005 I was writing Stored procedure like this BEGIN TRAN BEGIN TRY INSERT INTO Tags.tblTopic (Topic, TopicCode, Description) VALUES(@Topic, @TopicCode, @Description) INSERT INTO Tags.tblSubjectTopic (SubjectId, TopicId) VALUES(@SubjectId, @@IDENTITY) COMMIT TRAN END TRY BEGIN CATCH DECLARE @Error VARCHAR(1000) SET @Error= 'ERROR NO : '+ERROR_NUMBER() + ', LINE NO : '+ ERROR_LINE() + ', ERROR MESSAGE : '+ERROR_MESSAGE() PRINT @Error ROLLBACK TRAN END CATCH And my collegue was writing it like the below one BEGIN TRY BEGIN TRAN INSERT INTO Tags.tblTopic (Topic, TopicCode, Description) VALUES(@Topic, @TopicCode, @Description) INSERT INTO Tags.tblSubjectTopic (SubjectId, TopicId) VALUES(@SubjectId, @@IDENTITY) COMMIT TRAN END TRY BEGIN CATCH DECLARE @Error VARCHAR(1000) SET @Error= 'ERROR NO : '+ERROR_NUMBER() + ', LINE NO : '+ ERROR_LINE() + ', ERROR MESSAGE : '+ERROR_MESSAGE() PRINT @Error ROLLBACK TRAN END CATCH Here the only difference that you will find is the position of writing Begin TRAN. According to me the methodology of my collegue should not work when an exception occurs i.e. Rollback should not get executed because TRAN does'nt have scope. But when i tried to run both the code, both was working in the same way. I am confused to know how does TRANSACTION works. Is it scope free or what ?

    Read the article

  • java.io.StreamCorruptedException: invalid stream header: 7371007E

    - by Alex
    Hello, this is pprobably a simple question . I got a client Server application which communicate using objects. when I send only one object from the client to server all works well. when I attempt to send several objects one after another on the same stream I get StreamCorruptedException. can some one direct me to the cause of this error . Thanks client write method private SecMessage[] send(SecMessage[] msgs) { SecMessage result[]=new SecMessage[msgs.length]; Socket s=null; ObjectOutputStream objOut =null; ObjectInputStream objIn=null; try { s=new Socket("localhost",12345); objOut=new ObjectOutputStream( s.getOutputStream()); for (SecMessage msg : msgs) { objOut.writeObject(msg); } objOut.flush(); objIn=new ObjectInputStream(s.getInputStream()); for (int i=0;i<result.length;i++) result[i]=(SecMessage)objIn.readObject(); } catch(java.io.IOException e) { alert(IO_ERROR_MSG+"\n"+e.getMessage()); } catch (ClassNotFoundException e) { alert(INTERNAL_ERROR+"\n"+e.getMessage()); } finally { try {objIn.close();} catch (IOException e) {} try {objOut.close();} catch (IOException e) {} } return result; } server read method //in is an inputStream Defined in the server SecMessage rcvdMsgObj; rcvdMsgObj=(SecMessage)new ObjectInputStream(in).readObject(); return rcvdMsgObj; and the SecMessage Class is public class SecMessage implements java.io.Serializable { private static final long serialVersionUID = 3940341617988134707L; private String cmd; //... nothing interesting here , just a bunch of fields , getter and setters }

    Read the article

  • How to access method variables from within an anonymous function in JavaScript?

    - by Hussain
    I'm writing a small ajax class for personal use. In the class, I have a "post" method for sending post requests. The post method has a callback parameter. In the onreadystatechange propperty, I need to call the callback method. Something like this: this.requestObject.onreadystatechange = function() { callback(this.responseText); } However, I can't access the callback variable from within the anonomous function. How can I bring the callback variable into the scope of the onreadystatechange anonomous function? edit: Here's the full code so far: function request() { this.initialize = function(errorHandeler) { try { try { this.requestObject = new XDomainRequest(); } catch(e) { try { this.requestObject = new XMLHttpRequest(); } catch (e) { try { this.requestObject = new ActiveXObject("Msxml2.XMLHTTP"); //newer versions of IE5+ } catch (e) { this.requestObject = new ActiveXObject("Microsoft.XMLHTTP"); //older versions of IE5+ } } } } catch(e) { errorHandeler(); } } this.post = function(url,data) { var response;var escapedData = ""; if (typeof data == 'object') { for (i in data) { escapedData += escape(i)+'='+escape(data[i])+'&'; } escapedData = escapedData.substr(0,escapedData.length-1); } else { escapedData = escape(data); } this.requestObject.open('post',url,true); this.requestObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); this.requestObject.setRequestHeader("Content-length", data.length); this.requestObject.setRequestHeader("Connection", "close"); this.requestObject.onreadystatechange = function() { if (this.readyState == 4) { // call callback function } } this.requestObject.send(data); }

    Read the article

  • Problems initializing a final variable in Java

    - by froadie
    I keep running into slight variations of a problem in Java and it's starting to get to me, and I can't really think of a proper way to get around it. I have an object property that is final, but dynamic. That is, I want the value to be constant once assigned, but the value can be different each runtime. So I declare the class level variable at the beginning of the class - say private final FILE_NAME;. Then, in the constructor, I assign it a value - say FILE_NAME = buildFileName(); The problem begins when I have code in the buildFileName() method that throws an exception. So I try something like this in the constructor: try{ FILE_NAME = buildFileName(); } catch(Exception e){ ... System.exit(1); } Now I have an error - "The blank final field FILE_NAME may not have been initialized." This is where I start to get slightly annoyed at Java's strict compiler. I know that this won't be a problem because if it gets to the catch the program will exit... But the compiler doesn't know that and so doesn't allow this code. If I try to add a dummy assignment to the catch, I get - "The final field FILE_NAME may already have been assigned." I clearly can't assign a default value before the try-catch because I can only assign to it once. Any ideas...?

    Read the article

  • The uncatchable exception, pt 2

    - by chaiguy
    Ok I've done some testing and I've reduced the problem to something very simple: i. Create a method in a new class that throws an exception: public class Class1 { public void CallMe() { string blah = null; blah.ToLower(); } } ii. Create a MethodInfo that points to this method somewhere else: Type class1 = typeof( Class1 ); Class1 obj = new Class1(); MethodInfo method = class1.GetMethod( "CallMe" ); iii. Wrap a call to Invoke() in a try/catch block: try { method.Invoke( obj, null ); // exception is not being caught! } catch { } iv. Run the program without the debugger (works fine). v. Now run the program with the debugger. The debugger will halt the program when the exception occurs, even though it's wrapped in a catch handler that tries to ignore it. (Even if you put a breakpoint in the catch block it will halt before it reaches it!) In fact, the exception is happening when you run it without the debugger too. In a simple test project it's getting ignored at some other level, but if your app has any kind of global exception handling, it will get triggered there as well. This is causing me a real headache because it keeps triggering my app's crash-handler, not to mention the pain it is to attempt to debug.

    Read the article

  • Page content layout issues

    - by Prupel
    I'm designing a theme for a blog and I'm having some trouble trying to get a layout working. Here's an image of what I want. This diagram represents the individual posts and not the website itself, so it will be contained in a box of it's own, lets call it .container. Also the purple and green are in another box, let's call it .content. The other elements will be called by their color for now. so here's more or less what the CSS looks like: .container { display:block; margin:0 25px; } .gray, .blue, .content { display:block; width:100%; } .purple { display:inline-block; width:125px; height:100%; text-align:center; } .green { display:inline-block; } That's all there is at the moment. I tried float but that made no effect. What's happening is something like this. Here's a few more things you should know: .container's width is NOT set it is auto .purple and .green don't necessarily need to be the same size as long as .green doesn't go to that side. .purple CAN have a set height .green is where the meat is, that's where the actual post goes, keep that in mind. I don't think tables will help, the problem is inside .content.

    Read the article

  • JAAS + authentification from database

    - by AhmedDrira
    i am traying to performe an authentification from data base using JAAS i v configured the login-config.xml like this <application-policy name="e-procurment_domaine"> <authentication> <login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule" flag="required"> <module-option name = "dsJndiName">BasepfeDS</module-option> <module-option name="securityDomain">java:/jaas/e-procurment_domaine</module-option> <module-option name="principalsQuery">SELECT pass FROM personne WHERE login=?</module-option> <module-option name="rolesQuery">SELECT disc FROM personne WHERE login=?</module-option> </login-module> </authentication> </application-policy> and I've written a test : this one @Test public void testFindALL() { System.out.println("Debut test de la méthode findALL"); // WebAuthentication wa=new WebAuthentication(); // wa.login("zahrat", "zahrat"); securityClient.setSimple("zahrat", "zahrat"); try { securityClient.login(); } catch (LoginException e) { // TODO Auto-generated catch block e.printStackTrace(); } Acheteur acheteur = new Acheteur(); System.out.println("" + acheteurRemote.findAll().size()); // } catch (EJBAccessException ex) { // System.out.println("Erreur attendue de type EJBAccessException: " // + ex.getMessage()); // } catch (Exception ex) { // ex.printStackTrace(); // fail("Exception pendant le test find ALL"); System.out.println("Fin test find ALL");} // } the test is fail i dont know why , but when i change the polycy with the methode of .property file it works .. i am using the annotation on the session BEAN classes @SecurityDomain("e-procurment_domaine") @DeclareRoles({"acheteur","vendeur","physique"}) @RolesAllowed({"acheteur","vendeur","physique"}) and the annotation on the session for the methode @RolesAllowed("physique") @Override public List<Acheteur> findAll() { log.debug("fetching all Acheteur"); return daoGenerique.findWithNamedQuery("Acheteur.findAll"); } i think that the test have an acess to my data base doe's it need mysql DRIVER or a special config on JBOSS?

    Read the article

  • java servlet:response.sendRedirect() not giving illegal state exception if called after commit of re

    - by sahil garg
    after commit of response as here redirect statement should give exception but it is not doing so if this redirect statemnet is in if block.but it does give exception in case it is out of if block.i have shown same statement(with marked stars ) at two places below.can u please tell me reason for it. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub synchronized (noOfRequests) { noOfRequests++; } PrintWriter pw=null; response.setContentType("text/html"); response.setHeader("foo","bar"); //response is commited because of above statement pw=response.getWriter(); pw.print("hello : "+noOfRequests); //if i remove below statement this same statement is present in if block.so statement in if block should also give exception as this one do, but its not doing so.why? ***response.sendRedirect("http://localhost:8625/ServletPrc/login% 20page.html"); if(true) { //same statement as above ***response.sendRedirect("http://localhost:8625/ServletPrc/login%20page.html"); } else{ request.setAttribute("noOfReq", noOfRequests); request.setAttribute("name", new Name().getName()); request.setAttribute("GmailId",this.getServletConfig().getInitParameter("GmailId") ); request.setAttribute("YahooId",this.getServletConfig().getInitParameter("YahooId") ); RequestDispatcher view1=request.getRequestDispatcher("HomePage.jsp"); view1.forward(request, response); } }

    Read the article

  • Latex multicols. Can I group content so it won't split over cols and/or suggest colbreaks?

    - by valadil
    Hi. I'm trying to learn LaTeX. I've been googling this one for a couple days, but I don't speak enough LaTeX to be able to search for it effectively and what documentation I have found is either too simple or goes way over my head (http://www.uoregon.edu/~dspivak/files/multicol.pdf) I have a document using the multicol package. (I'm actually using multicols* so that the first col fills before the second begins instead of trying to balance them, but I don't think that's relevant here.) The columns output nicely, but I want to be able to indicate that some content won't be broken up into different columns. For instance, aaaaaaaa bbbbbbb aaaaaaaa bbbbbbb aaaaaaaa ccccccc bbbbbbbb ccccccc That poor attempt at ascii art columns is what's happening. I'd like to indicate that the b block is a whole unit that shouldn't be broken up into different columns. Since it doesn't fit under the a block, the entirety of the b block should be moved to the second column. Should b be wrapped in something? Is there a block/float/section/box/minipage/paragraph structure I can use? Something specific to multicol? Alternatively is there a way that I can suggest a columnbreak? I'm thinking of something like \- that suggests a hyphenated line break if its convenient, but this would go between blocks. Thanks!

    Read the article

  • How to fix IllegalStateException error when trying to update a listview?

    - by Michael Vetrano
    Hi guys, I am trying to get this code to run, but I get an IllegalStateException when I run this code saying that the content of the listview wasn't notified, yet I have a notification upon updating the data. This is a custom listview adapter. Here is the relevant part of my code: class LoadingThread extends Thread { public void run() { int itemsOriginallyLoaded = 0; synchronized( items ) { itemsOriginallyLoaded = items.size(); } for( int i = itemsOriginallyLoaded ; i < itemsToLoad ; ++i ) { Log.d( LOG_TAG, "Loading item #"+i ); //String item = "FAIL"; //try { String item = "FAIL"; try { item = stockGrabber.getStockString(dataSource.get(i)); } catch (ApiException e) { Log.e(LOG_TAG, "Problem making API request", e); } catch (ParseException e) { Log.e(LOG_TAG, "Problem parsing API request", e); } //} catch (ApiException e) { // Log.e(TAG, "Problem making API request", e); //} catch (ParseException e) { // Log.e(TAG, "Problem parsing API request", e); //} synchronized( items ) { items.add( item ); } itemsLoaded = i+1; uiHandler.post( updateTask ); Log.d( LOG_TAG, "Published item #"+i ); } if( itemsLoaded >= ( dataSource.size() - 1 ) ) allItemsLoaded = true; synchronized( loading ) { loading = Boolean.FALSE; } } } class UIUpdateTask implements Runnable { public void run() { Log.d( LOG_TAG, "Publishing progress" ); notifyDataSetChanged(); } }

    Read the article

  • How to read data from file(.dat) in append mode

    - by govardhan
    We have an application which requires us to read data from a file (.dat) dynamically using deserialization. We are actually getting first object and it throws null pointer exception and "java.io.StreamCorruptedException:invalid type code:AC" when we are accessing other objects using a "for" loop. File file=null; FileOutputStream fos=null; BufferedOutputStream bos=null; ObjectOutputStream oos=null; try{ file=new File("account4.dat"); fos=new FileOutputStream(file,true); bos=new BufferedOutputStream(fos); oos=new ObjectOutputStream(bos); oos.writeObject(m); System.out.println("object serialized"); amlist=new MemberAccountList(); oos.close(); } catch(Exception ex){ ex.printStackTrace(); } Reading objects: try{ MemberAccount m1; file=new File("account4.dat");//add your code here fis=new FileInputStream(file); bis=new BufferedInputStream(fis); ois=new ObjectInputStream(bis); System.out.println(ois.readObject()); **while(ois.readObject()!=null){ m1=(MemberAccount)ois.readObject(); System.out.println(m1.toString()); }/*mList.addElement(m1);** // Here we have the issue throwing null pointer exception Enumeration elist=mList.elements(); while(elist.hasMoreElements()){ obj=elist.nextElement(); System.out.println(obj.toString()); }*/ } catch(ClassNotFoundException e){ } catch(EOFException e){ System.out.println("end"); } catch(Exception ex){ ex.printStackTrace(); }

    Read the article

  • Undefined return value

    - by yynneejj
    what's wrong to my code..where my return value found undefind... var so; var imgid_callback1; const DIV_ID = 'locationsample'; function setup(){ try { so = device.getServiceObject("Service.Location", "ILocation"); } catch (e) { alert('<setup> ' +e); } } function getLocation(imgId) { var updateoptions = new Object(); // Setting PartialUpdates to 'FALSE' ensures that user get atleast // BasicLocationInformation (Longitude, Lattitude, and Altitude.) updateoptions.PartialUpdates = false; var criteria = new Object(); criteria.LocationInformationClass = "BasicLocationInformation"; criteria.Updateoptions = updateoptions; try { var result = so.ILocation.GetLocation(criteria); if(!checkError("ILocation::getLocation",result,DIV_ID,imgId)) { document.getElementById(DIV_ID).innerHTML = showObject(result.ReturnValue); } } catch (e) { alert ("getLocation: " + e); } } function getLocationAsync(imgId) { var updateoptions = new Object(); updateoptions.PartialUpdates = false; var criteria = new Object(); criteria.LocationInformationClass = "BasicLocationInformation"; criteria.Updateoptions = updateoptions; imgid_callback1 = imgId; try { var result = so.ILocation.GetLocation(criteria, callback1); if(!checkError("ILocation::getLocationAsync",result,DIV_ID,imgId)) { showIMG(imgId,""); } } catch (e) { alert ("getLocationAsync: " + e); } } function callback1(transId, eventCode, result){ var latitude = result.ReturnValue.Latitude; //<-----Error: Undefined Value var longitude = result.ReturnValue.Longitude; var req = null; try { req = new XMLHttpRequest(); if (typeof req.overrideMimeType != "undefined") { req.overrideMimeType("text/xml"); } req.onreadystatechange = function() { if (req.readyState == 4) { if (req.status == 200) { } } else { alert("Error"); } } req.open("POST","http://localhost:8080/GPS/location",true); req.setRequestHeader("longitude",+longitude); req.setRequestHeader("latitude",+latitude); req.send(); } catch (ex) { alert(ex); } }

    Read the article

< Previous Page | 78 79 80 81 82 83 84 85 86 87 88 89  | Next Page >