Search Results

Search found 561 results on 23 pages for 'inputstream'.

Page 18/23 | < Previous Page | 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • Creating android app Database with big amount of data

    - by Thomas
    Hi all, The database of my application need to be filled with a lot of data, so during onCreate(), it's not only some create table sql instructions, there is a lot of inserts. The solution I chose is to store all this instructions in a sql file located in res/raw and which is loaded with Resources.openRawResource(id). It works well but I face to encoding issue, I have some accentuated caharacters in the sql file which appears bad in my application. This my code to do this : public String getFileContent(Resources resources, int rawId) throws IOException { InputStream is = resources.openRawResource(rawId); int size = is.available(); // Read the entire asset into a local byte buffer. byte[] buffer = new byte[size]; is.read(buffer); is.close(); // Convert the buffer into a string. return new String(buffer); } public void onCreate(SQLiteDatabase db) { try { // get file content String sqlCode = getFileContent(mCtx.getResources(), R.raw.db_create); // execute code for (String sqlStatements : sqlCode.split(";")) { db.execSQL(sqlStatements); } Log.v("Creating database done."); } catch (IOException e) { // Should never happen! Log.e("Error reading sql file " + e.getMessage(), e); throw new RuntimeException(e); } catch (SQLException e) { Log.e("Error executing sql code " + e.getMessage(), e); throw new RuntimeException(e); } The solution I found to avoid this is to load the sql instructions from a huge static final string instead of a file, and all accentutated characters appears well. But Isn't there a more elegant way to load sql instructions than a big static final String attribute with all sql instructions ? Thanks in advance Thomas

    Read the article

  • Android - BitmapFactory.decodeByteArray - OutOfMemoryError (OOM)

    - by Bob Keathley
    I have read 100s of article about the OOM problem. Most are in regard to large bitmaps. I am doing a mapping application where we download 256x256 weather overlay tiles. Most are totally transparent and very small. I just got a crash on a bitmap stream that was 442 Bytes long while calling BitmapFactory.decodeByteArray(....). The Exception states: java.lang.OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=9415KB, Allocated=5192KB, Bitmap Size=23671KB) The code is: protected Bitmap retrieveImageData() throws IOException { URL url = new URL(imageUrl); InputStream in = null; OutputStream out = null; HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // determine the image size and allocate a buffer int fileSize = connection.getContentLength(); if (fileSize < 0) { return null; } byte[] imageData = new byte[fileSize]; // download the file //Log.d(LOG_TAG, "fetching image " + imageUrl + " (" + fileSize + ")"); BufferedInputStream istream = new BufferedInputStream(connection.getInputStream()); int bytesRead = 0; int offset = 0; while (bytesRead != -1 && offset < fileSize) { bytesRead = istream.read(imageData, offset, fileSize - offset); offset += bytesRead; } // clean up istream.close(); connection.disconnect(); Bitmap bitmap = null; try { bitmap = BitmapFactory.decodeByteArray(imageData, 0, bytesRead); } catch (OutOfMemoryError e) { Log.e("Map", "Tile Loader (241) Out Of Memory Error " + e.getLocalizedMessage()); System.gc(); } return bitmap; } Here is what I see in the debugger: bytesRead = 442 So the Bitmap data is 442 Bytes. Why would it be trying to create a 23671KB Bitmap and running out of memory?

    Read the article

  • Java Out of memory - Out of heap size

    - by user1907849
    I downloaded the sample program , for file transfer between the client and server. When I try running the program with 1 GB file , I get the Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at Client.main(Client.java:31). Edit: Line no 31: byte [] mybytearray = new byte [FILE_SIZE]; public final static int FILE_SIZE = 1097742336; // receive file long startTime = System.nanoTime(); byte [] mybytearray = new byte [FILE_SIZE]; InputStream is = sock.getInputStream(); fos = new FileOutputStream(FILE_TO_RECEIVED); bos = new BufferedOutputStream(fos); bytesRead = is.read(mybytearray,0,mybytearray.length); current = bytesRead; do { bytesRead = is.read(mybytearray, current, (mybytearray.length-current)); if(bytesRead >= 0) current += bytesRead; } while(bytesRead > -1); bos.write(mybytearray, 0 , current); bos.flush(); Is there any fix for this?

    Read the article

  • Android: Having trouble getting html from webpage

    - by Kyle
    Hi, I'm writing an android application that is supposed to get the html from a php page and use the parsed data from thepage. I've searched for this issue on here, and ended up using some code from an example another poster put up. Here is my code so far: HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); try { Log.d("first","first"); HttpResponse response = client.execute(request); String html = ""; Log.d("second","second"); InputStream in = response.getEntity().getContent(); Log.d("third","third"); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); Log.d("fourth","fourth"); StringBuilder str = new StringBuilder(); String line = null; Log.d("fifth","fifth"); while((line = reader.readLine()) != null) { Log.d("request line",line); } in.close(); } catch (ClientProtocolException e) { } catch (IOException e) { // TODO Auto-generated catch block Log.d("error", "error"); } Log.d("end","end"); } Like I said before, the url is a php page. Whenever I run this code, it prints out the first first message, but then prints out the error error message and then finally the end end message. I've tried modifying the headers, but I've had no luck with it. Any help would be greatly appreciated as I don't know what I'm doing wrong. Thanks!

    Read the article

  • Servlet File Upload Memory Consumption

    - by Scott
    Hi, I'm using a servlet to do a multi fileupload (using apache commons fileupload to help). A portion of my code is posted below. My problem is that if I upload several files at once, the memory consumption of the app server jumps rather drastically. This is probably OK if it were only until the file upload is finished, but the app server seems to hang on to the memory and never return it to the OS. I'm worried that when I put this into production I'll end up getting an out of memory exception on the server. Any ideas on why this is happening? I'm thinking the server may have started a session and will give the memory back after it expires, but I'm not 100% positive. if(ServletFileUpload.isMultipartContent(request)) { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while(iter.hasNext()) { FileItemStream license = iter.next(); if(license.getFieldName().equals("upload_button") || license.getName().equals("")) continue; //DataInputStream stream = new DataInputStream(license.openStream()); InputStream stream = license.openStream(); ArrayList<Integer> byteArray = new ArrayList<Integer>(); int tempByte; do { tempByte = stream.read(); byteArray.add(tempByte); }while(tempByte != -1); stream.close(); byteArray.remove(byteArray.size()-1); byte[] bytes = new byte[byteArray.size()]; int i = 0; for(Integer tByte : byteArray) { bytes[i++] = tByte.byteValue(); } Thanks in advanced!!

    Read the article

  • How to make simple dicitonary J2ME

    - by batosai_fk
    Hi, I am beginner in JavaME. I'd like to make simple dicitionary. The source data is placed on "data.txt" file in "res" directory. The structure is like this: #apple=kind of fruit; #spinach=kind of vegetable; The flow is so simple. User enters word that he want to search in a text field, e.g "apple", system take the user input, read the "data.txt", search the matched word in it, take corresponding word, and display it to another textfield/textbox. I've managed to read whole "data.txt" using this code.. private String readDataText() { InputStream is = getClass().getResourceAsStream("data.txt"); try { StringBuffer sb = new StringBuffer(); int chr, i=0; while ((chr = is.read()) != -1) sb.append((char) chr); return sb.toString(); } catch (Exception e) { } return null; } but I still dont know how to split it, find the matched word with the user input and take corresponding word. Hope somebody willing to share his/her knowledge to help me.. Add to batosai_fk's Reputation

    Read the article

  • C struct written in file, open with Java

    - by DaunnC
    For example in C I have structure: typedef struct { int number; double x1; double y1; double x2; double y2; double x3; double y3; } CTRstruct;` Then I write it to file fwrite(&tr, 1, sizeof(tr), fp); (tr - its CTRstruct var, fp - File pointer); Then I need to read it with Java! I really don't know how to read struct from file... I tried to read it with ObjectInputStream(), last idea is to read with RandomAccessFile() but I also don't know how to... (readLong(), readDouble() also doesn't work, it works ofcource but doesn't read correct data). So, any idea how to read C struct from binary file with Java? If it's interesting, my version to read integer (but it's ugly, & I don't know what to do with double): public class MyDataInputStream extends DataInputStream{ public MyDataInputStream(InputStream AIs) { super(AIs); } public int readInt1() throws IOException{ int ch1 = in.read(); int ch2 = in.read(); int ch3 = in.read(); int ch4 = in.read(); if ((ch1 | ch2 | ch3 | ch4) < 0) throw new EOFException(); return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0)); } with double we can deal the same way (like with int or with long (8bytes) & then convert to double with native func).

    Read the article

  • What to set the scalar type to contain a byte []. Entity in MVC2

    - by Brad8118
    I'm trying out the EF 4.0 and using the Model first approach. I'd like to store images into the database and I'm not sure of the best type for the scalar in the entity. I currently have it(the image scalar type) setup as a binary. From what I have been reading the best way to store the image in the db is a byte[]. So I'm assuming that binary is the way to go. If there is a better way I'd switch. In my controller I have: //file from client to store in the db HttpPostedFileBase file = Request.Files[inputTagName]; if (file.ContentLength > 0) { keyToAdd.Image = new byte[file.ContentLength]; file.InputStream.Write(keyToAdd.Image, 0, file.ContentLength); } This builds fine but when I run it I get an exception writing the stream to keyToAdd.Image. The exception is something like: Method does not exist. Any ideas? Note that when using a EF 4.0 model first approach I only have int16, int32, double, string, decimal, binary, byte, DateTime, Double, Single, and SByte as available types. Thanks

    Read the article

  • problems piping in node.js

    - by alvaizq
    We have the following example in node.js var http = require('http'); http.createServer(function(request, response) { var proxy = http.createClient(8083, '127.0.0.1') var proxy_request = proxy.request(request.method, request.url, request.headers); proxy_request.on('response', function (proxy_response) { proxy_response.pipe(response); response.writeHead(proxy_response.statusCode, proxy_response.headers); }); setTimeout(function(){ request.pipe(proxy_request); },3000); }).listen(8081, '127.0.0.1'); The example listen to a request in 127.0.0.1:8081 and sends it to a dummy server (always return 200 OK status code) in 127.0.0.1:8083. The problem is in the pipe among the input stream (readable) and output stream (writable) when we have a async module before (in this case the setTimeOut timing). The pipe doesn't work and nothing is sent to dummy server in 8083 port. Maybe, when we have a async call (in this case the setTimeOut) before the pipe call, the inputstream change to a state "not readable", and after the async call the pipe doesn't send anything. This is just an example...we test it with more async modules from node.js community with the same result (ldapjs, etc)... We try to fix it with: - request.readable =true; //before pipe call - request.pipe(proxy_request, {end : false}); with the same result (the pipe doesn't work). Can anybody help us? Many thanks in advanced and best regards,

    Read the article

  • Need to have JProgress bar to measure progress when copying directories and files

    - by user1815823
    I have the below code to copy directories and files but not sure where to measure the progress. Can someone help as to where can I measure how much has been copied and show it in the JProgress bar public static void copy(File src, File dest) throws IOException{ if(src.isDirectory()){ if(!dest.exists()){ //checking whether destination directory exisits dest.mkdir(); System.out.println("Directory copied from " + src + " to " + dest); } String files[] = src.list(); for (String file : files) { File srcFile = new File(src, file); File destFile = new File(dest, file); copyFolder(srcFile,destFile); } }else{ InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0){ out.write(buffer, 0, length); } in.close(); out.close(); System.out.println("File copied from " + src + " to " + dest); }

    Read the article

  • Downloading Large JSON File to local file using Java

    - by user1279675
    I'm attempting to download a JSON from the following URL - http://api.crunchbase.com/v/1/companies.js - to a local file. I'm using Java 1.7 and the following JSON Libraries - http://www.json.org/java/ - to attempt to make it work. Here's my code: public static void download(String address, String localFileName) { OutputStream out = null; URLConnection conn = null; InputStream in = null; try { URL url = new URL(address); out = new BufferedOutputStream( new FileOutputStream(localFileName)); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; System.out.println(buffer.length); System.out.println(" " + buffer.hashCode()); } System.out.println(localFileName + "\t" + numWritten); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } } } When I run the code everything seems to work until midway through the loop the program seems to stop and not continue reading the JSON Object. Does anyone know why this would stop reading? How could I fix the issue?

    Read the article

  • upload new file first check if this file exist already in database or not then if not exist save that in database

    - by Hala Qaseam
    I'm trying to create sql database that contains Image Id (int) Imagename (varchar(50)) Image (image) and in aspx write in upload button this code: protected void btnUpload_Click(object sender, EventArgs e) { //Condition to check if the file uploaded or not if (fileuploadImage.HasFile) { //getting length of uploaded file int length = fileuploadImage.PostedFile.ContentLength; //create a byte array to store the binary image data byte[] imgbyte = new byte[length]; //store the currently selected file in memeory HttpPostedFile img = fileuploadImage.PostedFile; //set the binary data img.InputStream.Read(imgbyte, 0, length); string imagename = txtImageName.Text; //use the web.config to store the connection string SqlConnection connection = new SqlConnection(strcon); connection.Open(); SqlCommand cmd = new SqlCommand("INSERT INTO Image (ImageName,Image) VALUES (@imagename,@imagedata)", connection); cmd.Parameters.Add("@imagename", SqlDbType.VarChar, 50).Value = imagename; cmd.Parameters.Add("@imagedata", SqlDbType.Image).Value = imgbyte; int count = cmd.ExecuteNonQuery(); connection.Close(); if (count == 1) { BindGridData(); txtImageName.Text = string.Empty; ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true); } } } When I'm uploading a new image I need to first check if this image already exists in database and if it doesn't exist save that in database. Please how I can do that?

    Read the article

  • How to stream authenticated content with MediaPlayer on Android

    - by 102790073222983779908
    I've seen quite a few posts askign this question on SO but there doesn't seem to be a definitive answer (or at least an answer I like!) I've got content protected behind basic auth (username/password) -- I can download it fine using the various HTTP download clases but for the life of me I can't sort out how to tell media player to stream it (and provide the authentication). I saw one post that suggested it wasn't possible since the MediaPlayer is all native code and doesn't things like the Authenticator. There are plenty of examples of how to first download to a cached copy and then play that back but....That sort of sucks (and the files maybe 100's of MB's). I saw at least one proposal to download it in smalish chunks and then start & stop the playback (redirecting to the new file) but that sort of sucks also since there would (I presume) be a stutter (I haven't tried it though) The best idea I have at this point is to start downloading to a cache file and then when it's 'full enough' start up playback while I continue to fill the file.... I hope that this works (but again, haven't tried it). Am I missing something obvious? It's so painful to have all the various pieces almost working and I sort of convinced myself that there had to be a way to natively stream protected content (or have it take a already established & qualified InputStream) but it appears no joy. BTW I'm a Mac/iPhone guy and a newb at Android so I'm still fighting a bit of Java learning.... Excuse me if I'm missing somthing obvious. -john

    Read the article

  • Android Java error handling XML file

    - by Paul
    I'm using SAX and XML reader to read XML weather info from the web and it works fine if the page exists. But if for instance the user inputs an invalid city, zip etc the XML page that gets read from is empty and the app force closes with nullpointerexception. The area that generates the error is here right at open inputstream. Any suggestions?: SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = null; try { sp = spf.newSAXParser(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* Get the XMLReader of the SAXParser we created. */ XMLReader xr = null; try { xr = sp.getXMLReader(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* Create a new ContentHandler and apply it to the XML-Reader*/ WeatherHandler myExampleHandler = new WeatherHandler(); xr.setContentHandler(myExampleHandler); /* Parse the xml-data from our URL. */ try { xr.parse(new InputSource(url.openStream())); parsedWeatherDataSet = myExampleHandler.getParsedData(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } return parsedWeatherDataSet.toString();

    Read the article

  • Hopping/Tumbling Windows Could Introduce Latency.

    This is a pre-article to one I am going to be writing on adjusting an event’s time and duration to satisfy business process requirements but it is one that I think is really useful when understanding the way that Hopping/Tumbling windows work within StreamInsight.  A Tumbling window is just a special shortcut version of  a Hopping window where the width of the window is equal to the size of the hop Here is the simplest and often used definition for a Hopping Window.  You can find them all here public static CepWindowStream<CepWindow<TPayload>> HoppingWindow<TPayload>(     this CepStream<TPayload> source,     TimeSpan windowSize,     TimeSpan hopSize,     WindowInputPolicy inputPolicy,     HoppingWindowOutputPolicy outputPolicy )   And here is the definition for a Tumbling Window public static CepWindowStream<CepWindow<TPayload>> TumblingWindow<TPayload>(     this CepStream<TPayload> source,     TimeSpan windowSize,     WindowInputPolicy inputPolicy,     HoppingWindowOutputPolicy outputPolicy )   These methods allow you to group events into windows of a temporal size.  It is a really useful and simple feature in StreamInsight.  One of the downsides though is that the windows cannot be flushed until an event in a following window occurs.  This means that you will potentially never see some events or see them with a delay.  Let me explain. Remember that a stream is a potentially unbounded sequence of events. Events in StreamInsight are given a StartTime.  It is this StartTime that is used to calculate into which temporal window an event falls.  It is best practice to assign a timestamp from the source system and not one from the system clock on the processing server.  StreamInsight cannot know when a window is over.  It cannot tell whether you have received all events in the window or whether some events have been delayed which means that StreamInsight cannot flush the stream for you.   Imagine you have events with the following Timestamps 12:10:10 PM 12:10:20 PM 12:10:35 PM 12:10:45 PM 11:59:59 PM And imagine that you have defined a 1 minute Tumbling Window over this stream using the following syntax var HoppingStream = from shift in inputStream.TumblingWindow(TimeSpan.FromMinutes(1),HoppingWindowOutputPolicy.ClipToWindowEnd) select new WindowCountPayload { CountInWindow = (Int32)shift.Count() };   The events between 12:10:10 PM and 12:10:45 PM will not be seen until the event at 11:59:59 PM arrives.  This could be a real problem if you need to react to windows promptly This can always be worked around by using a different design pattern but a lot of the examples I see assume there is a constant, very frequent stream of events resulting in windows always being flushed. Further examples of using windowing in StreamInsight can be found here

    Read the article

  • Parsing xml files locally from assets folder using XmlPullParser

    - by Randolphg
    Im trying to parse a local xml file that I place in my assets folder. I've been trying to do this for almost a week now. Here is my test xml file Test1 Test2 Test3 Test4 Test5 I keep getting the same error: W/System.err(22458): org.xmlpull.v1.XmlPullParserException: unexpected type (position:TEXT Code: public void xmlParser() throws XmlPullParserException, IOException, ParserConfigurationException, SAXException { Log.d("tag", "xmlParsing...."); Arithmetic arthm = new Arithmetic(); XmlPullParserFactory xmlPF = XmlPullParserFactory.newInstance(); xmlPF.setValidating(false); XmlPullParser xml = xmlPF.newPullParser(); InputStream raw = getApplication().getAssets().open("menu.xml"); xml.setInput(raw, null); xml.nextTag(); Log.d("tag", "start parsing...."); String elementText = null; String elemName = null; int nofTags = 0; while (xml.getEventType() != XmlPullParser.END_DOCUMENT) { Log.d("tag", "while(xml.next)..."); switch (xml.getEventType()) { case XmlPullParser.START_DOCUMENT: Log.d("tag", "while (xml.getEventType() != XmlPullParser.END_DOCUMENT)"); break; case XmlPullParser.START_TAG: Log.d("tag", " case XmlPullParser.START_TAG"); elementText = xml.getName(); Log.d("tag", "elementText = " + elementText); if (xml.getEventType() != XmlPullParser.END_TAG) { xml.nextTag(); } break; case XmlPullParser.TEXT: Log.d("tag", "case TEXT"); if (elementText.equals("menu") && xml.isWhitespace()) { Log.d("tag", "<" + elementText + ">"); arthm.menu_name = xml.getText(); Log.d("tag", "value " + xml.getText() + " added"); } else if (elementText.equals("item")) { arthm.description = xml.getText(); Log.d("tag", "value " + xml.getText() + " added"); } else if (elementText.equals("SUBCATEGORY NAME")) { arthm.subcategoryDesc.add(xml.getText()); Log.d("tag", "value " + xml.getText() + " added"); } else if (elementText.equals("SUBCATEGORY DESC")) { arthm.subcategoryName.add(xml.getText()); Log.d("tag", "value " + xml.getText() + " added"); } break; case XmlPullParser.END_TAG: Log.d("tag", "case END_TAG"); nofTags += 1; String tags = Integer.toString(nofTags); Log.d("tags", elementText + " number of tags" + tags); if (xml.nextTag() != XmlPullParser.START_TAG) { xml.next(); } break; case XmlPullParser.END_DOCUMENT: Log.d("tag", "case END_DOCUMENT"); break; default: break; } } Log.d("tag", "Success!"); } Thanks in advance.

    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

  • Encrypt images before uploading to Dropbox [migrated]

    - by Cherry
    I want to encrypt a file first before the file will be uploaded to the dropbox. So i have implement the encryption inside the uploading of the codes. However, there is an error after i integrate the codes together. Where did my mistake go wrong? Error at putFileOverwriteRequest and it says The method putFileOverwriteRequest(String, InputStream, long, ProgressListener) in the type DropboxAPI is not applicable for the arguments (String, FileOutputStream, long, new ProgressListener(){}) Another problem is that this FileOutputStream fis = new FileOutputStream(new File("dont know what to put in this field")); i do not know where to put the file so that after i read the file, it will call the path and then upload to the Dropbox. Anyone is kind to help me in this? As time is running out for me and i still cant solve the problem. Thank you in advance. The full code is as below. public class UploadPicture extends AsyncTask<Void, Long, Boolean> { private DropboxAPI<?> mApi; private String mPath; private File mFile; private long mFileLen; private UploadRequest mRequest; private Context mContext; private final ProgressDialog mDialog; private String mErrorMsg; public UploadPicture(Context context, DropboxAPI<?> api, String dropboxPath, File file) { // We set the context this way so we don't accidentally leak activities mContext = context.getApplicationContext(); mFileLen = file.length(); mApi = api; mPath = dropboxPath; mFile = file; mDialog = new ProgressDialog(context); mDialog.setMax(100); mDialog.setMessage("Uploading " + file.getName()); mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mDialog.setProgress(0); mDialog.setButton("Cancel", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { // This will cancel the putFile operation mRequest.abort(); } }); mDialog.show(); } @Override protected Boolean doInBackground(Void... params) { try { KeyGenerator keygen = KeyGenerator.getInstance("DES"); SecretKey key = keygen.generateKey(); //generate key //encrypt file here first byte[] plainData; byte[] encryptedData; Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); //File f = new File(mFile); //read file FileInputStream in = new FileInputStream(mFile); //obtains input bytes from a file plainData = new byte[(int)mFile.length()]; in.read(plainData); //Read bytes of data into an array of bytes encryptedData = cipher.doFinal(plainData); //encrypt data FileOutputStream fis = new FileOutputStream(new File("dont know what to put in this field")); //upload to a path first then call the path so that it can be uploaded up to the dropbox //save encrypted file to dropbox // By creating a request, we get a handle to the putFile operation, // so we can cancel it later if we want to //FileInputStream fis = new FileInputStream(mFile); String path = mPath + mFile.getName(); mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(), new ProgressListener() { @Override public long progressInterval() { // Update the progress bar every half-second or so return 500; } @Override public void onProgress(long bytes, long total) { publishProgress(bytes); } }); if (mRequest != null) { mRequest.upload(); return true; } } catch (DropboxUnlinkedException e) { // This session wasn't authenticated properly or user unlinked mErrorMsg = "This app wasn't authenticated properly."; } catch (DropboxFileSizeException e) { // File size too big to upload via the API mErrorMsg = "This file is too big to upload"; } catch (DropboxPartialFileException e) { // We canceled the operation mErrorMsg = "Upload canceled"; } catch (DropboxServerException e) { // Server-side exception. These are examples of what could happen, // but we don't do anything special with them here. if (e.error == DropboxServerException._401_UNAUTHORIZED) { // Unauthorized, so we should unlink them. You may want to // automatically log the user out in this case. } else if (e.error == DropboxServerException._403_FORBIDDEN) { // Not allowed to access this } else if (e.error == DropboxServerException._404_NOT_FOUND) { // path not found (or if it was the thumbnail, can't be // thumbnailed) } else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) { // user is over quota } else { // Something else } // This gets the Dropbox error, translated into the user's language mErrorMsg = e.body.userError; if (mErrorMsg == null) { mErrorMsg = e.body.error; } } catch (DropboxIOException e) { // Happens all the time, probably want to retry automatically. mErrorMsg = "Network error. Try again."; } catch (DropboxParseException e) { // Probably due to Dropbox server restarting, should retry mErrorMsg = "Dropbox error. Try again."; } catch (DropboxException e) { // Unknown error mErrorMsg = "Unknown error. Try again."; } catch (FileNotFoundException e) { } return false; } @Override protected void onProgressUpdate(Long... progress) { int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5); mDialog.setProgress(percent); } @Override protected void onPostExecute(Boolean result) { mDialog.dismiss(); if (result) { showToast("Image successfully uploaded"); } else { showToast(mErrorMsg); } } private void showToast(String msg) { Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG); error.show(); } }

    Read the article

  • QR Code encoding and decoding using zxing

    - by helixed
    Okay, so I'm going to take the off chance that someone here has used zxing before. I'm developing a Java application, and one of the things it needs to do is encode a byte array of data into a QR Code and then decode it at a later time. Here's an example of what my encoder looks like: byte[] b = {0x48, 0x45, 0x4C, 0x4C, 0x4F}; //convert the byte array into a UTF-8 string String data; try { data = new String(b, "UTF8"); } catch (UnsupportedEncodingException e) { //the program shouldn't be able to get here return; } //get a byte matrix for the data ByteMatrix matrix; com.google.zxing.Writer writer = new QRCodeWriter(); try { matrix = writer.encode(data, com.google.zxing.BarcodeFormat.QR_CODE, width, height); } catch (com.google.zxing.WriterException e) { //exit the method return; } //generate an image from the byte matrix int width = matrix.getWidth(); int height = matrix.getHeight(); byte[][] array = matrix.getArray(); //create buffered image to draw to BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //iterate through the matrix and draw the pixels to the image for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int grayValue = array[y][x] & 0xff; image.setRGB(x, y, (grayValue == 0 ? 0 : 0xFFFFFF)); } } //write the image to the output stream ImageIO.write(image, "png", outputStream); The beginning byte array in this code is just used to test it. The actual byte data will be varied. Here's what my decoder looks like: //get the data from the input stream BufferedImage image = ImageIO.read(inputStream); //convert the image to a binary bitmap source LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); //decode the barcode QRCodeReader reader = new QRCodeReader(); Result result; try { result = reader.decode(bitmap, hints); } catch (ReaderException e) { //the data is improperly formatted throw new MCCDatabaseMismatchException(); } byte[] b = result.getRawBytes(); System.out.println(ByteHelper.convertUnsignedBytesToHexString(result.getText().getBytes("UTF8"))); System.out.println(ByteHelper.convertUnsignedBytesToHexString(b)); convertUnsignedBytesToHexString(byte) is a method which converts an array of bytes in a string of hexadecimal characters. When I try to run these two blocks of code together, this is the output: 48454c4c4f 202b0b78cc00ec11ec11ec11ec11ec11ec11ec Clearly the text is being encoded, but the actual bytes of data are completely off. Any help would be appreciated here. Thanks, helixed

    Read the article

  • Java Process "The pipe has been ended" problem

    - by Amit Kumar
    I am using Java Process API to write a class that receives binary input from the network (say via TCP port A), processes it and writes binary output to the network (say via TCP port B). I am using Windows XP. The code looks like this. There are two functions called run() and receive(): run is called once at the start, while receive is called whenever there is a new input received via the network. Run and receive are called from different threads. The run process starts an exe and receives the input and output stream of the exe. Run also starts a new thread to write output from the exe on to the port B. public void run() { try { Process prc = // some exe is `start`ed using ProcessBuilder OutputStream procStdIn = new BufferedOutputStream(prc.getOutputStream()); InputStream procStdOut = new BufferedInputStream(prc.getInputStream()); Thread t = new Thread(new ProcStdOutputToPort(procStdOut)); t.start(); prc.waitFor(); t.join(); procStdIn.close(); procStdOut.close(); } catch (Exception e) { e.printStackTrace(); printError("Error : " + e.getMessage()); } } The receive forwards the received input from the port A to the exe. public void receive(byte[] b) throws Exception { procStdIn.write(b); } class ProcStdOutputToPort implements Runnable { private BufferedInputStream bis; public ProcStdOutputToPort(BufferedInputStream bis) { this.bis = bis; } public void run() { try { int bytesRead; int bufLen = 1024; byte[] buffer = new byte[bufLen]; while ((bytesRead = bis.read(buffer)) != -1) { // write output to the network } } catch (IOException ex) { Logger.getLogger().log(Level.SEVERE, null, ex); } } } The problem is that I am getting the following stack inside receive() and the prc.waitfor() returns immediately afterwards. The line number shows that the stack is while writing to the exe. The pipe has been ended java.io.IOException: The pipe has been ended at java.io.FileOutputStream.writeBytes(Native Method) at java.io.FileOutputStream.write(FileOutputStream.java:260) at java.io.BufferedOutputStream.write(BufferedOutputStream.java:105) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65) at java.io.BufferedOutputStream.write(BufferedOutputStream.java:109) at java.io.FilterOutputStream.write(FilterOutputStream.java:80) at xxx.receive(xxx.java:86) Any advice about this will be appreciated.

    Read the article

  • Interfacing Android Nexus One with Arduino + BlueSmirf

    - by efgomez
    I'm a bit new to all of this, so bear with me - I'd really appreciate your help. I am trying to link the Android Nexus One with an arduino (Duemilanove) that is connected to a BlueSmirf. I have a program that is simply outputting the string "Hello Bluetooth" to whatever device the BlueSmirf is connected to. Here is the Arduino program: void setup(){ Serial.begin(115200); int i; } void loop(){Serial.print("Hello Bluetooth!"); delay(1000); } One my computer BT terminal I can see the message and connect no problem. The trouble is with my android code. I can connect to the device with android, but when I look at the log it is not displaying "Hello Bluetooth". Here is the debug log: 04-09 16:27:49.022: ERROR/BTArduino(17288): FireFly-2583 connected 04-09 16:27:49.022: ERROR/BTArduino(17288): STARTING TO CONNECT THE SOCKET 04-09 16:27:55.705: ERROR/BTArduino(17288): Received: 16 04-09 16:27:56.702: ERROR/BTArduino(17288): Received: 1 04-09 16:27:56.712: ERROR/BTArduino(17288): Received: 15 04-09 16:27:57.702: ERROR/BTArduino(17288): Received: 1 04-09 16:27:57.702: ERROR/BTArduino(17288): Received: 15 04-09 16:27:58.704: ERROR/BTArduino(17288): Received: 1 04-09 16:27:58.704: ERROR/BTArduino(17288): Received: 15 ect... Here is the code, I'm trying to put only the relative code but if you need more please let me know: private class ConnectThread extends Thread { private final BluetoothSocket mySocket; private final BluetoothDevice myDevice; public ConnectThread(BluetoothDevice device) { myDevice = device; BluetoothSocket tmp = null; try { tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { Log.e(TAG, "CONNECTION IN THREAD DIDNT WORK"); } mySocket = tmp; } public void run() { Log.e(TAG, "STARTING TO CONNECT THE SOCKET"); InputStream inStream = null; boolean run = false; //...More Connection code here... The more relative code is here: byte[] buffer = new byte[1024]; int bytes; // handle Connection try { inStream = mySocket.getInputStream(); while (run) { try { bytes = inStream.read(buffer); Log.e(TAG, "Received: " + bytes); } catch (IOException e3) { Log.e(TAG, "disconnected"); } } I am reading bytes = inStream.read(buffer). I know bytes is an integer, so I tried sending integers over bluetooth because "bytes" was an integer but it still didn't make sense. It almost appears that is sending incorrect baud rate. Could this be true? Any help would be appreciated. Thank you very much.

    Read the article

  • Android Mediaplayer: setDataSource issue for downloaded media file

    - by Erik
    I have an application that will record and play audio files. Some of the audio files are downloaded using simple standard http downloads using httpclient. It worked like a charm for a long time. Now all of a sudden I cannot play the files I download. It fails with this stack. I store the files on the SDCard and I experience the problem both on a handset and a USB connected device. I have checked that the downloaded file is cool on the server, and I can play it without any issues. These are the code snippets I use ( I know that recordingFile is a valid path for the file). // inside the activity class private void playRecording() throws IOException{ File recordingFile = new File(recordingFileName); FileInputStream recordingInputStream = new FileInputStream(recordingFile); audioMediaPlayer.playAudio(recordingInputStream); } Here is the media player code: // inside my media player class which handles the recordings public void playAudio(FileInputStream audioInputStream) throws IOException { mediaPlayer.reset(); mediaPlayer.setDataSource(audioInputStream.getFD()); mediaPlayer.prepare(); mediaPlayer.start(); } Here is the exception: E/MediaPlayerService( 555): offset error E/MediaPlayer( 786): Unable to to create media player W/System.err( 786): java.io.IOException: setDataSourceFD failed.: status=0x80000000 W/System.err( 786): at android.media.MediaPlayer.setDataSource(Native Method) W/System.err( 786): at android.media.MediaPlayer.setDataSource(MediaPlayer.java:632) W/System.err( 786): at net.xxx.xxx.AudioMediaPlayer.playAudio(AudioMediaPlayer.java:69) W/System.err( 786): at net.xxx.xxx.Downloads.playRecording(Downloads.java:299) W/System.err( 786): at net.xxx.xxx.Downloads.access$0(Downloads.java:294) W/System.err( 786): at net.xxx.xxx.Downloads$1.onClick(Downloads.java:135) I have tried seeking some answer of the offset error, but not really clear what this issue might be. PS I download the file with this code: public FileOutputStream executeHttpGet(FileOutputStream fileOutputStream) throws ClientProtocolException, IOException{ try { // Execute HTTP Post Request httpResponse = httpClient.execute(httpPost, localContext); int status = httpResponse.getStatusLine().getStatusCode(); // we assume that the response body contains the error message if (status != HttpStatus.SC_OK) { ByteArrayOutputStream ostream = new ByteArrayOutputStream(); httpResponse.getEntity().writeTo(ostream); fileOutputStream = null; } else { InputStream content = httpResponse.getEntity().getContent(); byte[] buffer = new byte[1024]; int len = 0; while ( (len = content.read(buffer)) > 0 ) { fileOutputStream.write(buffer,0, len); } fileOutputStream.close(); content.close(); // this will also close the connection } } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); fileOutputStream = null; } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); fileOutputStream = null; } return fileOutputStream; }

    Read the article

  • Metro UsernameToken Policy

    - by Rodney
    I created a web services client prototype using api's available in weblogic 10.3. I've been told I need to use Metro 2.0 instead (it's already being used for other projects). The problem I have encounter is that the WSDL does not include any Security Policy information but a UsernameToken is required for each method call. In weblogic I was able to write my own policy xml file and instantiate my service with it (see below), however I can not seem to figure out how to do the same using Metro. Policy.xml <?xml version="1.0"?> <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200512"> <sp:SupportingTokens> <wsp:Policy> <sp:UsernameToken sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200512/IncludeToken/AlwaysToRecipient"> <wsp:Policy> <sp:WssUsernameToken10/> <sp:HashPassword/> </wsp:Policy> </sp:UsernameToken> </wsp:Policy> </sp:SupportingTokens> </wsp:Policy> Client.java (Weblogic) ClientPolicyFeature cpf = new ClientPolicyFeature(); InputStream asStream = WebServiceSoapClient.class.getResourceAsStream("Policy.xml"); cpf.setEffectivePolicy(new InputStreamPolicySource(asStream)); try { webService = new WebService(new URL("http://192.168.1.10/WebService/WebService.asmx?wsdl"), new QName("http://testme.com", "WebService")); } catch ( MalformedURLException e ) { e.printStackTrace(); } WebServiceSoap client = webService.getWebServiceSoap(new WebServiceFeature[] {cpf}); List<CredentialProvider> credProviders = new ArrayList<CredentialProvider>(); String username = "user"; String password = "pass"; CredentialProvider cp = new ClientUNTCredentialProvider(username.getBytes(), password.getBytes()); credProviders.add(cp); Map<String, Object> rc = ((BindingProvider) client).getRequestContext(); rc.put(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credProviders); ... I am able to generate my Proxy classes using Metro however I can not figure out how to configure it to send the UsernameToken. I have attempted several different examples from the web which have not worked. Any help would be appreciated.

    Read the article

  • How to use GWT when downloading Files with a Servlet?

    - by molleman
    Hello Guys I am creating a simple project that will allow me to upload and download files using gwt. i am having trouble with the downloading of files that are on my server. For the file upload i used http://code.google.com/p/gwtupload/ and followed the instructions there. My file is stored on the server outside of the website container(on the hard drive), Now when it comes to the downloading of a file, i want a user to press a download button and whatever item is currently selected will download. i dont really know how this will be done i know i need a download servlet public class DownloadAttachmentServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub super.doGet(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String fileName = (String) req.getSession().getAttribute("fileName"); YFUser user = (YFUser) req.getSession().getAttribute(TestServiceImpl.SESSION_USER); if (user == null) throw new ServletException("Invalid Session"); InputStream in = null; OutputStream out = resp.getOutputStream(); FileInputStream fIn = new FileInputStream(fileName); byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) > 0){ out.write(buffer, 0, length); } in.close(); out.flush(); } } for the moment i will just pass a fileName string to retrieve the file for testing now i am lost at what to do on the client side, i have a simple public class DownloadFilePanel extends Composite { public DownloadFilePanel(final YFUser user , final String fileName){ final Element downloadIframe = RootPanel.get("__download").getElement(); VerticalPanel content = new VerticalPanel(); content.add(new Label("Download For this File : " + fileName)); Button button = new Button("Download"); button.addClickHandler(new ClickHandler(){ @Override public void onClick(ClickEvent event) { // i do not know what to do here }); content.add(button); initWidget(content); } } above is a simple widget that will supply a panel that will allow for the download of a file based on a fileName as you can see above, i do not know what to do to be able to download the file is there any one that can point me in the right direction?

    Read the article

  • Blackberry - Listfield layout question

    - by Kai
    I'm having an interesting anomaly when displaying a listfield on the blackberry simulator: The top item is the height of a single line of text (about 12 pixels) while the rest are fine. Does anyone know why only the top item is being drawn this way? Also, when I add an empty venue in position 0, it still displays the first actual venue this way (item in position 1). Not sure what to do. Thanks for any help. The layout looks like this: ----------------------------------- | *part of image* | title | ----------------------------------- | | title | | * full image * | address | | | city, zip | ----------------------------------- The object is called like so: listField = new ListField( venueList.size() ); listField.setCallback( this ); listField.setSelectedIndex(-1); _middle.add( listField ); Here is the drawListRow code: public void drawListRow( ListField listField, Graphics graphics, int index, int y, int width ) { listField.setRowHeight(90); Hashtable item = (Hashtable) venueList.elementAt( index ); String venue_name = (String) item.get("name"); String image_url = (String) item.get("image_url"); String address = (String) item.get("address"); String city = (String) item.get("city"); String zip = (String) item.get("zip"); EncodedImage img = null; try { String filename = image_url.substring(image_url.indexOf("crop/") + 5, image_url.length() ); FileConnection fconn = (FileConnection)Connector.open( "file:///SDCard/Blackberry/project1/" + filename, Connector.READ); if ( !fconn.exists() ) { } else { InputStream input = fconn.openInputStream(); byte[] data = new byte[(int)fconn.fileSize()]; input.read(data); input.close(); if(data.length > 0) { EncodedImage rawimg = EncodedImage.createEncodedImage( data, 0, data.length); int dw = Fixed32.toFP(Display.getWidth()); int iw = Fixed32.toFP(rawimg.getWidth()); int sf = Fixed32.div(iw, dw); img = rawimg.scaleImage32(sf * 4, sf * 4); } else { } } } catch(IOException ef) { } graphics.drawText( venue_name, 140, y, 0, width ); graphics.drawText( address, 140, y + 15, 0, width ); graphics.drawText( city + ", " + zip, 140, y + 30, 0, width ); if(img != null) { graphics.drawImage(0, y, img.getWidth(), img.getHeight(), img, 0, 0, 0); } }

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23  | Next Page >