Search Results

Search found 268 results on 11 pages for 'outputstream'.

Page 10/11 | < Previous Page | 6 7 8 9 10 11  | Next Page >

  • Can't get InputStream read to block...

    - by mark dufresne
    I would like the input stream read to block instead of reading end of stream (-1). Is there a way to configure the stream to do this? Here's my Servlet code: PrintWriter out = response.getWriter(); BufferedReader in = request.getReader(); try { String line; int loop = 0; while (loop < 20) { line = in.readLine(); lgr.log(Level.INFO, line); out.println("<" + loop + "html>"); Thread.sleep(1000); loop++; // } } catch (InterruptedException ex) { lgr.log(Level.SEVERE, null, ex); } finally { out.close(); } Here's my Midlet code: private HttpConnection conn; InputStream is; OutputStream os; private boolean exit = false; public void run() { String url = "http://localhost:8080/WebApplication2/NewServlet"; try { conn = (HttpConnection) Connector.open(url); is = conn.openInputStream(); os = conn.openOutputStream(); StringBuffer sb = new StringBuffer(); int c; while (!exit) { os.write("<html>\n".getBytes()); while ((c = is.read()) != -1) { sb.append((char) c); } System.out.println(sb.toString()); sb.delete(0, sb.length() - 1); try { Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } os.close(); is.close(); conn.close(); } catch (IOException ex) { ex.printStackTrace(); } } I've tried InputStream.read, but it doesn't block either, it returns -1 as well. I'm trying to keep the I/O streams on either side alive. I want the servlet to wait for input, process the input, then send back a response. In the code above it should do this 20 times. thanks for any help

    Read the article

  • Vaadin: Downloaded file has whole path as file name

    - by javydreamercsw
    I have a download action implemented on my Vaadin application but for some reason the downloaded file has the original file's full path as the file name. Any idea? You can see the code on this post. Edit: Here's the important part of the code: package com.bluecubs.xinco.core.server.vaadin; import com.bluecubs.xinco.core.server.XincoConfigSingletonServer; import com.vaadin.Application; import com.vaadin.terminal.DownloadStream; import com.vaadin.terminal.FileResource; import java.io.*; import java.net.URLEncoder; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.CRC32; import java.util.zip.CheckedInputStream; /** * * @author Javier A. Ortiz Bultrón<[email protected]> */ public class FileDownloadResource extends FileResource { private final String fileName; private File download; private File newFile; public FileDownloadResource(File sourceFile, String fileName, Application application) { super(sourceFile, application); this.fileName = fileName; } protected void cleanup() { if (newFile != null && newFile.exists()) { newFile.delete(); } if (download != null && download.exists() && download.listFiles().length == 0) { download.delete(); } } @Override public DownloadStream getStream() { try { //Copy file to directory for downloading InputStream in = new CheckedInputStream(new FileInputStream(getSourceFile()), new CRC32()); download = new File(XincoConfigSingletonServer.getInstance().FileRepositoryPath + System.getProperty("file.separator") + UUID.randomUUID().toString()); newFile = new File(download.getAbsolutePath() + System.getProperty("file.separator") + fileName); download.mkdirs(); OutputStream out = new FileOutputStream(newFile); newFile.deleteOnExit(); download.deleteOnExit(); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); final DownloadStream ds = new DownloadStream( new FileInputStream(newFile), getMIMEType(), fileName); ds.setParameter("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8")); ds.setCacheTime(getCacheTime()); return ds; } catch (final FileNotFoundException ex) { Logger.getLogger(FileDownloadResource.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (IOException ex) { Logger.getLogger(FileDownloadResource.class.getName()).log(Level.SEVERE, null, ex); return null; } } } I already debugged and verified that fileName only contains the file's name not the whole path.

    Read the article

  • Large File Download - Connection With Server Reset

    - by daveywc
    I have an asp.net website that allows the user to download largish files - 30mb to about 60mb. Sometimes the download works fine but often it fails at some varying point before the download finishes with the message saying that the connection with the server was reset. Originally I was simply using Server.TransmitFile but after reading up a bit I am now using the code posted below. I am also setting the Server.ScriptTimeout value to 3600 in the Page_Init event. private void DownloadFile(string fname, bool forceDownload) { string path = MapPath(fname); string name = Path.GetFileName(path); string ext = Path.GetExtension(path); string type = ""; // set known types based on file extension if (ext != null) { switch (ext.ToLower()) { case ".mp3": type = "audio/mpeg"; break; case ".htm": case ".html": type = "text/HTML"; break; case ".txt": type = "text/plain"; break; case ".doc": case ".rtf": type = "Application/msword"; break; } } if (forceDownload) { Response.AppendHeader("content-disposition", "attachment; filename=" + name.Replace(" ", "_")); } if (type != "") { Response.ContentType = type; } else { Response.ContentType = "application/x-msdownload"; } System.IO.Stream iStream = null; // Buffer to read 10K bytes in chunk: byte[] buffer = new Byte[10000]; // Length of the file: int length; // Total bytes to read: long dataToRead; try { // Open the file. iStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); // Total bytes to read: dataToRead = iStream.Length; //Response.ContentType = "application/octet-stream"; //Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); // Read the bytes. while (dataToRead > 0) { // Verify that the client is connected. if (Response.IsClientConnected) { // Read the data in buffer. length = iStream.Read(buffer, 0, 10000); // Write the data to the current output stream. Response.OutputStream.Write(buffer, 0, length); // Flush the data to the HTML output. Response.Flush(); buffer = new Byte[10000]; dataToRead = dataToRead - length; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } } catch (Exception ex) { // Trap the error, if any. Response.Write("Error : " + ex.Message); } finally { if (iStream != null) { //Close the file. iStream.Close(); } Response.Close(); } }

    Read the article

  • Java: Detecting image formate - resize (scale) and save as JPEG

    - by BoDiE2003
    This is the code I have, it actually works, not perfectly but it does, the problem is that the resized thumbnails are not pasting on the white Drawn rectangle, breaking the images aspect ratio, here is the code, could someone suggest me a fix for it, please? Thank you import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ImageScalerImageIoImpl implements ImageScaler { private static final String OUTPUT_FORMAT_ID = "jpeg"; // Re-scaling image public byte[] scaleImage(byte[] originalImage, int targetWidth, int targetHeight) { try { InputStream imageStream = new BufferedInputStream( new ByteArrayInputStream(originalImage)); Image image = (Image) ImageIO.read(imageStream); int thumbWidth = targetWidth; int thumbHeight = targetHeight; // Make sure the aspect ratio is maintained, so the image is not skewed double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } // Draw the scaled image BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); System.out.println("Thumb width Buffered: " + thumbWidth + " || Thumb height Buffered: " + thumbHeight); Graphics2D graphics2D = thumbImage.createGraphics(); // Use of BILNEAR filtering to enable smooth scaling graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // White Background graphics2D.setPaint(Color.WHITE); graphics2D.fill(new Rectangle2D.Double(0, 0, targetWidth, targetHeight)); graphics2D.fillRect(0, 0, targetWidth, targetHeight); System.out.println("Target width: " + targetWidth + " || Target height: " + targetHeight); // insert the resized thumbnail between X and Y of the image graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); System.out.println("Thumb width: " + thumbWidth + " || Thumb height: " + thumbHeight); // Write the scaled image to the outputstream ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(thumbImage, OUTPUT_FORMAT_ID, out); return out.toByteArray(); } catch (IOException ioe) { throw new ImageResizingException(ioe); } } }

    Read the article

  • run shell command from java

    - by Aykut
    Hi, I am working on an application an have an issue about running shell command from java application. here is the code: public String execRuntime(String cmd) { Process proc = null; int inBuffer, errBuffer; int result = 0; StringBuffer outputReport = new StringBuffer(); StringBuffer errorBuffer = new StringBuffer(); try { proc = Runtime.getRuntime().exec(cmd); } catch (IOException e) { return ""; } try { response.status = 1; result = proc.waitFor(); } catch (InterruptedException e) { return ""; } if (proc != null && null != proc.getInputStream()) { InputStream is = proc.getInputStream(); InputStream es = proc.getErrorStream(); OutputStream os = proc.getOutputStream(); try { while ((inBuffer = is.read()) != -1) { outputReport.append((char) inBuffer); } while ((errBuffer = es.read()) != -1) { errorBuffer.append((char) errBuffer); } } catch (IOException e) { return ""; } try { is.close(); is = null; es.close(); es = null; os.close(); os = null; } catch (IOException e) { return ""; } proc.destroy(); proc = null; } if (errorBuffer.length() > 0) { logger .error("could not finish execution because of error(s)."); logger.error("*** Error : " + errorBuffer.toString()); return ""; } return outputReport.toString(); } but when i try to exec command like : /export/home/test/myapp -T "some argument" myapp reads "some argument" as two seperated arguments.but I want to read "some argument" as only a argument. when i directly run this command from terminal, it executed successfully. I tried '"some argument"' ,""some argument"" , "some\ argument" but did not work for me. how can i read this argument as one argument. Thnaks.

    Read the article

  • Threadpool with pasistant worker instances

    - by Matt Smokey-waters Holmes
    So basically what im trying to do is queue up tasks in a thread pool to be executed as soon as a worker becomes free, i have found various examples of this but in all cases the examples have been setup to use a new Worker instance for each job, i want persistent workers. Im trying to make a ftp backup tool, i have it working but because of the limitations of a single connection it is slow. What i ideally want to do is have a single connection for scanning directories and building up a file list then four workers to download said files. Here is an example of my worker /** * FTP Worker */ public class Worker implements Runnable { protected FTPClient _ftp; // Connection details protected String _host = ""; protected String _user = ""; protected String _pass = ""; // worker status protected boolean _working = false; public Worker(String host, String user, String pass) { this._host = host; this._user = user; this._pass = pass; } // Check if the worker is in use public boolean inUse() { return this._working; } @Override public void run() { this._ftp = new FTPClient(); this._connect(); } // Download a file from the ftp server public boolean download(String base, String path, String file) { this._working = true; boolean outcome = true; //create directory if not exists File pathDir = new File(base + path); if (!pathDir.exists()) { pathDir.mkdirs(); } //download file try { OutputStream output = new FileOutputStream(base + path + file); this._ftp.retrieveFile(file, output); output.close(); } catch (Exception e) { outcome = false; } finally { this._working = false; return outcome; } } // Connect to the server protected boolean _connect() { try { this._ftp.connect(this._host); this._ftp.login(this._user, this._pass); } catch (Exception e) { return false; } return this._ftp.isConnected(); } // Disconnect from the server protected void _disconnect() { try { this._ftp.disconnect(); } catch (Exception e) { /* do nothing */ } } } and basically i want to be able to call Worker.download(...) for each task in a queue whenever a worker becomes available without having to create a new connection to the ftp server for each download Any help would be appreciated as iv'e never used threads before and I'm going round in circles at the moment

    Read the article

  • Command Not working in separate thread in J2me.

    - by RishiPatel
    I am creating a bluetooth application. I created a simple midlet with a exit command and i create a thread for finding the service and discovering the device. While doing so it displays a animated screen on which i added the parent commandListener for exit command. After successful connection both user is represented with greetings(Current screen calls the parent Display method setCurrent for displaying itself). This screen also have CommandListener set to the parent. Now i want to add few more commands. I Implemented the CommandLIstener Interface in this class, added few commands but the commands are not working. I dont whats wen wrong. I am giving u Code snippets to fully describle my issue : - package name Imports here public class MyMidlet extends MIDlet implements CommandListener { public CommandListener theListener; public Display theDisplay; public Command exitCommand; public MyMidlet() { // Retrieve the display for this MIDlet //Create the initial screen } public void startApp() throws MIDletStateChangeException { } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command c, Displayable d) { // Determine if the exit command was selected if (c == exitCommand) { //End application here notifyDestroyed(); } else { //Start the new thread here } } } Now here is the code for the class which is invoked by the above midlet in a separate thread; package here; imports here public class MyService implements Runnable, CommandListener { private MyMidlet parent; private StreamConnection conn; private OutputStream output; private InputStream input; public Command sendCommand; private TextField messageToSend Form form; public BChatService(boolean isServer, BChatMidlet parent) { //some stuff here this.parent = parent; } public void run() { //functino for showing animation here try { input = conn.openInputStream(); output = conn.openOutputStream(); } catch (IOException e) { displayError("IO Error", "An error occurred while opening " + "the input and output streams" + "(IOException: " + e.getMessage() + ")"); try { conn.close(); } catch (Exception ex) { } return; } // Create the Form here when service is discoverd and greets the users Command sendCommand = new Command("Send", Command.ITEM, 2); exitCommand = new Command("Exit", Command.EXIT, 1); form.addCommand(exitCommand); form.addCommand(sendCommand); parent.theDisplay.setCurrent(form); form.setCommandListener(this); public void commandAction(Command c, Displayable d) { if (c == exitCommand) { // End the game parent.destroyApp(true); parent.notifyDestroyed(); } if(c == sendCommand) { form.append("SOme text here"); } } } When i select the Send command, the string doesnt append in form neither exit command works. What can be the possible cause for it?? I need to implement this functionality...Is there any other way to achieve this??

    Read the article

  • Display BLOB (image) through JSP

    - by jMarcel
    I have a code to show a chart o employees. The data (name, phone, photo etc) are stored in SQLServer and displayed through JSP. Showing the data is ok, except the image .jpg (stored in IMAGE=BLOB column). By the way, I've already got the image displayed (see code below), but I dont't know how to put it in the area defined in a .css (see code below, too), since the image got through the resultSet is loaded in the whole page in the browser. Does anyone knows how can I 'frame' the image ? <% Connection con = FactoryConnection_SQL_SERVER.getConnection("empCHART"); Statement stSuper = con.createStatement(); Statement stSetor = con.createStatement(); Blob image = null; byte[] imgData = null; ResultSet rsSuper = stSuper.executeQuery("SELECT * FROM funChart WHERE dept = 'myDept'"); if (rsSuper.next()) { image = rsSuper.getBlob(12); imgData = image.getBytes(1, (int) image.length()); response.setContentType("image/gif"); OutputStream o = response.getOutputStream(); //o.write(imgData); // even here we got the same as below. //o.flush(); //o.close(); --[...] <table style="margin: 0px; margin-top: 15px;"> <tr> <td id="photo"> <img title="<%=rsSuper.getString("empName").trim()%>" src="<%= o.wite(imageData); o.flush(); o.close(); %>" /> </td> </td> <td id="empData"> <h3><%=rsSuper.getString("empName")%></h3> <p><%=rsSuper.getString("Position")%></p> <p>Id:<br/><%=rsSuper.getString("id")%></p> <p>Phone:<br/><%=rsSuper.getString("Phone")%></p> <p>E-Mail:<br/><%=rsSuper.getString("Email")%></p> </td> </table> And here is the fragment supposed to frame the image: #photo { padding: 0px; vertical-align: middle; text-align: center; width: 170px; height: 220px; } Thanks in advance !

    Read the article

  • Can SQLite file copied successfully on the data folder of an unrooted android device ?

    - by student
    I know that in order to access the data folder on the device, it needs to be rooted. However, if I just want to copy the database from my assets folder to the data folder on my device, will the copying process works on an unrooted phone? The following is my Database Helper class. From logcat, I can verify that the methods call to copyDataBase(), createDataBase() and openDataBase() are returned successfully. However, I got this error message android.database.sqlite.SQLiteException: no such table: TABLE_NAME: when my application is executing rawQuery. I'm suspecting the database file is not copied successfully (cannot be too sure as I do not have access to data folder), yet the method call to copyDatabase() are not throwing any exception. What could it be? Thanks. ps: My device is still unrooted, I hope it is not the main cause of the error. public DatabaseHelper(Context context) { super(context, DB_NAME, null, 1); this.myContext = context; } public void createDataBase() throws IOException{ boolean dbExist = checkDataBase(); String s = new Boolean(dbExist).toString(); Log.d("dbExist", s ); if(dbExist){ //do nothing - database already exist Log.d("createdatabase","DB exists so do nothing"); }else{ this.getReadableDatabase(); try { copyDataBase(); Log.d("copydatabase","Successful return frm method call!"); } catch (IOException e) { throw new Error("Error copying database"); } } } private boolean checkDataBase(){ File dbFile = new File(DB_PATH + DB_NAME); return dbFile.exists(); } private void copyDataBase() throws IOException{ //Open your local db as the input stream InputStream myInput = null; myInput = myContext.getAssets().open(DB_NAME); Log.d("copydatabase","InputStream successful!"); // Path to the just created empty db String outFileName = DB_PATH + DB_NAME; //Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); //transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer))>0){ myOutput.write(buffer, 0, length); } //Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } public void openDataBase() throws SQLException{ //Open the database String myPath = DB_PATH + DB_NAME; myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } /* @Override public synchronized void close() { if(myDataBase != null) myDataBase.close(); super.close(); }*/ public void close() { // NOTE: openHelper must now be a member of CallDataHelper; // you currently have it as a local in your constructor if (myDataBase != null) { myDataBase.close(); } } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }

    Read the article

  • Creating vCard action result

    - by DigiMortal
    I added support for vCards to one of my ASP.NET MVC applications. I worked vCard support out as very simple and intelligent solution that fits perfectly to ASP.NET MVC applications. In this posting I will show you how to send vCards out as response to ASP.NET MVC request. We need three things: some vCard class, vCard action result, controller method to test vCard action result. Everything is very simple, let’s get hands on. vCard class As first thing we need vCard class. Last year I introduced vCard class that supports also images. Let’s take this class because it is easy to use and some dirty work is already done for us. NB! Take a look at ASP.NET example in the blog posting referred above. We need it later when we close the topic. Now think about how useful blogging and information sharing with others can be. With this class available at public I saved pretty much time now. :) vCardResult As we have vCard it is now time to write action result that we can use in our controllers. Here’s the code. public class vCardResult : ActionResult {     private vCard _card;       protected vCardResult() { }       public vCardResult(vCard card)     {         _card = card;     }       public override void ExecuteResult(ControllerContext context)     {         var response = context.HttpContext.Response;         response.ContentType = "text/vcard";         response.AddHeader("Content-Disposition", "attachment; fileName=" + _card.FirstName + " " + _card.LastName + ".vcf");           var cardString = _card.ToString();         var inputEncoding = Encoding.Default;         var outputEncoding = Encoding.GetEncoding("windows-1257");         var cardBytes = inputEncoding.GetBytes(cardString);           var outputBytes = Encoding.Convert(inputEncoding,                                 outputEncoding, cardBytes);           response.OutputStream.Write(outputBytes, 0, outputBytes.Length);     } } And we are done. Some notes: vCard is sent to browser as downloadable file (user can save or open it with Outlook or any other e-mail client that supports vCards), File name is made of first and last name of contact. Encoding is important because Outlook may not understand vCards otherwise (don’t know if this problem is solved in Outlook 2010). Using vCardResult in controller Now let’s tale a look at simple controller method that accepts person ID and returns vCardResult. public class ContactsController : Controller {       // ... other controller methods ...       public vCardResult vCard(int id)     {         var person = _partyRepository.GetPersonById(id);         var card = new vCard                 {                     FirstName=person.FirstName,                     LastName = person.LastName,                     StreetAddress = person.StreetAddress,                     City = person.City,                     CountryName = person.Country.Name,                       Mobile = person.Mobile,                     Phone = person.Phone,                     Email = person.Email,                 };           return new vCardResult(card);     } } Now you can run Visual Studio and check out how your vCard is moving from your web application to your e-mail client. Conclusion We took old code that worked well with ASP.NET Forms and we divided it into action result and controller method that uses vCard as bridge between our controller and action result. All functionality is located where it should be and we did nothing complex. We wrote only couple of lines of very easy code to achieve our goal. Do you understand now why I love ASP.NET MVC? :)

    Read the article

  • Save blob to DB using hibernate

    - by Link123
    Hey! I tried save file to MySQL using blob with hibernate3. But I always have java.lang.UnsupportedOperationException: Blob may not be manipulated from creating session org.hibernate.lob.BlobImpl.excep(BlobImpl.java:127) Here some code. package com.uni.domain; public class File extends Identifier { private byte[] data; private String contentType; public byte[] getData() { return data; } public File() {} public void setData(byte[] photo) { this.data = photo; } public boolean isNew() { return true; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } } package com.uni.domain; import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.usertype.UserType; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.sql.*; import java.util.Arrays; public class PhotoType implements UserType { public int[] sqlTypes() { return new int[]{Types.BLOB}; } public Class returnedClass() { return byte[].class; } public boolean equals(Object o, Object o1) throws HibernateException { return Arrays.equals((byte[]) o, (byte[]) o1); } public int hashCode(Object o) throws HibernateException { return o.hashCode(); } public Object nullSafeGet(ResultSet resultSet, String[] strings, Object o) throws HibernateException, SQLException { Blob blob = resultSet.getBlob(strings[0]); return blob.getBytes(1, (int) blob.length()); } public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { st.setBlob(index, Hibernate.createBlob((byte[]) value)); } public Object deepCopy(Object value) { if (value == null) return null; byte[] bytes = (byte[]) value; byte[] result = new byte[bytes.length]; System.arraycopy(bytes, 0, result, 0, bytes.length); return result; } public boolean isMutable() { return true; } public Serializable disassemble(Object o) throws HibernateException { return null; . } public Object assemble(Serializable serializable, Object o) throws HibernateException { return null; . } public Object replace(Object o, Object o1, Object o2) throws HibernateException { return null; . } <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.uni.domain"> <class name="com.uni.domain.File"> <id name="id"> <generator class="native"/> </id> <property name="data" type="com.uni.domain.FleType"/> <property name="contentType"/> </class> </hibernate-mapping> Help me please. Where I’m wrong?

    Read the article

  • Receicing POST data in ASP.NET

    - by grast
    Hi, I want to use ASP for code generation in a C# desktop application. To achieve this, I set up a simple host (derived from System.MarshalByRefObject) that processes a System.Web.Hosting.SimpleWorkerRequest via HttpRuntime.ProcessRequest. This processes the ASPX script specified by the incoming request (using System.Net.HttpListener to wait for requests). The client-part is represented by a System.ComponentModel.BackgroundWorker that builds the System.Net.HttpWebRequest and receives the response from the server. A simplified version of my client-part-code looks like this: private void SendRequest(object sender, DoWorkEventArgs e) { // create request with GET parameter var uri = "http://localhost:9876/test.aspx?getTest=321"; var request = (HttpWebRequest)WebRequest.Create(uri); // append POST parameter request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; var postData = Encoding.Default.GetBytes("postTest=654"); var postDataStream = request.GetRequestStream(); postDataStream.Write(postData, 0, postData.Length); // send request, wait for response and store/print content using (var response = (HttpWebResponse)request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { _processsedContent = reader.ReadToEnd(); Debug.Print(_processsedContent); } } } My server-part-code looks like this (without exception-handling etc.): public void ProcessRequests() { // HttpListener at http://localhost:9876/ var listener = SetupListener(); // SimpleHost created by ApplicationHost.CreateApplicationHost var host = SetupHost(); while (_running) { var context = listener.GetContext(); using (var writer = new StreamWriter(context.Response.OutputStream)) { // process ASP script and send response back to client host.ProcessRequest(GetPage(context), GetQuery(context), writer); } context.Response.Close(); } } So far all this works fine as long as I just use GET parameters. But when it comes to receiving POST data in my ASPX script I run into trouble. For testing I use the following script: // GET parameters are working: var getTest = Request.QueryString["getTest"]; Response.Write("getTest: " + getTest); // prints "getTest: 321" // don't know how to access POST parameters: var postTest1 = Request.Form["postTest"]; // Request.Form is empty?! Response.Write("postTest1: " + postTest1); // so this prints "postTest1: " var postTest2 = Request.Params["postTest"]; // Request.Params is empty?! Response.Write("postTest2: " + postTest2); // so this prints "postTest2: " It seems that the System.Web.HttpRequest object I'm dealing with in ASP does not contain any information about my POST parameter "postTest". I inspected it in debug mode and none of the members did contain neither the parameter-name "postTest" nor the parameter-value "654". I also tried the BinaryRead method of Request, but unfortunately it is empty. This corresponds to Request.InputStream==null and Request.ContentLength==0. And to make things really confusing the Request.HttpMethod member is set to "GET"?! To isolate the problem I tested the code by using a PHP script instead of the ASPX script. This is very simple: print_r($_GET); // prints all GET variables print_r($_POST); // prints all POST variables And the result is: Array ( [getTest] = 321 ) Array ( [postTest] = 654 ) So with the PHP script it works, I can access the POST data. Why does the ASPX script don't? What am I doing wrong? Is there a special accessor or method in the Response object? Can anyone give a hint or even know how to solve this? Thanks in advance.

    Read the article

  • How to create Large resumable download from a secured location .NET

    - by Kelvin H
    I need to preface I'm not a .NET coder at all, but to get partial functionality, I modified a technet chunkedfilefetch.aspx script that uses chunked Data Reading and writing Streamed method of doing file transfer, to get me half-way. iStream = New System.IO.FileStream(path, System.IO.FileMode.Open, _ IO.FileAccess.Read, IO.FileShare.Read) dataToRead = iStream.Length Response.ContentType = "application/octet-stream" Response.AddHeader("Content-Length", file.Length.ToString()) Response.AddHeader("Content-Disposition", "attachment; filename=" & filedownload) ' Read and send the file 16,000 bytes at a time. ' While dataToRead 0 If Response.IsClientConnected Then length = iStream.Read(buffer, 0, 16000) Response.OutputStream.Write(buffer, 0, length) Response.Flush() ReDim buffer(16000) ' Clear the buffer ' dataToRead = dataToRead - length Else ' Prevent infinite loop if user disconnects ' dataToRead = -1 End If End While This works great on files up to 2GB and is fully functioning now.. But only one problem it doesn't allow for resume. I took the original code called it fetch.aspx and pass an orderNUM through the URL. fetch.aspx&ordernum=xxxxxxx It then reads the filename/location from the database occording to the ordernumber, and chunks it out from a secured location NOT under the webroot. I need a way to make this resumable, by the nature of the internet and large files people always get disconnected and would like to resume where they left off. But any resumable articles i've read, assume the file is within the webroot.. ie. http://www.devx.com/dotnet/Article/22533/1954 Great article and works well, but I need to stream from a secured location. I'm not a .NET coder at all, at best i can do a bit of coldfusion, if anyone could help me modify a handler to do this, i would really appreciate it. Requirements: I Have a working fetch.aspx script that functions well and uses the above code snippet as a base for the streamed downloading. Download files are large 600MB and are stored in a secured location outside of the webroot. Users click on the fetch.aspx to start the download, and would therefore be clicking it again if it was to fail. If the ext is a .ASPX and the file being sent is a AVI, clicking on it would completely bypass an IHTTP handler mapped to .AVI ext, so this confuses me From what I understand the browser will read and match etag value and file modified date to determine they are talking about the same file, then a subsequent accept-range is exchanged between the browser and IIS. Since this dialog happens with IIS, we need to use a handler to intercept and respond accordingly, but clicking on the link would send it to an ASPX file which the handeler needs to be on an AVI fiel.. Also confusing me. If there is a way to request the initial HTTP request header containing etag, accept-range into the normal .ASPX file, i could read those values and if the accept-range and etag exist, start chunking at that byte value somehow? but I couldn't find a way to transfer the http request headers since they seem to get lost at the IIS level. OrderNum which is passed in the URL string is unique and could be used as the ETag Response.AddHeader("ETag", request("ordernum")) Files need to be resumable and chunked out due to size. File extensions are .AVI so a handler could be written around it. IIS 6.0 Web Server Any help would really be appreciated, i've been reading and reading and downloading code, but none of the examples given meet my situation with the original file being streamed from outside of the webroot. Please help me get a handle on these httphandlers :)

    Read the article

  • How to read URDU from url and show it to your mobile using java Me

    - by Basit
    HI, Hope you all will be fine. Actually I m facing a problem. Actually i am using Google translation API. What my application does it connect to CGI-script, i pass value to it using GET then the CGI script connect to Google API, Translate the mesage from english to Urdu and then i retreive it.Here is the code [Java] import java.io.*; import javax.microedition.io.*; import javax.microedition.lcdui.*; import javax.microedition.midlet.*; /** * An example MIDlet to invoke a CGI script (GET method). */ public class InvokeCgiMidlet1 extends MIDlet { private Display display; String url = "http://xxx.xxx.xx.xxx/cgi-bin/api/GT/GT_Send_Msg.cgi?message=my%20name%20is%20basit"; public InvokeCgiMidlet1() { display = Display.getDisplay(this); } /** * Initialization. Invoked when we activate the MIDlet. */ public void startApp() { try { getGrade(url); } catch (IOException e) { System.out.println("IOException " + e); e.printStackTrace(); } } /** * Pause, discontinue .... */ public void pauseApp() { } /** * Destroy must cleanup everything. */ public void destroyApp(boolean unconditional) { } /** * Retrieve a grade.... */ void getGrade(String url) throws IOException { HttpConnection c = null; InputStream is = null; OutputStream os = null; StringBuffer b = new StringBuffer(); TextBox t = null; String response; try { c = (HttpConnection)Connector.open(url, Connector.READ_WRITE); c.setRequestMethod(HttpConnection.GET); c.setRequestProperty("User-Agent","Profile/MIDP-1.0 Confirguration/CLDC-1.0"); c.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); c.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.1"); c.setRequestProperty("Accept-Charset","UTF-8;q=0.7,*;q=0.7"); c.setRequestProperty("Accept-Encoding","gzip, deflate"); c.setRequestProperty("Accept","text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); c.setRequestProperty("Content-Language", "en-EN"); os = c.openOutputStream(); Reader r = new InputStreamReader(c.openDataInputStream(), "UTF-8"); int ch; while ((ch = r.read()) != -1) { b.append((char) ch ); //System.out.println((char)ch + "->" + ch + "->" + ch); } t = new TextBox("Final Grades", b.reverse().toString(), 1024, 0); } finally { if(is!= null) { is.close(); } if(os != null) { os.close(); } if(c != null) { c.close(); } } display.setCurrent(t); } } [/Java] The problem is as i told you that the translated text is in Urdu. So when it appear on screen each character is separate like this. ? ?? ? ? ?? . Because i read character by character I want it to appear in proper form like this ??????? So how can i do this. Is there font rendering required. If yes then how can i do it or any other method please hep me. Thanks

    Read the article

  • The problem about use the exist sqlite database,

    - by flybirdtt
    I have a sqlite database, and i put this file in "assets" folder. The code like below, Pls help and tell what's wrong in this code, How to use my own sqlite database. public class DataBaseHelper extends SQLiteOpenHelper { private static String DB_PATH = "/data/data/com.SGMalls/databases/"; private static String DB_NAME = "mallMapv2.sqlite"; private SQLiteDatabase myDataBase; private final Context myContext; public DataBaseHelper(Context context) { super(context, DB_NAME, null, 1); this.myContext = context; } public void createDataBase() throws IOException { File dbDir = new File(DB_PATH); if (!dbDir.exists()) { dbDir.mkdir(); } boolean dbExist = checkDataBase(); if (dbExist) { } else { this.getReadableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error("Error copying database"); } } close(); } private boolean checkDataBase() { SQLiteDatabase checkDB = null; boolean isnull=false; try { String myPath = DB_PATH + DB_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } catch (SQLiteException e) { // database does't exist yet. } if (checkDB != null) { isnull=true; checkDB.close(); } return isnull; } private void copyDataBase() throws IOException { InputStream myInput = myContext.getAssets().open(DB_NAME); String outFileName = DB_PATH + DB_NAME; OutputStream myOutput = new FileOutputStream(outFileName); byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } public void openDataBase() throws SQLException { // Open the database String myPath = DB_PATH + DB_NAME; myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } @Override public synchronized void close() { if (myDataBase != null) myDataBase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } public class GetData { private static String DB_PATH = "/data/data/com.SGMalls/databases/mallMapv2.sqlite"; // private static String DB_NAME = "mallMapv2.sqlite"; public static ArrayList<Mall> getMalls() { ArrayList<Mall> mallsList = new ArrayList<Mall>(); SQLiteDatabase malldatabase = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READONLY); String queryString="select id,title from malls order by title"; Cursor cursor=malldatabase.rawQuery(queryString, null); if(cursor!=null){ cursor.moveToFirst(); while(!cursor.isLast()){ Mall mall=new Mall(); mall.setMallid(cursor.getInt(0)); mall.setMallname(cursor.getString(0)); mallsList.add(mall); cursor.moveToNext(); } } malldatabase.close(); return mallsList; } } The error message: ERROR/Database(725): sqlite3_open_v2("/data/data/com.SGMalls/databases/ mallMapv2.sqlite", &handle, 1, NULL) failed 03-15 22:34:11.747: ERROR/AndroidRuntime(725): Uncaught handler: thread main exiting due to uncaught exception 03-15 22:34:11.766: ERROR/AndroidRuntime(725): java.lang.Error: Error copying database Thanks very much

    Read the article

  • Receiving POST data in ASP.NET

    - by grast
    Hi, I want to use ASP for code generation in a C# desktop application. To achieve this, I set up a simple host (derived from System.MarshalByRefObject) that processes a System.Web.Hosting.SimpleWorkerRequest via HttpRuntime.ProcessRequest. This processes the ASPX script specified by the incoming request (using System.Net.HttpListener to wait for requests). The client-part is represented by a System.ComponentModel.BackgroundWorker that builds the System.Net.HttpWebRequest and receives the response from the server. A simplified version of my client-part-code looks like this: private void SendRequest(object sender, DoWorkEventArgs e) { // create request with GET parameter var uri = "http://localhost:9876/test.aspx?getTest=321"; var request = (HttpWebRequest)WebRequest.Create(uri); // append POST parameter request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; var postData = Encoding.Default.GetBytes("postTest=654"); var postDataStream = request.GetRequestStream(); postDataStream.Write(postData, 0, postData.Length); // send request, wait for response and store/print content using (var response = (HttpWebResponse)request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { _processsedContent = reader.ReadToEnd(); Debug.Print(_processsedContent); } } } My server-part-code looks like this (without exception-handling etc.): public void ProcessRequests() { // HttpListener at http://localhost:9876/ var listener = SetupListener(); // SimpleHost created by ApplicationHost.CreateApplicationHost var host = SetupHost(); while (_running) { var context = listener.GetContext(); using (var writer = new StreamWriter(context.Response.OutputStream)) { // process ASP script and send response back to client host.ProcessRequest(GetPage(context), GetQuery(context), writer); } context.Response.Close(); } } So far all this works fine as long as I just use GET parameters. But when it comes to receiving POST data in my ASPX script I run into trouble. For testing I use the following script: // GET parameters are working: var getTest = Request.QueryString["getTest"]; Response.Write("getTest: " + getTest); // prints "getTest: 321" // don't know how to access POST parameters: var postTest1 = Request.Form["postTest"]; // Request.Form is empty?! Response.Write("postTest1: " + postTest1); // so this prints "postTest1: " var postTest2 = Request.Params["postTest"]; // Request.Params is empty?! Response.Write("postTest2: " + postTest2); // so this prints "postTest2: " It seems that the System.Web.HttpRequest object I'm dealing with in ASP does not contain any information about my POST parameter "postTest". I inspected it in debug mode and none of the members did contain neither the parameter-name "postTest" nor the parameter-value "654". I also tried the BinaryRead method of Request, but unfortunately it is empty. This corresponds to Request.InputStream==null and Request.ContentLength==0. And to make things really confusing the Request.HttpMethod member is set to "GET"?! To isolate the problem I tested the code by using a PHP script instead of the ASPX script. This is very simple: print_r($_GET); // prints all GET variables print_r($_POST); // prints all POST variables And the result is: Array ( [getTest] = 321 ) Array ( [postTest] = 654 ) So with the PHP script it works, I can access the POST data. Why does the ASPX script don't? What am I doing wrong? Is there a special accessor or method in the Response object? Can anyone give a hint or even know how to solve this? Thanks in advance.

    Read the article

  • multipart file-upload post request from java

    - by Martin
    I'm trying to make a program that uploads a image to a webserver that accepts multipart file-uploads. More specificly i want to make a http POST request to http://iqs.me that sends a file in the variable "pic". I've made a lot of tries but i don't know if i've even been close. The hardest part seems to be to get a HttpURLConnection to make a request of the type POST. The response i get looks like it makes a GET. (And i want to do this without any third party libs) UPDATE: non-working code goes here (no errors but doesn't seem to do a POST): HttpURLConnection conn = null; BufferedReader br = null; DataOutputStream dos = null; DataInputStream inStream = null; InputStream is = null; OutputStream os = null; boolean ret = false; String StrMessage = ""; String exsistingFileName = "myScreenShot.png"; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1*1024*1024; String responseFromServer = ""; String urlString = "http://iqs.local.com/index.php"; try{ FileInputStream fileInputStream = new FileInputStream( new File(exsistingFileName) ); URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); dos = new DataOutputStream( conn.getOutputStream() ); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"pic\";" + " filename=\"" + exsistingFileName +"\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0){ dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); fileInputStream.close(); dos.flush(); dos.close(); }catch (MalformedURLException ex){ System.out.println("Error:"+ex); }catch (IOException ioe){ System.out.println("Error:"+ioe); } try{ inStream = new DataInputStream ( conn.getInputStream() ); String str; while (( str = inStream.readLine()) != null){ System.out.println(str); } inStream.close(); }catch (IOException ioex){ System.out.println("Error: "+ioex); }

    Read the article

  • multipart file-upload post request from java

    - by Martin
    I'm trying to make a program that uploads a image to a webserver that accepts multipart file-uploads. More specificly i want to make a http POST request to http://iqs.me that sends a file in the variable "pic". I've made a lot of tries but i don't know if i've even been close. The hardest part seems to be to get a HttpURLConnection to make a request of the type POST. The response i get looks like it makes a GET. (And i want to do this without any third party libs) UPDATE: non-working code goes here (no errors but doesn't seem to do a POST): HttpURLConnection conn = null; BufferedReader br = null; DataOutputStream dos = null; DataInputStream inStream = null; InputStream is = null; OutputStream os = null; boolean ret = false; String StrMessage = ""; String exsistingFileName = "myScreenShot.png"; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1*1024*1024; String responseFromServer = ""; String urlString = "http://iqs.local.com/index.php"; try{ FileInputStream fileInputStream = new FileInputStream( new File(exsistingFileName) ); URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); dos = new DataOutputStream( conn.getOutputStream() ); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"pic\";" + " filename=\"" + exsistingFileName +"\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0){ dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); fileInputStream.close(); dos.flush(); dos.close(); }catch (MalformedURLException ex){ System.out.println("Error:"+ex); }catch (IOException ioe){ System.out.println("Error:"+ioe); } try{ inStream = new DataInputStream ( conn.getInputStream() ); String str; while (( str = inStream.readLine()) != null){ System.out.println(str); } inStream.close(); }catch (IOException ioex){ System.out.println("Error: "+ioex); }

    Read the article

  • OutOfMemoryError during the pdf merge

    - by Vijay
    the below code merges the pdf files and returns the combined pdf data. while this code runs, i try to combine the 100 files with each file approximately around 500kb, i get outofmemory error in the line document.close();. this code runs in the web environment, is the memory available to webspehere server is the problem? i read in an article to use freeReader method, but i cannot get how to use it my scenario. protected ByteArrayOutputStream joinPDFs(List<InputStream> pdfStreams, boolean paginate) { Document document = new Document(); ByteArrayOutputStream mergedPdfStream = new ByteArrayOutputStream(); try { //List<InputStream> pdfs = pdfStreams; List<PdfReader> readers = new ArrayList<PdfReader>(); int totalPages = 0; //Iterator<InputStream> iteratorPDFs = pdfs.iterator(); Iterator<InputStream> iteratorPDFs = pdfStreams.iterator(); // Create Readers for the pdfs. while (iteratorPDFs.hasNext()) { InputStream pdf = iteratorPDFs.next(); if (pdf == null) continue; PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); totalPages += pdfReader.getNumberOfPages(); } //clear this pdfStreams = null; //WeakReference ref = new WeakReference(pdfs); //ref.clear(); // Create a writer for the outputstream PdfWriter writer = PdfWriter.getInstance(document, mergedPdfStream); writer.setFullCompression(); document.open(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); PdfContentByte cb = writer.getDirectContent(); // Holds the PDF // data PdfImportedPage page; int currentPageNumber = 0; int pageOfCurrentReaderPDF = 0; Iterator<PdfReader> iteratorPDFReader = readers.iterator(); // Loop through the PDF files and add to the output. while (iteratorPDFReader.hasNext()) { PdfReader pdfReader = iteratorPDFReader.next(); // Create a new page in the target for each source page. while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { pageOfCurrentReaderPDF++; document.setPageSize(pdfReader .getPageSizeWithRotation(pageOfCurrentReaderPDF)); document.newPage(); // pageOfCurrentReaderPDF++; currentPageNumber++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); cb.addTemplate(page, 0, 0); // Code for pagination. if (paginate) { cb.beginText(); cb.setFontAndSize(bf, 9); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + currentPageNumber + " of " + totalPages, 520, 5, 0); cb.endText(); } } pageOfCurrentReaderPDF = 0; System.out.println("now the size is: "+pdfReader.getFileLength()); } mergedPdfStream.flush(); document.close(); mergedPdfStream.close(); return mergedPdfStream; } catch (Exception e) { e.printStackTrace(); } finally { if (document.isOpen()) document.close(); try { if (mergedPdfStream != null) mergedPdfStream.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } return mergedPdfStream; } Thanks V

    Read the article

  • RSA encryption/ Decryption in a client server application

    - by user308806
    Hi guys, probably missing something very straight forward on this, but please forgive me, I'm very naive! Have a client server application where the client identifies its self with an RSA encrypted username & password. Unfortunately I'm getting a "bad padding exception: data must start with zero" when i try to decrypt with the public key on the client side. I'm fairly sure the key is correct as I have tested encrypting with public key then decrypting with private key on the client side with no problems at all. Just seems when I transfer it over the connection it messses it up somehow?! Using PrintWriter & BufferedReader on the sockets if thats of importance. EncodeBASE64 & DecodeBASE64 encode byte[] to 64base and vice versa respectively. Any ideas guys?? Client side: Socket connectionToServer = new Socket("127.0.0.1", 7050); InputStream in = connectionToServer.getInputStream(); DataInputStream dis = new DataInputStream(in); int length = dis.readInt(); byte[] data = new byte[length]; // dis.readFully(data); dis.read(data); System.out.println("The received Data*****************************************"); System.out.println("The length of bits "+ length); System.out.println(data); System.out.println("***********************************************************"); Decryption d = new Decryption(); byte [] ttt = d.decrypt(data); System.out.print(data); String ss = new String(ttt); System.out.println("***********************"); System.out.println(ss); System.out.println("************************"); Server Side: in = connectionFromClient.getInputStream(); OutputStream out = connectionFromClient.getOutputStream(); DataOutputStream dataOut = new DataOutputStream(out); LicenseList licenses = new LicenseList(); String ValidIDs = licenses.getAllIDs(); System.out.println(ValidIDs); Encryption enc = new Encryption(); byte[] encrypted = enc.encrypt(ValidIDs); byte[] dd = enc.encrypt(ValidIDs); String tobesent = new String(dd); //byte[] rsult = enc.decrypt(dd); //String tt = String(rsult); System.out.println("The sent data**********************************************"); System.out.println(dd); String temp = new String(dd); System.out.println(temp); System.out.println("*************************************************************"); //BufferedWriter bf = new BufferedWriter(OutputStreamWriter(out)); //dataOut.write(ValidIDs.getBytes().length); dataOut.writeInt(ValidIDs.getBytes().length); dataOut.flush(); dataOut.write(encrypted); dataOut.flush(); System.out.println("********Testing**************"); System.out.println("Here are the ids:::"); System.out.println(licenses.getAllIDs()); System.out.println("**********************"); //bw.write("it is working well\n");

    Read the article

  • How to convert image to bitmap code for bluetooth print in iphone

    - by John Patel
    I am interested to print image from iPhone programmatically using bluetooth printer device. In one of the sample code I have implemented code for Text print but in that sample I am not getting how to convert image into format, like unsigned char buffer3[796]={ 0x55 , 0x66 , 0x77 , 0x88 , 0x44 , 0x1B , 0x58 , 0x31 , 0x19, 0x20, 0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 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x00 ,0x01 ,0xC0 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x80 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 }; //[self addLabel:@"buffer3 is selected"]; [[session outputStream] write:(const uint8_t *)buffer3 maxLength:796];//send print package*/ This is sample code for Image print I am not able to print any other image because I am not having idea how to convert UIImage or NSData to the below mentioned Bit code. If any proper step by step method to do Image to bitmap conversion, then please let me know this.

    Read the article

  • missing table in SQLite with specific version of HTC DESIRE HD

    - by William
    My application has a SQLite database in the asset folder. When the user launches my application, the database is created and the tables too. This works fine with a lot of devices (Nexus One, Htc Magic, SGS, X10… and even Htc Desire HD v2.2). My application works with all versions of Android (tested on my device (1.6, 2.2, 2.2.1 Htc Magic) and on the emulator (v1,5 until v2.3). I have just a problem with HTC DESIRE HD v2.2.1 1.72.405.3. The logcat: android.database.sqlite.SQLiteException: no such table: LISTE: , while compiling: select _id from LISTE at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2833) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2854) at android.app.ActivityThread.access$2300(ActivityThread.java:136) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2179) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:143) at android.app.ActivityThread.main(ActivityThread.java:5068) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:521) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) at dalvik.system.NativeStart.main(Native Method) Caused by: android.database.sqlite.SQLiteException: no such table: LISTE: , while compiling: select _id from LISTE at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method) at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:91) at android.database.sqlite.SQLiteCompiledSql.(SQLiteCompiledSql.java:64) at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:80) at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:46) at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:53) at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1417) at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1387) ... 11 more My application create the database but it doesn’t copy the tables of the file of the asset folder in data\data\packagename\databases\mydatabase. My code: public void createDataBase() throws IOException{ boolean dbExist = checkDataBase(); if(dbExist){ //do nothing - database already exist }else{ //By calling this method and empty database will be created into the default system path //of your application so we are gonna be able to overwrite that database with our database. this.getReadableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error("Error copying database"); } } } private void copyDataBase() throws IOException{ //Open your local db as the input stream InputStream myInput = myContext.getAssets().open(DB_NAME); // Path to the just created empty db String outFileName = DB_PATH + DB_NAME; //Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); //transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer))!= -1){ if (length > 0){ myOutput.write(buffer, 0, length); } } //Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } I think that the copydatabase function has a problem but I don't see. This code works fine with all devices except the HTC DESIRE HD v2.2.1 1.72.405.3. What problems might exist here for the HTC Desire with the given version above? How can this be remedied?

    Read the article

  • ask help: I need to create a demo application in Java to test my new designed Java Api

    - by Christophe
    A new programmer needs yourhelp. I'm working on a porject of re-developement of Java driver for the company's PIN pad terminals. the Java Api (CPXApplicationUpdate) will allow the applications in pinpads to be updated and to be downloaded at different speed (Baud rate). the Java Api was created. i followed the protocolto build the message. the message is to send to a RS-232 port. i'm trying to use setter and getter to let the code work as an API. import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; public class CPXApplicationUpdate extends CPXCommand { private int speed; // TODO: temporary variable for baud rate test stub. // speed: baud rate of the maintenance application performing DL /** Creates a new instance of CPXApplicationUpdate */ public CPXApplicationUpdate() { speed = 9600; // no baud rate change CPXProcessor.logger.fine("-------CPXApplicationUpdate constructor"); // setParam("timeout", _cmdInfo.getDefaultParValue("timeout")); } public CPXApplicationUpdate(int speedinit) { speed = speedinit; // TODO: where to get the speed? wait for user input. CPXProcessor.logger.fine("-------CPXApplicationUpdate constructor"); // setParam("timeout", _cmdInfo.getDefaultParValue("timeout")); } public void setSpeed(int speed){ this.speed = speed; } protected void buildRequest() throws ElitePortException { String trans = ""; // build the full-qualified message trans = addToRequest(trans, (char) 0); trans = addToRequest(trans, (char) 5); trans = addToRequest(trans, (char) 6); trans = addToRequest(trans, (char) 0); trans = addToRequest(trans, (char) 0); trans = addToRequest(trans, (char) 2); switch (speed) { case 9600: trans = addToRequest(trans, (char) 0x09); break; case 19200: trans = addToRequest(trans, (char) 0x0A); break; case 115200: trans = addToRequest(trans, (char) 0x0E); break; default: // TODO: unexpected baud rate. throw(); break; } trans = EncryptBinary(trans); trans = "F0." + trans; wrapRequest(trans); } protected String addToRequest(String req, char c) { CPXProcessor.logger.fine("adding char to request: I-" + (int) c + " C-" + c + " H-" + Integer.toHexString((int) c)); return req + c; } protected String addToRequest(String req, String s) { CPXProcessor.logger.fine("adding String to request: S-" + s); return req + s; } protected String addToRequest(String req) { return req; } public void analyzeResponse() { String response_transaction, response; int absLen = _response.length(); if (absLen < 4) return; response = _response.substring(3); CPXProcessor.logger.fine("stripped response=[" + response + "]"); for (int i = 0; i < response.length(); i++) { char c = response.charAt(i); CPXProcessor.logger.fine("[" + i + "] = " + c + " <> " + Integer.toHexString((int) c)); } int status = (short) response.charAt(3); CPXProcessor.logger.fine("status = " + status); _outputValues.put("status", "" + status); } please help me to correct the code. Now, i need to create a demo application to test if this java driver (Java Api) works. the value of the speed can be input by users (command line), or creat property files. how can i do that?

    Read the article

  • Servlet response wrapper has encoding problem

    - by John O
    A servlet response wrapper is being used in a Servlet Filter. The idea is that the response is manipulated, with a 'nonce' value being injected into forms, as part of defence against CSRF attacks. The web app is using UTF-8 everywhere. When the Servlet Filter is absent, no problems. When the filter is added, encoding issues occur. (It seems as if the response is reverting to 8859-1.) The guts of the code : final class CsrfResponseWrapper extends AbstractResponseWrapper { ... byte[] modifyResponse(byte[] aInputResponse){ ... String originalInput = new String(aInputResponse, encoding); String modifiedResult = addHiddenParamToPostedForms(originalInput); result = modifiedResult.getBytes(encoding); ... } ... } As I understand it, the transition between byte-land and String-land should specify an encoding. That is done here, as you can see, in two places. The value of the 'encoding' variable is 'UTF-8'; the alteration of the String itself is standard string manipulation (with a regex), and never specifies an encoding (addHiddenParamToPostedForms). Where am I in error about the encoding? EDIT: Here is the base class (sorry it's rather long): package hirondelle.web4j.security; import javax.servlet.ServletOutputStream; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; /** Abstract Base Class for altering response content. (May be useful in future contexts as well. For now, keep package-private.) */ abstract class AbstractResponseWrapper extends HttpServletResponseWrapper { AbstractResponseWrapper(ServletResponse aServletResponse) throws IOException { super((HttpServletResponse)aServletResponse); fOutputStream = new ModifiedOutputStream(aServletResponse.getOutputStream()); fWriter = new PrintWriter(fOutputStream); } /** Return the modified response. */ abstract byte[] modifyResponse(byte[] aInputResponse); /** Standard servlet method. */ public final ServletOutputStream getOutputStream() { //fLogger.fine("Modified Response : Getting output stream."); if ( fWriterReturned ) { throw new IllegalStateException(); } fOutputStreamReturned = true; return fOutputStream; } /** Standard servlet method. */ public final PrintWriter getWriter() { //fLogger.fine("Modified Response : Getting writer."); if ( fOutputStreamReturned ) { throw new IllegalStateException(); } fWriterReturned = true; return fWriter; } // PRIVATE /* Well-behaved servlets return either an OutputStream or a PrintWriter, but not both. */ private PrintWriter fWriter; private ModifiedOutputStream fOutputStream; /* These items are used to implement conformance to the javadoc for ServletResponse, regarding exceptions being thrown. */ private boolean fWriterReturned; private boolean fOutputStreamReturned; /** Modified low level output stream. */ private class ModifiedOutputStream extends ServletOutputStream { public ModifiedOutputStream(ServletOutputStream aOutputStream) { fServletOutputStream = aOutputStream; fBuffer = new ByteArrayOutputStream(); } /** Must be implemented to make this class concrete. */ public void write(int aByte) { fBuffer.write(aByte); } public void close() throws IOException { if ( !fIsClosed ){ processStream(); fServletOutputStream.close(); fIsClosed = true; } } public void flush() throws IOException { if ( fBuffer.size() != 0 ){ if ( !fIsClosed ) { processStream(); fBuffer = new ByteArrayOutputStream(); } } } /** Perform the core processing, by calling the abstract method. */ public void processStream() throws IOException { fServletOutputStream.write(modifyResponse(fBuffer.toByteArray())); fServletOutputStream.flush(); } // PRIVATE // private ServletOutputStream fServletOutputStream; private ByteArrayOutputStream fBuffer; /** Tracks if this stream has been closed. */ private boolean fIsClosed = false; } }

    Read the article

  • Path to background in servlet

    - by kapil chhattani
    //the below line is the element of my HTML form which renders the image sent by the servlet written further below. <img style="margin-left:91px; margin-top:-6px;" class="image" src="http://www.abcd.com/captchaServlet"> I generate a captcha code using the following code in java. public class captchaServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int width = 150; int height = 50; int charsToPrint = 6; String elegibleChars = "ABCDEFGHJKLMPQRSTUVWXYabcdefhjkmnpqrstuvwxy1234567890"; char[] chars = elegibleChars.toCharArray(); StringBuffer finalString = new StringBuffer(); for ( int i = 0; i < charsToPrint; i++ ) { double randomValue = Math.random(); int randomIndex = (int) Math.round(randomValue * (chars.length - 1)); char characterToShow = chars[randomIndex]; finalString.append(characterToShow); } System.out.println(finalString); BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bufferedImage.createGraphics(); Font font = new Font("Georgia", Font.BOLD, 18); g2d.setFont(font); RenderingHints rh = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHints(rh); GradientPaint gp = new GradientPaint(0, 0, Color.BLUE, 0, height/2, Color.black, true); g2d.setPaint(gp); g2d.fillRect(0, 0, width, height); g2d.setColor(new Color(255, 255, 0)); Random r = new Random(); int index = Math.abs(r.nextInt()) % 5; char[] data=new String(finalString).toCharArray(); String captcha = String.copyValueOf(data); int x = 0; int y = 0; for (int i=0; i<data.length; i++) { x += 10 + (Math.abs(r.nextInt()) % 15); y = 20 + Math.abs(r.nextInt()) % 20; g2d.drawChars(data, i, 1, x, y); } g2d.dispose(); response.setContentType("image/png"); OutputStream os = response.getOutputStream(); ImageIO.write(bufferedImage, "png", os); os.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } } But in the above code background is also generated using the setPaint menthod I am guessing. I want the background to be some image from my local machine whoz URL i should be able to mention like URL url=this.getClass().getResource("Desktop/images.jpg"); BufferedImage bufferedImage = ImageIO.read(url); I am just writing the above two lines for making the reader understand better what the issue is. Dont want to use the exact same commands. All I want is the the background of the captcha code generated should be an image of my choice.

    Read the article

< Previous Page | 6 7 8 9 10 11  | Next Page >