Search Results

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

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

  • Android:How to display images from the in a ListView?

    - by Maxood
    Android:How to display images from the web in a ListView?I have the following code to display image from a URL in an ImageView: import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import android.app.ListActivity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.widget.ImageView; public class HttpImgDownload extends ListActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Bitmap bitmap = // DownloadImage( // "http://www.streetcar.org/mim/cable/images/cable-01.jpg"); DownloadImage( "http://s.twimg.com/a/1258674567/images/default_profile_3_normal.png"); ImageView img = (ImageView) findViewById(R.id.img); img.setImageBitmap(bitmap); } private InputStream OpenHttpConnection(String urlString) throws IOException { InputStream in = null; int response = -1; URL url = new URL(urlString); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection"); try{ HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception ex) { throw new IOException("Error connecting"); } return in; } private Bitmap DownloadImage(String URL) { Bitmap bitmap = null; InputStream in = null; try { in = OpenHttpConnection(URL); bitmap = BitmapFactory.decodeStream(in); in.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return bitmap; } } Now how can i display images in an array in a listview? Here's how i want to display the images: http://sites.google.com/site/androideyecontact/_/rsrc/1238086823282/Home/android-eye-contact-lite/eye_contact-list_view_3.png?height=420&width=279

    Read the article

  • Saxon XSLT-Transformation: How to change serialization of an empty tag from <x/> to <x></x>?

    - by Ben
    Hello folks! I do some XSLT-Transformation using Saxon HE 9.2 with the output later being unmarshalled by Castor 1.3.1. The whole thing runs with Java at the JDK 6. My XSLT-Transformation looks like this: <xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns="http://my/own/custom/namespace/for/the/target/document"> <xsl:output method="xml" encoding="UTF-8" indent="no" /> <xsl:template match="/"> <ns:item> <ns:property name="id"> <xsl:value-of select="/some/complicated/xpath" /> </ns:property> <!-- ... more ... --> </xsl:template> So the thing is: if the XPath-expression /some/complicated/xpath evaluates to an empty sequence, the Saxon serializer writes <ns:property/> instead of <ns:property></ns:property>. This, however, confuses the Castor unmarshaller, which is next in the pipeline and which unmarshals the output of the transformation to instances of XSD-generated Java-code. So my question is: How can I tell the Saxon-serializer to output empty tags not as standalone tags? Here is what I am proximately currently doing to execute the transformation: import net.sf.saxon.s9api.*; import javax.xml.transform.*; import javax.xml.transform.sax.SAXSource; // ... // read data XMLReader xmlReader = XMLReaderFactory.createXMLReader(); // ... there is some more setting up the xmlReader here ... InputStream xsltStream = new FileInputStream(xsltFile); InputStream inputStream = new FileInputStream(inputFile); Source xsltSource = new SAXSource(xmlReader, new InputSource(xsltStream)); Source inputSource = new SAXSource(xmlReader, new InputSource(inputStream)); XdmNode input = processor.newDocumentBuilder().build(inputSource); // initialize transformation configuration Processor processor = new Processor(false); XsltCompiler compiler = processor.newXsltCompiler(); compiler.setErrorListener(this); XsltExecutable executable = compiler.compile(xsltSource); Serializer serializer = new Serializer(); serializer.setOutputProperty(Serializer.Property.METHOD, "xml"); serializer.setOutputProperty(Serializer.Property.INDENT, "no"); serializer.setOutputStream(output); // execute transformation XsltTransformer transformer = executable.load(); transformer.setInitialContextNode(input); transformer.setErrorListener(this); transformer.setDestination(serializer); transformer.setSchemaValidationMode(ValidationMode.STRIP); transformer.transform(); I'd appreciate any hint pointing in the direction of a solution. :-) In case of any unclarity I'd be happy to give more details. Nightly greetings from Germany, Benjamin

    Read the article

  • ASP.NET MVC - Appending data onto a file download

    - by aschepis
    what is the best way to append data onto a file download? I figure that i can make my own class that implements InputStream and just consolidates two input streams (the file first, my additional data to append second.) but is there an existing view class that i can use to just return an InputStream or will i have to roll my own view class as well?

    Read the article

  • EAAccessory Notification problem

    - by Deepak
    Hi, I am using a POS device for card swipe. its working good. i have used following codes. (id) init { self = [super init]; if (self != nil) { NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; EAAccessoryManager *accessoryMamaner = [EAAccessoryManager sharedAccessoryManager]; [accessoryMamaner registerForLocalNotifications]; [notificationCenter addObserver: self selector: @selector (accessoryDidConnect:) name: EAAccessoryDidConnectNotification object: nil]; [notificationCenter addObserver: self selector: @selector (accessoryDidDisconnect:) name: EAAccessoryDidDisconnectNotification object: nil]; NSArray *accessories = [accessoryMamaner connectedAccessories]; accessory = nil; session = nil; for (EAAccessory *obj in accessories) { if ([[obj protocolStrings] containsObject:@"com.XXXXX"] || [[obj protocolStrings] containsObject:@"com.YYYYYY"] ) { accessory = obj; break; } } if (accessory) { session = [[EASession alloc] initWithAccessory:accessory forProtocol:@"com.dailysystems.DS247"]; if (!session) session = [[EASession alloc] initWithAccessory:accessory forProtocol:@"com.usaepay.ipos"]; if (session) { self.deviceConnected = YES; [[session inputStream] setDelegate:self]; [[session inputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [[session inputStream] open]; [[session outputStream] setDelegate:self]; [[session outputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [[session outputStream] open]; } else { UIAlertView *accessoryInfo = [[UIAlertView alloc] initWithTitle:@"Alert!" message:@"Hardware is not connected." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [accessoryInfo show]; [accessoryInfo release]; } } } return self; } When i disconnect the accessory it gives me accessoryDidDisconnect and when i connect it gives me accessoryDidConnect, But Problem is after that accessory stop working it does not respond to command. i tried to release the alloc and alloc again but no use. Please tell me if some one have any idea how to get the accessory work again. Thanks in advance.

    Read the article

  • BitmapFactory.decodeStream returning null when options are set.

    - by Robert Foss
    Hi! I'm having issues with BitmapFactory.decodeStream(). When using it without options, it will return an image. But when I use it with options as in .decodeStream(inputStream, null, options) it never returns Bitmaps. What I'm trying to do is to downsample a Bitmap before I actually load it to save memory. I've read some good guides, but none using .decodeStream. Here httpIM:NOT//nornalbion.SPAMcom/blog/?p=143 httpIM:NOT//kfb-android.blogspot.SPAMcom/2009/04/image-processing-in-android.html WORKS JUST FINE InputStream is = connection.getInputStream(); Bitmap img = BitmapFactory.decodeStream(is, null, options); DOESNT WORK InputStream is = connection.getInputStream(); Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, options); Boolean scaleByHeight = Math.abs(options.outHeight - TARGET_HEIGHT) >= Math.abs(options.outWidth - TARGET_WIDTH); if(options.outHeight * options.outWidth * 2 >= 200*100*2){ // Load, scaling to smallest power of 2 that'll get it <= desired dimensions double sampleSize = scaleByHeight ? options.outHeight / TARGET_HEIGHT : options.outWidth / TARGET_WIDTH; options.inSampleSize = (int)Math.pow(2d, Math.floor( Math.log(sampleSize)/Math.log(2d))); System.out.println("Samplesize: " + options.inSampleSize); } // Do the actual decoding options.inJustDecodeBounds = false; //options.inTempStorage = new byte[IMG_BUFFER_LEN]; Bitmap img = BitmapFactory.decodeStream(is, null, options);

    Read the article

  • NAudio Mp3 Playback in Console

    - by Kurru
    Hi I'm trying to make a helper dll that will simplify the NAudio framework into a subset of functions I'm likely to need but I've hit a stumbling block right off the bat. I'm trying to use the following code to play an mp3 but I'm not hearing anything at all. Any help would be appreciated! static WaveOut waveout; static WaveStream playback; static System.Threading.ManualResetEvent wait = new System.Threading.ManualResetEvent(false); static void Main(string[] args) { System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(PlaySong)); t.Start(); wait.WaitOne(); System.Threading.Thread.Sleep(2 * 1000); waveout.Stop(); waveout.Dispose(); playback.Dispose(); } static void PlaySong() { waveout = new WaveOut(); playback = OpenMp3Stream(@"songname.mp3"); waveout.Init(playback); waveout.Play(); Console.WriteLine("Started"); wait.Set(); } private static WaveChannel32 OpenMp3Stream(string fileName) { WaveChannel32 inputStream; WaveStream mp3Reader = new Mp3FileReader(fileName); WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(mp3Reader); WaveStream blockAlignedStream = new BlockAlignReductionStream(pcmStream); inputStream = new WaveChannel32(blockAlignedStream); return inputStream; }

    Read the article

  • NinePatchDrawable from Drawable.createFromPath or FileInputStream

    - by Tim H
    I cannot get a nine patch drawable to work (i.e. it is stretching the nine patch image) when loading from either Drawable.createFromPath or from a number of other methods using an InputStream. Loading the same nine patch works fine when loading from when resources. Here's the methods I am trying: Button b = (Button) findViewById(R.id.Button01); Drawable d = null; //From Resources (WORKS!) d = getResources().getDrawable(R.drawable.test); //From Raw Resources (Doesn't Work) InputStream is = getResources().openRawResource(R.raw.test); d = Drawable.createFromStream(is, null); //From Assets (Doesn't Work) try { InputStream is = getResources().getAssets().open("test.9.png"); d = Drawable.createFromStream(is, null); } catch (Exception e) {e.printStackTrace();} //From FileInputStream (Doesn't Work) try { FileInputStream is = openFileInput("test.9.png"); d = Drawable.createFromStream(is, null); } catch (Exception e) {e.printStackTrace();} //From File path (Doesn't Work) d = Drawable.createFromPath(getFilesDir() + "/test.9.png"); if (d != null) b.setBackgroundDrawable(d);

    Read the article

  • NAudio playback wont stop successfully

    - by Kurru
    Hi When using NAudio to playback an mp3 [in the console], I cant figure out how to stop the playback. When I call waveout.Stop() the code just stops running and waveout.Dispose() never gets called. Is it something to do with the function callback? I dont know how to fix that if it is. static string MP3 = @"song.mp3"; static WaveOut waveout; static WaveStream playback; static void Main(string[] args) { waveout = new WaveOut(WaveCallbackInfo.FunctionCallback()); playback = OpenMp3Stream(MP3); waveout.Init(playback); waveout.Play(); Console.WriteLine("Started"); Thread.Sleep(2 * 1000); Console.WriteLine("Ending"); if (waveout.PlaybackState != PlaybackState.Stopped) waveout.Stop(); Console.WriteLine("Stopped"); waveout.Dispose(); Console.WriteLine("1st dispose"); playback.Dispose(); Console.WriteLine("2nd dispose"); } private static WaveChannel32 OpenMp3Stream(string fileName) { WaveChannel32 inputStream; WaveStream mp3Reader = new Mp3FileReader(fileName); WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(mp3Reader); WaveStream blockAlignedStream = new BlockAlignReductionStream(pcmStream); inputStream = new WaveChannel32(blockAlignedStream); return inputStream; }

    Read the article

  • Swingworker producing duplicate output/output out of order?

    - by Stefan Kendall
    What is the proper way to guarantee delivery when using a SwingWorker? I'm trying to route data from an InputStream to a JTextArea, and I'm running my SwingWorker with the execute method. I think I'm following the example here, but I'm getting out of order results, duplicates, and general nonsense. Here is my non-working SwingWorker: class InputStreamOutputWorker extends SwingWorker<List<String>,String> { private InputStream is; private JTextArea output; public InputStreamOutputWorker(InputStream is, JTextArea output) { this.is = is; this.output = output; } @Override protected List<String> doInBackground() throws Exception { byte[] data = new byte[4 * 1024]; int len = 0; while ((len = is.read(data)) > 0) { String line = new String(data).trim(); publish(line); } return null; } @Override protected void process( List<String> chunks ) { for( String s : chunks ) { output.append(s + "\n"); } } }

    Read the article

  • Android: Unable to make httprequest behind firewall

    - by Yang
    The standard getUrlContent works welll when there is no firewall. But I got exceptions when I try to do it behind a firewall. I've tried to set "http proxy server" in AVD manager, but it didn't work. Any idea how to correctly set it up? protected static synchronized String getUrlContent(String url) throws ApiException { if(url.equals("try")){ return "thanks"; } if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } // Create client and set our specific user-agent string HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); request.setHeader("User-Agent", sUserAgent); try { HttpResponse response = client.execute(request); // Check if server response is valid StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HTTP_STATUS_OK) { throw new ApiException("Invalid response from server: " + status.toString()); } // Pull content stream from response HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } // Return result from buffered stream return new String(content.toByteArray()); } catch (IOException e) { throw new ApiException("Problem communicating with API", e); } }

    Read the article

  • Pass Variable to Java Method from an Ant Target

    - by user200317
    At the moment I have a .properties file to store settings related to the framework. Example: default.auth.url=http://someserver-at008:8080/ default.screenshots=false default.dumpHTML=false And I have written a class to extract those values and here is the method of that class. public static String getResourceAsStream(String defaultProp) { String defaultPropValue = null; //String keys = null; try { InputStream inputStream = SeleniumDefaultProperties.class.getClassLoader().getResourceAsStream(PROP_FILE); Properties properties = new Properties(); //load the input stream using properties. properties.load(inputStream); defaultPropValue = properties.getProperty(defaultProp); }catch (IOException e) { log.error("Something wrong with .properties file, check the location.", e); } return defaultPropValue; } Throughout the application I use method like follows to just exact property needed, public String getBrowserDefaultCommand() { String bcmd = SeleniumDefaultProperties.getResourceAsStream("default.browser.command"); if(bcmd.equals("")) handleMissingConfigProperties(SeleniumDefaultProperties.getResourceAsStream("default.browser.command")); return bcmd; } But I have not decided do a change to this and use ant and pass a parameter instead of using it from .properties file. I was wondering how could I pass a value to a Java Method using ANT. Non of these classes have Main methods and will not have any main. Due to this I was unable to use it as a java system properties. Thanks in advance.

    Read the article

  • XML child node attribute value

    - by c0mrade
    I'm trying to read xml file, ex : <entry> <title>FEED TITLE</title> <id>5467sdad98787ad3149878sasda</id> <tempi type="application/xml"> <conento xmlns="http://mydomainname.com/xsd/radiofeed.xsd" madeIn="USA" /> </tempi> </entry> Here is the code I have so far : public void parseXML(String xml) { try { InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(inputStream); doc.getDocumentElement().normalize(); System.out.println("Root element " + doc.getDocumentElement().getNodeName()); NodeList nodeLst = doc.getElementsByTagName("entry"); System.out.println("Information of all entries"); for (int s = 0; s < nodeLst.getLength(); s++) { Node fstNode = nodeLst.item(s); if (fstNode.getNodeType() == Node.ELEMENT_NODE) { Element fstElmnt = (Element) fstNode; NodeList title = fstElmnt.getElementsByTagName("title").item(0).getChildNodes(); System.out.println("Title : " + ((Node) title.item(0)).getNodeValue()); NodeList id = fstElmnt.getElementsByTagName("id").item(0).getChildNodes(); System.out.println("Id: " + ((Node) update.item(0)).getNodeValue()); NodeList contento= fstElmnt.getElementsByTagName("tempi").item(0).getChildNodes(); System.out.println("Contento : " + ((Node) content.item(0)).getFirstChild().getAttributes()); // with this line above I'm having problems, I get null pointer exception } } } catch (Exception e) { e.printStackTrace(); } } How can I read/get, contento tag attributes? I'm using org.w3c.dom lib.

    Read the article

  • Displaying emails in a JTable (Java Swing)

    - by Paul
    Hi I'm new to all this. I have been trying to display fetched emails in a JTable using the JavaMail add-on. However when I ask the program to set the value it never does. I have been working in NetBeans if that is any help? the fetchMail class finds all may on a server. The gui class is used to display all emails in a table as well as creating mail. You will probably think that I have tried it like a bull in a china shop, I am new to Java and trying to give myself a challenge. Any help/advice would be greatly appreciated fetchMail: package mail; import java.util.; import java.io.; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.mail.; import javax.mail.internet.; import javax.mail.search.; import javax.activation.; public class fetchMail { public void fetch(String username, String pass, String search){ MessagesTableModel tableModel = new MessagesTableModel(); String complete; DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); gui gui = new gui(); // SUBSTITUTE YOUR ISP's POP3 SERVER HERE!!! String host = "imap.gmail.com"; // SUBSTITUTE YOUR USERNAME AND PASSWORD TO ACCESS E-MAIL HERE!!! String user = username; String password = pass; // SUBSTITUTE YOUR SUBJECT SUBSTRING TO SEARCH HERE!!! String subjectSubstringToSearch = search; // Get a session. Use a blank Properties object. Session session = Session.getInstance(new Properties()); Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.imap.socketFactory.fallback", "false"); try { // Get a Store object Store store = session.getStore("imaps"); store.connect(host, user, password); // Get "INBOX" Folder fldr = store.getFolder("INBOX"); fldr.open(Folder.READ_WRITE); int count = fldr.getMessageCount(); System.out.println(count + " total messages"); // Message numebers start at 1 for(int i = 1; i <= count; i++) { // Get a message by its sequence number Message m = fldr.getMessage(i); // Get some headers Date date = m.getSentDate(); int pos = i - 1; String d = df.format(date); Address [] from = m.getFrom(); String subj = m.getSubject(); String mimeType = m.getContentType(); complete = date + "\t" + from[0] + "\t" + subj + "\t" + mimeType; //tableModel.setMessages(m); gui.setDate(d, pos); // System.out.println(d + " " + i); } // Search for e-mails by some subject substring String pattern = subjectSubstringToSearch; SubjectTerm st = new SubjectTerm(pattern); // Get some message references Message [] found = fldr.search(st); System.out.println(found.length + " messages matched Subject pattern \"" + pattern + "\""); for (int i = 0; i < found.length; i++) { Message m = found[i]; // Get some headers Date date = m.getSentDate(); Address [] from = m.getFrom(); String subj = m.getSubject(); String mimeType = m.getContentType(); //System.out.println(date + "\t" + from[0] + "\t" + // subj + "\t" + mimeType); Object o = m.getContent(); if (o instanceof String) { // System.out.println("**This is a String Message**"); // System.out.println((String)o); } else if (o instanceof Multipart) { // System.out.print("**This is a Multipart Message. "); Multipart mp = (Multipart)o; int count3 = mp.getCount(); // System.out.println("It has " + count3 + // " BodyParts in it**"); for (int j = 0; j < count3; j++) { // Part are numbered starting at 0 BodyPart b = mp.getBodyPart(j); String mimeType2 = b.getContentType(); // System.out.println( "BodyPart " + (j + 1) + // " is of MimeType " + mimeType); Object o2 = b.getContent(); if (o2 instanceof String) { // System.out.println("**This is a String BodyPart**"); // System.out.println((String)o2); } else if (o2 instanceof Multipart) { // System.out.print( // "**This BodyPart is a nested Multipart. "); Multipart mp2 = (Multipart)o2; int count2 = mp2.getCount(); // System.out.println("It has " + count2 + // "further BodyParts in it**"); } else if (o2 instanceof InputStream) { // System.out.println( // "**This is an InputStream BodyPart**"); } } //End of for } else if (o instanceof InputStream) { // System.out.println("**This is an InputStream message**"); InputStream is = (InputStream)o; // Assumes character content (not binary images) int c; while ((c = is.read()) != -1) { // System.out.write(c); } } // Uncomment to set "delete" flag on the message //m.setFlag(Flags.Flag.DELETED,true); } //End of for // "true" actually deletes flagged messages from folder fldr.close(true); store.close(); } catch (MessagingException mex) { // Prints all nested (chained) exceptions as well mex.printStackTrace(); } catch (IOException ioex) { ioex.printStackTrace(); } } } gui: /* * gui.java * * Created on 13-May-2010, 18:29:30 */ package mail; import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Vector; import javax.mail.Address; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; public class gui extends javax.swing.JFrame { private MessagesTableModel tableModel; // Table listing messages. private JTable table; String date; /** Creates new form gui */ public gui() { initComponents(); } @SuppressWarnings("unchecked") private void initComponents() { recieve = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); inboxTable = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); recieve.setText("Receve"); recieve.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { recieveActionPerformed(evt); } }); jButton1.setText("new"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); inboxTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "Date", "subject", "sender" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jScrollPane1.setViewportView(inboxTable); inboxTable.getColumnModel().getColumn(0).setResizable(false); inboxTable.getColumnModel().getColumn(1).setResizable(false); inboxTable.getColumnModel().getColumn(2).setResizable(false); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(39, 39, 39) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 558, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(recieve) .addGap(18, 18, 18) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(73, 73, 73)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(31, 31, 31) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(recieve) .addComponent(jButton1)) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(179, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void recieveActionPerformed(java.awt.event.ActionEvent evt) { fetchMail fetch = new fetchMail(); fetch.fetch(email goes here, password goes here, search goes here); } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { createMail create = new createMail(); centerW center = new centerW(); //create.attVis(); center.center(create); create.setVisible(true); } public void setDate(String Date, int pos){ //pos = pos + 1; String [] s = new String [5]; s[pos] = Date; inboxTable.setValueAt(Date, pos, 0); } public String getDate(){ return date; } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new gui().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JTable inboxTable; private javax.swing.JButton jButton1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton recieve; // End of variables declaration }

    Read the article

  • Hibernate - Problem in parsing mapping file (.hbm.xml)

    - by Yatendra Goel
    I am new to Hibernate. I have an exception while running an Hibernate-based application. The exception is as follows: 16 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.3.2.GA 16 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found 16 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist 31 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling 94 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml 94 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml 219 [main] INFO org.hibernate.cfg.Configuration - Reading mappings from resource : app/data/City.hbm.xml 266 [main] ERROR org.hibernate.util.XMLHelper - Error parsing XML: XML InputStream(12) Attribute "coloumn" must be declared for element type "property". 266 [main] ERROR org.hibernate.util.XMLHelper - Error parsing XML: XML InputStream(13) Attribute "coloumn" must be declared for element type "property". 266 [main] ERROR org.hibernate.util.XMLHelper - Error parsing XML: XML InputStream(14) Attribute "coloumn" must be declared for element type "property". It seems that it is not finding coloumn attribute of the property element in the mappings file but my mappings file do have the coloumn attribute. Below is the mappings file (City.hbm.xml) <?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="app.data"> <class name="City" table="CITY"> <id column="CITY_ID" name="cityId"> <generator class="native"/> </id> <property name="cityDisplyaName" coloumn="CITY_DISPLAY_NAME" /> <property coloumn="CITY_MEANINGFUL_NAME" name="cityMeaningFulName" /> <property coloumn="CITY_URL" name="cityURL" /> </class> </hibernate-mapping>

    Read the article

  • Apache HttpClient 4.0. Weird behavior.

    - by Mikhail T
    Hello. I'm using Apache HttpClient 4.0 for my web crawler. The behavior i found strange is: i'm trying to get page via HTTP GET method and getting response about 404 HTTP error. But if i try to get that page using browser it's done successfully. Details: 1. I upload multipart form to server this way: HttpPost httpPost = new HttpPost("http://[host here]/in.php"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("method", new StringBody("post")); entity.addPart("key", new StringBody("223fwe0923fjf23")); FileBody fileBody = new FileBody(new File("photo.jpg"), "image/jpeg"); entity.addPart("file", fileBody); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); HttpEntity result = response.getEntity(); String responseString = ""; if (result != null) { InputStream inputStream = result.getContent(); byte[] buffer = new byte[1024]; while(inputStream.read(buffer) > 0) responseString += new String(buffer); result.consumeContent(); } Uppload succefully ends. I'm getting some results from web server: HttpGet httpGet = new HttpGet("http://[host here]/res.php?key="+myKey+"&action=get&id="+id); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); I'm getting ClientProtocolException while execute method run. I was debugging this situation with log4j. Server answers "404 Not Found". But my browser loads me that page with no problem. Can anybody help me? Thank you.

    Read the article

  • getSystemResourceAsStream() returns null

    - by Hitesh Solanki
    Hiii... I want to get the content of properties file into InputStream class object using getSystemResourceAsStream(). I have built the sample code. It works well using main() method,but when i deploy the project and run on the server, properties file path cannot obtained ... so inputstream object store null value. Sample code is here.. public class ReadPropertyFromFile { public static Logger logger = Logger.getLogger(ReadPropertyFromFile.class); public static String readProperty(String fileName, String propertyName) { String value = null; try { //fileName = "api.properties"; //propertyName = "api_loginid"; System.out.println("11111111...In the read proprty file....."); // ClassLoader loader = ClassLoader.getSystemClassLoader(); InputStream inStream = ClassLoader.getSystemResourceAsStream(fileName); System.out.println("In the read proprty file....."); System.out.println("File Name :" + fileName); System.out.println("instream = "+inStream); Properties prop = new Properties(); try { prop.load(inStream); value = prop.getProperty(propertyName); } catch (Exception e) { logger.warn("Error occured while reading property " + propertyName + " = ", e); return null; } } catch (Exception e) { System.out.println("Exception = " + e); } return value; } public static void main(String args[]) { System.out.println("prop value = " + ReadPropertyFromFile.readProperty("api.properties", "api_loginid")); } }

    Read the article

  • How to handle image/gif type response on client side using GWT

    - by user200340
    Hi all, I have a question about how to handle image/gif type response on client side, any suggestion will be great. There is a service which responds for retrieving image (only one each time at the moment) from database. The code is something like, JDBC Connection Construct MYSQL query. Execute query If has ResultSet, retrieve first one { //save image into Blob image, “img” is the only entity in the image table. image = rs.getBlob("img"); } response.setContentType("image/gif"); //set response type InputStream in = image.getBinaryStream(); //output Blob image to InputStream int bufferSize = 1024; //buffer size byte[] buffer = new byte[bufferSize]; //initial buffer int length =0; //read length data from inputstream and store into buffer while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); //write into ServletOutputStream } in.close(); out.flush(); //write out The code on client side .... imgform.setAction(GWT.getModuleBaseURL() + "serviceexample/ImgRetrieve"); .... ClickListener { OnClick, then imgform.submit(); } formHandler { onSubmit, form validation onSubmitComplete ??????? //handle response, and display image **Here is my question, i had tried Image img = new Image(GWT.getHostPageBaseURL() +"serviceexample/ImgRetrieve"); mg.setSize("300", "300"); imgpanel.add(img); but i only got a non-displayed image with 300X300 size.** } So, how should i handle the responde in this case? Thanks,

    Read the article

  • How can i fetch the large image from url

    - by Kutbi
    i used below code to fetch the image from url.but its not working for large image.. i missing something to add for that type of image to fetch. imgView = (ImageView)findViewById(R.id.ImageView01); imgView.setImageBitmap(loadBitmap("http://www.360technosoft.com/mx4.jpg")); //imgView.setImageBitmap(loadBitmap("http://sugardaddydiaries.com/wp-content/uploads/2010/12/how_do_i_get_sugar_daddy.jpg")); //setImageDrawable("http://sugardaddydiaries.com/wp-content/uploads/2010/12/holding-money-copy.jpg"); //Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png"); //imgView.setImageDrawable(drawable); /* try { ImageView i = (ImageView)findViewById(R.id.ImageView01); Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://sugardaddydiaries.com/wp-content/uploads/2010/12/holding-money-copy.jpg").getContent()); i.setImageBitmap(bitmap); } catch (MalformedURLException e) { System.out.println("hello"); } catch (IOException e) { System.out.println("hello"); }*/ } protected Drawable ImageOperations(Context context, String string, String string2) { // TODO Auto-generated method stub try { InputStream is = (InputStream) this.fetch(string); Drawable d = Drawable.createFromStream(is, "src"); return d; } catch (MalformedURLException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } }

    Read the article

  • Is this a safe way to release resources in Java?

    - by palto
    Usually when code needs some resource that needs to be released I see it done like this: InputStream in = null; try{ in = new FileInputStream("myfile.txt"); doSomethingWithStream(in); }finally{ if(in != null){ in.close(); } } What I don't like is that you have to initialize the variable to null and after that set it to another value and in the finally block check if the resource was initialized by checking if it is null. If it is not null, it needs to be released. I know I'm nitpicking, but I feel like this could be done cleaner. What I would like to do is this: InputStream in = new FileInputStream("myfile.txt"); try{ doSomethingWithStream(in); }finally{ in.close(); } To my eyes this looks almost as safe as the previous one. If resource initialization fails and it throws an exception, there's nothing to be done(since I didn't get the resource) so it doesn't have to be inside the try block. The only thing I'm worried is if there is some way(I'm not Java certified) that an exception or error can be thrown between operations? Even simpler example: Inputstream in = new FileInputStream("myfile.txt"); in.close(); Is there any way the stream would be left open that a try-finally block would prevent?

    Read the article

  • Images won't load if they are of high size

    - by Fahim Parkar
    I have created web-application using JSF 2.0 and mysql. I am storing images in DB using MEDIUMBLOB. When I try to load image, I am able to see those images. However if the image size is big (1 MB or more), I can see half or 3/4th image on the browser. Any idea how to overcome this issue? Do I need to set any variable in JSF or MySQL? I know I should have saved the images over disk instead of DB, however this was client requirement. Client wanted to backup data and provide it to someone else and client don't want to backup DB and images also. Edit 1 Do I need to set any variables on mysql like query_cache. Edit 2 When I download same image and put below code it works perfectly. <h:graphicImage value="images/myImage4.png" width="50%" /> Edit 3 code is as below. <h:graphicImage value="DisplayImage?mainID=drawing" /> DisplayImage.java String imgLen = rs1.getString(1); int len = imgLen.length(); byte[] rb = new byte[len]; InputStream readImg = rs1.getBinaryStream(1); InputStream inputStream = readImg; int index = readImg.read(rb, 0, len); response.reset(); response.setHeader("Content-Length", String.valueOf(len)); response.setHeader("Content-disposition", "inline;filename=/file.png"); response.setContentType("image/png"); response.getOutputStream().write(rb, 0, len); response.getOutputStream().flush(); When I print len I get value as len=1548432

    Read the article

  • Android: OutOfMemoryError while uploading video...

    - by AP257
    Hi all, I have the same problem as described here, but I will supply a few more details. While trying to upload a video in Android, I'm reading it into memory, and if the video is large I get an OutOfMemoryError. Here's my code: // get bytestream to upload videoByteArray = getBytesFromFile(cR, fileUriString); public static byte[] getBytesFromFile(ContentResolver cR, String fileUriString) throws IOException { Uri tempuri = Uri.parse(fileUriString); InputStream is = cR.openInputStream(tempuri); byte[] b3 = readBytes(is); is.close(); return b3; } public static byte[] readBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); // this is storage overwritten on each iteration with bytes int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { byteBuffer.write(buffer, 0, len); } return byteBuffer.toByteArray(); } And here's the traceback (the error is thrown on the byteBuffer.write(buffer, 0, len) line): 04-08 11:56:20.456: ERROR/dalvikvm-heap(6088): Out of memory on a 16775184-byte allocation. 04-08 11:56:20.456: INFO/dalvikvm(6088): "IntentService[UploadService]" prio=5 tid=17 RUNNABLE 04-08 11:56:20.456: INFO/dalvikvm(6088): | group="main" sCount=0 dsCount=0 s=N obj=0x449a3cf0 self=0x38d410 04-08 11:56:20.456: INFO/dalvikvm(6088): | sysTid=6119 nice=0 sched=0/0 cgrp=default handle=4010416 04-08 11:56:20.456: INFO/dalvikvm(6088): at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:~93) 04-08 11:56:20.456: INFO/dalvikvm(6088): at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:218) 04-08 11:56:20.456: INFO/dalvikvm(6088): at com.android.election2010.UploadService.readBytes(UploadService.java:199) 04-08 11:56:20.456: INFO/dalvikvm(6088): at com.android.election2010.UploadService.getBytesFromFile(UploadService.java:182) 04-08 11:56:20.456: INFO/dalvikvm(6088): at com.android.election2010.UploadService.doUploadinBackground(UploadService.java:118) 04-08 11:56:20.456: INFO/dalvikvm(6088): at com.android.election2010.UploadService.onHandleIntent(UploadService.java:85) 04-08 11:56:20.456: INFO/dalvikvm(6088): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:30) 04-08 11:56:20.456: INFO/dalvikvm(6088): at android.os.Handler.dispatchMessage(Handler.java:99) 04-08 11:56:20.456: INFO/dalvikvm(6088): at android.os.Looper.loop(Looper.java:123) 04-08 11:56:20.456: INFO/dalvikvm(6088): at android.os.HandlerThread.run(HandlerThread.java:60) 04-08 11:56:20.467: WARN/dalvikvm(6088): threadid=17: thread exiting with uncaught exception (group=0x4001b180) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): Uncaught handler: thread IntentService[UploadService] exiting due to uncaught exception 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): java.lang.OutOfMemoryError 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:93) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:218) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at com.android.election2010.UploadService.readBytes(UploadService.java:199) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at com.android.election2010.UploadService.getBytesFromFile(UploadService.java:182) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at com.android.election2010.UploadService.doUploadinBackground(UploadService.java:118) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at com.android.election2010.UploadService.onHandleIntent(UploadService.java:85) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:30) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at android.os.Handler.dispatchMessage(Handler.java:99) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at android.os.Looper.loop(Looper.java:123) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at android.os.HandlerThread.run(HandlerThread.java:60) 04-08 11:56:20.496: INFO/Process(4657): Sending signal. PID: 6088 SIG: 3 I guess that as @DroidIn suggests, I need to upload it in chunks. But (newbie question alert) does that mean that I should make multiple PostMethod requests, and glue the file together at the server end? Or can I load the bytestream into memory in chunks, and glue it together in the Android code? If anyone could give me a clue as to the best approach, I would be very grateful.

    Read the article

  • Android: OutOfMemoryError while uploading video - how best to chunk?

    - by AP257
    Hi all, I have the same problem as described here, but I will supply a few more details. While trying to upload a video in Android, I'm reading it into memory, and if the video is large I get an OutOfMemoryError. Here's my code: // get bytestream to upload videoByteArray = getBytesFromFile(cR, fileUriString); public static byte[] getBytesFromFile(ContentResolver cR, String fileUriString) throws IOException { Uri tempuri = Uri.parse(fileUriString); InputStream is = cR.openInputStream(tempuri); byte[] b3 = readBytes(is); is.close(); return b3; } public static byte[] readBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); // this is storage overwritten on each iteration with bytes int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { byteBuffer.write(buffer, 0, len); } return byteBuffer.toByteArray(); } And here's the traceback (the error is thrown on the byteBuffer.write(buffer, 0, len) line): 04-08 11:56:20.456: ERROR/dalvikvm-heap(6088): Out of memory on a 16775184-byte allocation. 04-08 11:56:20.456: INFO/dalvikvm(6088): "IntentService[UploadService]" prio=5 tid=17 RUNNABLE 04-08 11:56:20.456: INFO/dalvikvm(6088): | group="main" sCount=0 dsCount=0 s=N obj=0x449a3cf0 self=0x38d410 04-08 11:56:20.456: INFO/dalvikvm(6088): | sysTid=6119 nice=0 sched=0/0 cgrp=default handle=4010416 04-08 11:56:20.456: INFO/dalvikvm(6088): at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:~93) 04-08 11:56:20.456: INFO/dalvikvm(6088): at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:218) 04-08 11:56:20.456: INFO/dalvikvm(6088): at com.android.election2010.UploadService.readBytes(UploadService.java:199) 04-08 11:56:20.456: INFO/dalvikvm(6088): at com.android.election2010.UploadService.getBytesFromFile(UploadService.java:182) 04-08 11:56:20.456: INFO/dalvikvm(6088): at com.android.election2010.UploadService.doUploadinBackground(UploadService.java:118) 04-08 11:56:20.456: INFO/dalvikvm(6088): at com.android.election2010.UploadService.onHandleIntent(UploadService.java:85) 04-08 11:56:20.456: INFO/dalvikvm(6088): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:30) 04-08 11:56:20.456: INFO/dalvikvm(6088): at android.os.Handler.dispatchMessage(Handler.java:99) 04-08 11:56:20.456: INFO/dalvikvm(6088): at android.os.Looper.loop(Looper.java:123) 04-08 11:56:20.456: INFO/dalvikvm(6088): at android.os.HandlerThread.run(HandlerThread.java:60) 04-08 11:56:20.467: WARN/dalvikvm(6088): threadid=17: thread exiting with uncaught exception (group=0x4001b180) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): Uncaught handler: thread IntentService[UploadService] exiting due to uncaught exception 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): java.lang.OutOfMemoryError 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:93) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:218) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at com.android.election2010.UploadService.readBytes(UploadService.java:199) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at com.android.election2010.UploadService.getBytesFromFile(UploadService.java:182) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at com.android.election2010.UploadService.doUploadinBackground(UploadService.java:118) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at com.android.election2010.UploadService.onHandleIntent(UploadService.java:85) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:30) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at android.os.Handler.dispatchMessage(Handler.java:99) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at android.os.Looper.loop(Looper.java:123) 04-08 11:56:20.467: ERROR/AndroidRuntime(6088): at android.os.HandlerThread.run(HandlerThread.java:60) 04-08 11:56:20.496: INFO/Process(4657): Sending signal. PID: 6088 SIG: 3 I guess that as @DroidIn suggests, I need to upload it in chunks. But (newbie question alert) does that mean that I should make multiple PostMethod requests, and glue the file together at the server end? Or can I load the bytestream into memory in chunks, and glue it together in the Android code? If anyone could give me a clue as to the best approach, I would be very grateful.

    Read the article

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