Search Results

Search found 89 results on 4 pages for 'bytearrayoutputstream'.

Page 3/4 | < Previous Page | 1 2 3 4  | Next Page >

  • final transient fields and serialization

    - by doublep
    Is it possible to have final transient fields that are set to any non-default value after serialization in Java? My usecase is a cache variable — that's why it is transient. I also have a habit of making Map fields that won't be changed (i.e. contents of the map is changed, but object itself remains the same) final. However, these attributes seem to be contradictory — while compiler allows such a combination, I cannot have the field set to anything but null after unserialization. I tried the following, without success: simple field initialization (shown in the example): this is what I normally do, but the initialization doesn't seem to happen after unserialization; initialization in constructor (I believe this is semantically the same as above though); assigning the field in readObject() — cannot be done since the field is final. In the example cache is public only for testing. import java.io.*; import java.util.*; public class test { public static void main (String[] args) throws Exception { X x = new X (); System.out.println (x + " " + x.cache); ByteArrayOutputStream buffer = new ByteArrayOutputStream (); new ObjectOutputStream (buffer).writeObject (x); x = (X) new ObjectInputStream (new ByteArrayInputStream (buffer.toByteArray ())).readObject (); System.out.println (x + " " + x.cache); } public static class X implements Serializable { public final transient Map <Object, Object> cache = new HashMap <Object, Object> (); } } Output: test$X@1a46e30 {} test$X@190d11 null

    Read the article

  • Real Time Sound Captureing J2ME

    - by Abdul jalil
    i am capturing sound in J2me and send these bytes to remote system, i then play these bytes on remote system.five second voice is capture and send to remote system. i get the repeated sound again .i am making a sound messenger please help me where i am doing wrong i am using the follown code . String remoteTimeServerAddress="192.168.137.179"; sc = (SocketConnection) Connector.open("socket://"+remoteTimeServerAddress+":13"); p = Manager.createPlayer("capture://audio?encoding=pcm&rate=11025&bits=16&channels=1"); p.realize(); RecordControl rc = (RecordControl)p.getControl("RecordControl"); ByteArrayOutputStream output = new ByteArrayOutputStream(); OutputStream outstream =sc.openOutputStream(); rc.setRecordStream(output); rc.startRecord(); p.start(); int size=output.size(); int offset=0; while(true) { Thread.currentThread().sleep(5000); rc.commit(); output.flush(); size=output.size(); if(size0) { recordedSoundArray=output.toByteArray(); outstream.write(recordedSoundArray,0,size); } output.reset(); rc.reset(); rc.setRecordStream(output); rc.startRecord(); }

    Read the article

  • Dynamic loading a class in java with a different package name

    - by C. Ross
    Is it possible to load a class in Java and 'fake' the package name/canonical name of a class? I tried doing this, the obvious way, but I get a "class name doesn't match" message in a ClassDefNotFoundException. The reason I'm doing this is I'm trying to load an API that was written in the default package so that I can use it directly without using reflection. The code will compile against the class in a folder structure representing the package and a package name import. ie: ./com/DefaultPackageClass.class // ... import com.DefaultPackageClass; import java.util.Vector; // ... My current code is as follows: public Class loadClass(String name) throws ClassNotFoundException { if(!CLASS_NAME.equals(name)) return super.loadClass(name); try { URL myUrl = new URL(fileUrl); URLConnection connection = myUrl.openConnection(); InputStream input = connection.getInputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int data = input.read(); while(data != -1){ buffer.write(data); data = input.read(); } input.close(); byte[] classData = buffer.toByteArray(); return defineClass(CLASS_NAME, classData, 0, classData.length); } catch (MalformedURLException e) { throw new UndeclaredThrowableException(e); } catch (IOException e) { throw new UndeclaredThrowableException(e); } }

    Read the article

  • Java: Using GSon incorrectly? (null pointer exception)

    - by Rosarch
    I'm trying to get the hits of a google search from a string of the query. public class Utils { public static int googleHits(String query) throws IOException { String googleAjax = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q="; String json = stringOfUrl(googleAjax + query); JsonObject hits = new Gson().fromJson(json, JsonObject.class); return hits.get("estimatedResultCount").getAsInt(); } public static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); } public static void main(String[] args) throws URISyntaxException, IOException { System.out.println(googleHits("odp")); } } The following exception is thrown: Exception in thread "main" java.lang.NullPointerException at odp.compling.Utils.googleHits(Utils.java:48) at odp.compling.Utils.main(Utils.java:59) What am I doing incorrectly? Should I be defining an entire object for the Json return? That seems excessive, given that all I want to do is get one value. For reference: the returned JSON structure.

    Read the article

  • Java - Image encoding in XML

    - by Hoopla
    Hi everyone, I thought I would find a solution to this problem relatively easily, but here I am calling upon the help from ye gods to pull me out of this conundrum. So, I've got an image and I want to store it in an XML document using Java. I have previously achieved this in VisualBasic by saving the image to a stream, converting the stream to an array, and then VB's xml class was able to encode the array as a base64 string. But, after a couple of hours of scouring the net for an equivalent solution in Java, I've come back empty handed. The only success I have had has been by: import it.sauronsoftware.base64.*; import java.awt.image.BufferedImage; import org.w3c.dom.*; ... BufferedImage img; Element node; ... java.io.ByteArrayOutputStream os = new java.io.ByteArrayOutputStream(); ImageIO.write(img, "png", os); byte[] array = Base64.encode(os.toByteArray()); String ss = arrayToString(array, ","); node.setTextContent(ss); ... private static String arrayToString(byte[] a, String separator) { StringBuffer result = new StringBuffer(); if (a.length > 0) { result.append(a[0]); for (int i=1; i<a.length; i++) { result.append(separator); result.append(a[i]); } } return result.toString(); } Which is okay I guess, but reversing the process to get it back to an image when I load the XML file has proved impossible. If anyone has a better way to encode/decode an image in an XML file, please step forward, even if it's just a link to another thread that would be fine. Cheers in advance, Hoopla.

    Read the article

  • BitmapFactory.decodeFile out of memory with images 2400x2400

    - by alasarr
    I need to send an image from a file to a server. The server request the image in a resolution of 2400x2400. What I'm trying to do is: 1) Get a Bitmap using BitmapFactory.decodeFile using the correct inSampleSize. 2) Compress the image in JPEG with a quality of 40% 3) Encode the image in base64 4) Sent to the server I cannot achieve the first step, it throws an out of memory exception. I'm sure the inSampleSize is correct but I suppose even with inSampleSize the Bitmap is huge (around 30 MB in DDMS). Any ideas how can do it? Can I do these steps without created a bitmap object? I mean doing it on filesystem instead of RAM memory. This is the current code: // The following function calculate the correct inSampleSize Bitmap image = Util.decodeSampledBitmapFromFile(imagePath, width,height); // compressing the image ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 40, baos); // encode image String encodedImage = Base64.encodeToString(baos.toByteArray(),Base64.DEFAULT));

    Read the article

  • How can I get size in bytes of an object sent using RMI?

    - by Lucas Batistussi
    I'm implementing a cache server with MongoDB and ConcurrentHashMap java class. When there are available space to put object in memory, it will put at. Otherwise, the object will be saved in a mongodb database. Is allowed that user specify a size limit in memory (this should not exceed heap size limit obviously!) for the memory cache. The clients can use the cache service connecting through RMI. I need to know the size of each object to verify if a new incoming object can be put into memory. I searched over internet and i got this solution to get size: public long getObjectSize(Object o){ try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(o); oos.close(); return bos.size(); } catch (Exception e) { return Long.MAX_VALUE; } } This solution works very well. But, in terms of memory use doesn't solve my problem. :( If many clients are verifying the object size at same time this will cause stack overflow, right? Well... some people can say: Why you don't get the specific object size and store it in memory and when another object is need to put in memory check the object size? This is not possible because the objects are variable in size. :( Someone can help me? I was thinking in get socket from RMI communication, but I don't know how to do this...

    Read the article

  • Android Mediaplayer: setDataSource issue for downloaded media file

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

    Read the article

  • Apache HttpClient Digest authentication

    - by Milan Jovic
    Hi, Basically what I need to do is to perform digest authentication. First thing I tried is the official example available here. But when I try to execute it(with some small changes, Post instead of the the Get method) I get a org.apache.http.auth.MalformedChallengeException: missing nonce in challange at org.apache.http.impl.auth.DigestScheme.processChallenge(DigestScheme.java:132) When this failed I tried using: DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null), new UsernamePasswordCredentials("<username>", "<password>")); HttpPost post = new HttpPost(URI.create("http://<someaddress>")); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("domain", "<username>")); post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("algorithm", "MD5"); digestAuth.overrideParamter("realm", "http://<someaddress>"); digestAuth.overrideParamter("nonce", Long.toString(new Random().nextLong(), 36)); digestAuth.overrideParamter("qop", "auth"); digestAuth.overrideParamter("nc", "0"); digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce()); Header auth = digestAuth.authenticate(new UsernamePasswordCredentials("<username>", "<password>"), post); System.out.println(auth.getName()); System.out.println(auth.getValue()); post.setHeader(auth); HttpResponse ret = client.execute(post); ByteArrayOutputStream v2 = new ByteArrayOutputStream(); ret.getEntity().writeTo(v2); System.out.println("----------------------------------------"); System.out.println(v2.toString()); System.out.println("----------------------------------------"); System.out.println(ret.getStatusLine().getReasonPhrase()); System.out.println(ret.getStatusLine().getStatusCode()); At first I have only overridden "realm" and "nonce" DigestScheme parameters. But it turned out that PHP script running on the server requires all other params, but no matter if I specify them or not DigestScheme doesn't generate them when I call its authenticate() method. I've been struggling with this for two days, and no luck. Based on everything I think that the cause of the problem is the PHP script. It looks to me that it doesn't send a challenge when app tries to access it unauthorized. Any ideas anyone?

    Read the article

  • png image store in database and retrieve in android 1.5

    - by hany
    hai, I am new to android. I have problem. This is my code but it will not work, the problem is in view binder. Please correct it. // this is my activity package com.android.Fruits2; import java.util.ArrayList; import java.util.HashMap; import android.app.ListActivity; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.widget.SimpleAdapter; import android.widget.SimpleCursorAdapter; import android.widget.SimpleAdapter.ViewBinder; public class Fruits2 extends ListActivity { private DBhelper mDB; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.main); mDB = new DBhelper(this); mDB.Reset(); Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.icon); mDB.createPersonEntry(new PersonData(img, "Harsha", 24,"mca")); String[] columns = {mDB.KEY_ID, mDB.KEY_IMG, mDB.KEY_NAME, mDB.KEY_AGE, mDB.KEY_STUDY}; String table = mDB.PERSON_TABLE; Cursor c = mDB.getHandle().query(table, columns, null, null, null, null, null); startManagingCursor(c); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.data, c, new String[] {mDB.KEY_IMG, mDB.KEY_NAME, mDB.KEY_AGE, mDB.KEY_STUDY}, new int[] {R.id.img, R.id.name, R.id.age,R.id.study}); adapter.setViewBinder( new MyViewBinder()); setListAdapter(adapter); } } //my viewbinder package com.android.Fruits2; import android.database.Cursor; import android.graphics.BitmapFactory; import android.view.View; import android.widget.ImageView; import android.widget.SimpleCursorAdapter; public class MyViewBinder implements SimpleCursorAdapter.ViewBinder { public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if( (view instanceof ImageView) ) { ImageView iv = (ImageView) view; byte[] img = cursor.getBlob(columnIndex); iv.setImageBitmap(BitmapFactory.decodeByteArray(img, 0, img.length)); return true; } return false; } } // data package com.android.Fruits2; import android.graphics.Bitmap; public class PersonData { private Bitmap bmp; private String name; private int age; private String study; public PersonData(Bitmap b, String n, int k, String v) { bmp = b; name = n; age = k; study = v; } public Bitmap getBitmap() { return bmp; } public String getName() { return name; } public int getAge() { return age; } public String getStudy() { return study; } } //dbhelper package com.android.Fruits2; import java.io.ByteArrayOutputStream; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.graphics.Bitmap; import android.provider.BaseColumns; public class DBhelper { public static final String KEY_ID = BaseColumns._ID; public static final String KEY_NAME = "name"; public static final String KEY_AGE = "age"; public static final String KEY_STUDY = "study"; public static final String KEY_IMG = "image"; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; private static final String DATABASE_NAME = "PersonalDB"; private static final int DATABASE_VERSION = 1; public static final String PERSON_TABLE = "Person"; private static final String CREATE_PERSON_TABLE = "create table "+PERSON_TABLE+" (" +KEY_ID+" integer primary key autoincrement, " +KEY_IMG+" blob not null, " +KEY_NAME+" text not null , " +KEY_AGE+" integer not null, " +KEY_STUDY+" text not null);"; private final Context mCtx; private boolean opened = false; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_PERSON_TABLE); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+PERSON_TABLE); onCreate(db); } } public void Reset() { openDB(); mDbHelper.onUpgrade(this.mDb, 1, 1); closeDB(); } public DBhelper(Context ctx) { mCtx = ctx; mDbHelper = new DatabaseHelper(mCtx); } private SQLiteDatabase openDB() { if(!opened) mDb = mDbHelper.getWritableDatabase(); opened = true; return mDb; } public SQLiteDatabase getHandle() { return openDB(); } private void closeDB() { if(opened) mDbHelper.close(); opened = false; } public void createPersonEntry(PersonData about) { openDB(); ByteArrayOutputStream out = new ByteArrayOutputStream(); about.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, out); ContentValues cv = new ContentValues(); cv.put(KEY_IMG, out.toByteArray()); cv.put(KEY_NAME, about.getName()); cv.put(KEY_AGE, about.getAge()); cv.put(KEY_STUDY, about.getStudy()); mDb.insert(PERSON_TABLE, null, cv); closeDB(); } } //data.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"> <ImageView android:id = "@+id/img" android:layout_width = "wrap_content" android:layout_height = "wrap_content" > </ImageView> <TextView android:id = "@+id/name" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:textSize="15dp" android:textColor="#ff0000" > </TextView> <TextView android:id = "@+id/age" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:textSize="15dp" android:textColor="#ff0000" /> <TextView android:id = "@+id/study" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:textSize="15dp" android:textColor="#ff0000" /> </LinearLayout> When I run this in android 1.6 and 2.1, it works. But when I run in android 1.5, not work. My application is android 1.5. Please correct and send code to me. Thank you.

    Read the article

  • Java multithreaded server - each connection returns data. Processing on main thread?

    - by oliwr
    I am writing a client with an integrated server that should wait indefinitely for new connections - and handle each on a Thread. I want to process the received byte array in a system wide available message handler on the main thread. However, currently the processing is obviously done on the client thread. I've looked at Futures, submit() of ExecutorService, but as I create my Client-Connections within the Server, the data would be returned to the Server thread. How can I return it from there onto the main thread (in a synchronized packet store maybe?) to process it without blocking the server? My current implementation looks like this: public class Server extends Thread { private int port; private ExecutorService threadPool; public Server(int port) { this.port = port; // 50 simultaneous connections threadPool = Executors.newFixedThreadPool(50); } public void run() { try{ ServerSocket listener = new ServerSocket(this.port); System.out.println("Listening on Port " + this.port); Socket connection; while(true){ try { connection = listener.accept(); System.out.println("Accepted client " + connection.getInetAddress()); connection.setSoTimeout(4000); ClientHandler conn_c= new ClientHandler(connection); threadPool.execute(conn_c); } catch (IOException e) { System.out.println("IOException on connection: " + e); } } } catch (IOException e) { System.out.println("IOException on socket listen: " + e); e.printStackTrace(); threadPool.shutdown(); } } } class ClientHandler implements Runnable { private Socket connection; ClientHandler(Socket connection) { this.connection=connection; } @Override public void run() { try { // Read data from the InputStream, buffered int count; byte[] buffer = new byte[8192]; InputStream is = connection.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); // While there is data in the stream, read it while ((count = is.read(buffer)) > 0) { out.write(buffer, 0, count); } is.close(); out.close(); System.out.println("Disconnect client " + connection.getInetAddress()); connection.close(); // handle the received data MessageHandler.handle(out.toByteArray()); } catch (IOException e) { System.out.println("IOException on socket read: " + e); e.printStackTrace(); } return; } }

    Read the article

  • Complex HashMap has different hashCode after serialization

    - by woezelmann
    I am parsing a xml file into a complex HashMap looking like this: Map<String, Map<String, EcmObject> EcmObject: public class EcmObject implements Comparable, Serializable { private final EcmObjectType type; private final String name; private final List<EcmField> fields; private final boolean pages; // getter, equals, hashCode } EcmObjectType: public enum EcmObjectType implements Serializable { FOLDER, REGISTER, DOCUMENT } EcmField public class EcmField implements Comparable, Serializable { private final EcmFieldDataType dataType; private final EcmFieldControlType controlType; private final String name; private final String dbname; private final String internalname; private final Integer length; // getter, equals, hashCode } EcmFieldDataType public enum EcmFieldDataType implements Serializable { TEXT, DATE, NUMBER, GROUP, DEC; } and EcmFieldControlType public enum EcmFieldControlType implements Serializable{ DEFAULT, CHECKBOX, LIST, DBLIST, TEXTAREA, HIERARCHY, TREE, GRID, RADIO, PAGECONTROL, STATIC; } I have overwritten all hashCode and equal methods by usind commons lang's EqualsBuilder and HashCodeBuilder. Now when I copy a A HashMap this way: Map<String, Map<String, EcmObject>> m = EcmUtil.convertXmlObjectDefsToEcmEntries(new File("e:\\objdef.xml")); Map<String, Map<String, EcmObject>> m2; System.out.println(m.hashCode()); ByteArrayOutputStream baos = new ByteArrayOutputStream(8 * 4096); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(m); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); m2 = (Map<String, Map<String, EcmObject>>) ois.readObject(); System.out.println(m.hashCode()); System.out.println(m2.hashCode()); m.hashCode() is not equal to m2.hashCode() here is my output: -1639352210 -2071553208 1679930154 Another strange thing is, that eg. 10 times m has the same hashcode and suddenly on the 11th time the hashcode is different... Any ideas what this is about?

    Read the article

  • Reusing xalan transformer causing its extension functions break

    - by Leslie Norman
    I am using xalan 2.7.1 to validate my xml docs with xslt style sheet. It works fine for the first document and returns error message in case of error along with correct line and column number of xml source by making use of NodeInfo.lineNumber and NodeInfo.columnNumber extensions. The problem is when I try to reuse transformer to validate other xml docs, it successfully transforms the document but always returns lineNumber=columnNumber=-1 for all errors. Any idea? Here is my code: TransformerFactory tFactory = TransformerFactory.newInstance("org.apache.xalan.processor.TransformerFactoryImpl", null); tFactory.setAttribute(TransformerFactoryImpl.FEATURE_SOURCE_LOCATION, Boolean.TRUE); StreamSource xsltStreamSource = new StreamSource(new File("E:\\Temp\\Test\\myXslt.xsl")); Transformer transformer=null; try { transformer = tFactory.newTransformer(xsltStreamSource); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); File srcFolder = new File("E:\\Temp\\Test"); for (File file :srcFolder.listFiles()) { if (file.getName().endsWith("xml")) { transformer.transform(new StreamSource(file), new StreamResult(outStream)); transformer.reset(); } } System.out.println(outStream.toString()); } catch (TransformerException e) { e.printStackTrace(); } Edit: New code after implementing @rsp suggestions: package mycompany; import java.io.File; import javax.xml.transform.ErrorListener; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.xalan.processor.TransformerFactoryImpl; public class XsltTransformer { public static void main(String[] args) { TransformerFactory tFactory = TransformerFactory.newInstance("org.apache.xalan.processor.TransformerFactoryImpl", null); tFactory.setAttribute(TransformerFactoryImpl.FEATURE_SOURCE_LOCATION, Boolean.TRUE); StreamSource xsltStreamSource = new StreamSource(new File("E:\\Temp\\Test\\myXslt.xsl")); try { Transformer transformer = tFactory.newTransformer(xsltStreamSource); File srcFolder = new File("E:\\Temp\\Test"); for (File file : srcFolder.listFiles()) { if (file.getName().endsWith("xml")) { Source source = new StreamSource(file); StreamResult result = new StreamResult(System.out); XsltTransformer xsltTransformer = new XsltTransformer(); ErrorListenerImpl errorHandler = xsltTransformer.new ErrorListenerImpl(); transformer.setErrorListener(errorHandler); transformer.transform(source, result); if (errorHandler.e != null) { System.out.println("Transformation Exception: " + errorHandler.e.getMessage()); } transformer.reset(); } } } catch (TransformerException e) { e.printStackTrace(); } } private class ErrorListenerImpl implements ErrorListener { public TransformerException e = null; public void error(TransformerException exception) { this.e = exception; } public void fatalError(TransformerException exception) { this.e = exception; } public void warning(TransformerException exception) { this.e = exception; } } }

    Read the article

  • Java: Reading a pdf file from URL into Byte array/ByteBuffer in an applet.

    - by Pol
    I'm trying to figure out why this particular snippet of code isn't working for me. I've got an applet which is supposed to read a .pdf and display it with a pdf-renderer library, but for some reason when I read in the .pdf files which sit on my server, they end up as being corrupt. I've tested it by writing the files back out again. I've tried viewing the applet in both IE and Firefox and the corrupt files occur. Funny thing is, when I trying viewing the applet in Safari (for Windows), the file is actually fine! I understand the JVM might be different, but I am still lost. I've compiled in Java 1.5. JVMs are 1.6. The snippet which reads the file is below. public static ByteBuffer getAsByteArray(URL url) throws IOException { ByteArrayOutputStream tmpOut = new ByteArrayOutputStream(); URLConnection connection = url.openConnection(); int contentLength = connection.getContentLength(); InputStream in = url.openStream(); byte[] buf = new byte[512]; int len; while (true) { len = in.read(buf); if (len == -1) { break; } tmpOut.write(buf, 0, len); } tmpOut.close(); ByteBuffer bb = ByteBuffer.wrap(tmpOut.toByteArray(), 0, tmpOut.size()); //Lines below used to test if file is corrupt //FileOutputStream fos = new FileOutputStream("C:\\abc.pdf"); //fos.write(tmpOut.toByteArray()); return bb; } I must be missing something, and I've been banging my head trying to figure it out. Any help is greatly appreciated. Thanks. Edit: To further clarify my situation, the difference in the file before I read then with the snippet and after, is that the ones I output after reading are significantly smaller than they originally are. When opening them, they are not recognized as .pdf files. There are no exceptions being thrown that I ignore, and I have tried flushing to no avail. This snippet works in Safari, meaning the files are read in it's entirety, with no difference in size, and can be opened with any .pdf reader. In IE and Firefox, the files always end up being corrupted, consistently the same smaller size. I monitored the len variable (when reading a 59kb file), hoping to see how many bytes get read in at each loop. In IE and Firefox, at 18kb, the in.read(buf) returns a -1 as if the file has ended. Safari does not do this. I'll keep at it, and I appreciate all the suggestions so far.

    Read the article

  • How to record / capture audio with RecordControl on Java ME, SE K770i

    - by tomaszs
    I want to record sound on my Java ME App on K770i. So I used this: http://java.sun.com/javame/reference/apis/jsr135/javax/microedition/media/control/RecordControl.html example of RecordControl in my code. It goes like this: import java.util.Vector; import javax.microedition.lcdui.Choice; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.List; import javax.microedition.media.Manager; import javax.microedition.media.MediaException; import javax.microedition.midlet.MIDlet; import java.io.*; import javax.microedition.lcdui.*; import javax.microedition.media.*; import javax.microedition.media.control.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; (...) try { // Create a Player that captures live audio. Player p = Manager.createPlayer("capture://audio"); p.realize(); // Get the RecordControl, set the record stream, // start the Player and record for 5 seconds. RecordControl rc = (RecordControl)p.getControl("RecordControl"); ByteArrayOutputStream output = new ByteArrayOutputStream(); rc.setRecordStream(output); rc.startRecord(); p.start(); Thread.currentThread().sleep(5000); rc.commit(); p.close(); } catch (IOException ioe) { } catch (MediaException me) { } catch (InterruptedException ie) { } But unfortunately when I try to build it, it tells me: *** Creating directories *** *** Compiling source files *** ..\src\example\audiodemo\AudioPlayer.java:121: cannot find symbol symbol : class RecordControl location: class example.audiodemo.AudioPlayer RecordControl rc = (RecordControl)p.getControl("RecordControl"); ^ ..\src\example\audiodemo\AudioPlayer.java:121: cannot find symbol symbol : class RecordControl location: class example.audiodemo.AudioPlayer RecordControl rc = (RecordControl)p.getControl("RecordControl"); ^ 2 errors So my question is: why there is no RecordControl class if in documentations it is written this class should be there. Or is there other method to record / capture audio from microfone in Java ME of Sony Ericsson? How do you record sound?

    Read the article

  • Image rescale and write rescaled image file in blackberry

    - by Karthick
    I am using the following code to resize and save the file in to the blackberry device. After image scale I try to write image file into device. But it gives the same data. (Height and width of the image are same).I have to make rescaled image file.Can anyone help me ??? class ResizeImage extends MainScreen implements FieldChangeListener { private String path="file:///SDCard/BlackBerry/pictures/test.jpg"; private ButtonField btn; ResizeImage() { btn=new ButtonField("Write File"); btn.setChangeListener(this); add(btn); } public void fieldChanged(Field field, int context) { if (field == btn) { try { InputStream inputStream = null; //Get File Connection FileConnection fileConnection = (FileConnection) Connector.open(path); if (fileConnection.exists()) { inputStream = fileConnection.openInputStream(); //byte data[]=inputStream.toString().getBytes(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int j = 0; while((j=inputStream.read()) != -1) { baos.write(j); } byte data[] = baos.toByteArray(); inputStream.close(); fileConnection.close(); WriteFile("file:///SDCard/BlackBerry/pictures/org_Image.jpg",data); EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length); int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()), Fixed32.toFP(80)); int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()), Fixed32.toFP(80)); eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY); WriteFile("file:///SDCard/BlackBerry/pictures/resize.jpg",eImage.getData()); BitmapField bit=new BitmapField(eImage.getBitmap()); add(bit); } } catch(Exception e) { System.out.println("Exception is ==> "+e.getMessage()); } } } void WriteFile(String fileName,byte[] data) { FileConnection fconn = null; try { fconn = (FileConnection) Connector.open(fileName,Connector.READ_WRITE); } catch (IOException e) { System.out.print("Error opening file"); } if (fconn.exists()) try { fconn.delete(); } catch (IOException e) { System.out.print("Error deleting file"); } try { fconn.create(); } catch (IOException e) { System.out.print("Error creating file"); } OutputStream out = null; try { out = fconn.openOutputStream(); } catch (IOException e) { System.out.print("Error opening output stream"); } try { out.write(data); } catch (IOException e) { System.out.print("Error writing to output stream"); } try { fconn.close(); } catch (IOException e) { System.out.print("Error closing file"); } } }

    Read the article

  • Java HTTP Request Occasionally Hangs

    - by behrk2
    Hello Everyone, For the majority of the time, my HTTP Requests work with no problem. However, occasionally they will hang. The code that I am using is set up so that if the request succeeds (with a response code of 200 or 201), then call screen.requestSucceeded(). If the request fails, then call screen.requestFailed(). When the request hangs, however, it does so before one of the above methods are called. Is there something wrong with my code? Should I be using some sort of best practice to prevent any hanging? The following is my code. I would appreciate any help. Thanks! HttpConnection connection = (HttpConnection) Connector.open(url + connectionParameters); connection.setRequestMethod(method); connection.setRequestProperty("WWW-Authenticate", "OAuth realm=api.netflix.com"); if (method.equals("POST")) { connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); } int responseCode = connection.getResponseCode(); System.out.println("RESPONSE CODE: " + responseCode); if (connection instanceof HttpsConnection) { HttpsConnection secureConnection = (HttpsConnection) connection; String issuer = secureConnection.getSecurityInfo() .getServerCertificate().getIssuer(); UiApplication.getUiApplication().invokeLater( new DialogRunner( "Secure Connection! Certificate issued by: " + issuer)); } if (responseCode != 200 && responseCode != 201) { screen.requestFailed("Unexpected response code: " + responseCode); connection.close(); return; } String contentType = connection.getHeaderField("Content-type"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream responseData = connection.openInputStream(); byte[] buffer = new byte[20000]; int bytesRead = 0; while ((bytesRead = responseData.read(buffer)) > 0) { baos.write(buffer, 0, bytesRead); } baos.close(); connection.close(); screen.requestSucceeded(baos.toByteArray(), contentType); } catch (IOException ex) { screen.requestFailed(ex.toString()); }

    Read the article

  • How to send a Java integer in four bytes to another application?

    - by user1468729
    public void routeMessage(byte[] data, int mode) { logger.debug(mode); logger.debug(Integer.toBinaryString(mode)); byte[] message = new byte[8]; ByteBuffer byteBuffer = ByteBuffer.allocate(4); ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); DataOutputStream doStream = new DataOutputStream(baoStream); try { doStream.writeInt(mode); } catch (IOException e) { logger.debug("Error converting mode from integer to bytes.", e); return; } byte [] bytes = baoStream.toByteArray(); bytes[0] = (byte)((mode >>> 24) & 0x000000ff); bytes[1] = (byte)((mode >>> 16) & 0x000000ff); bytes[2] = (byte)((mode >>> 8) & 0x00000ff); bytes[3] = (byte)(mode & 0x000000ff); //bytes = byteBuffer.array(); for (byte b : bytes) { logger.debug(b); } for (int i = 0; i < 4; i++) { //byte tmp = (byte)(mode >> (32 - ((i + 1) * 8))); message[i] = bytes[i]; logger.debug("mode, " + i + ": " + Integer.toBinaryString(message[i])); message[i + 4] = data[i]; } broker.routeMessage(message); } I've tried different ways (as you can see from the commented code) to convert the mode to four bytes to send it via a socket to another application. It works well with integers up to 127 and then again with integers over 256. I believe it has something to do with Java types being signed but don't seem to get it to work. Here are some examples of what the program prints. 127 1111111 0 0 0 127 mode, 0: 0 mode, 1: 0 mode, 2: 0 mode, 3: 1111111 128 10000000 0 0 0 -128 mode, 0: 0 mode, 1: 0 mode, 2: 0 mode, 3: 11111111111111111111111110000000 211 11010011 0 0 0 -45 mode, 0: 0 mode, 1: 0 mode, 2: 0 mode, 3: 11111111111111111111111111010011 306 100110010 0 0 1 50 mode, 0: 0 mode, 1: 0 mode, 2: 1 mode, 3: 110010 How is it suddenly possible for a byte to store 32 bits? How could I fix this?

    Read the article

  • How to detect invalid image URL with JAVA?

    - by Cataclysm
    I have a method to download image from URL. As like below.. public static byte[] downloadImageFromURL(final String strUrl) { InputStream in; ByteArrayOutputStream out = new ByteArrayOutputStream(); try { URL url = new URL(strUrl); in = new BufferedInputStream(url.openStream()); byte[] buf = new byte[2048]; int n = 0; while (-1 != (n = in.read(buf))) { out.write(buf, 0, n); } out.close(); in.close(); } catch (IOException e) { return null; } return out.toByteArray(); } I have an image url and it is valid. for example. https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTxfYM-hnD-Z80tgWdIgQKchKe-MXVUfTpCw1R5KkfJlbRbgr3Zcg My problem is I don't want to download if image is really not exists.Like .... https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTxfYM-hnD-Z80tgWdIgQKchKe-MXVUfTpCw1R5KkfJlbRbgr3Zcgaaaaabbbbdddddddddddddddddddddddddddd This image shouldn't be download by my method. So , how can I know the giving image URL is not really exists. I don't want to validate my URL (I think that may not my solution ). So, I googled for that. From this article ... How to check if a URL exists or returns 404 with Java? and Java check if file exists on remote server using its url But this con.getResponseCode() will always return status code "200". This mean my method will also download invalid image urls. So , I output my bufferStream as like... System.out.println(in.read(buf)); Invalid image URL produces "43". So , I add these lines of codes in my method. if (in.read(buf) == 43) { return null; } It is ok. But I don't think that will always satisfy. Has another way to get it ? am I right? I would really appreciate any suggestions. This problem may struct my head. Thanks for reading my question.

    Read the article

  • Creating a Serializable mock with Mockito error

    - by KwintenP
    I'm trying to create a mock object with Mockito that can be serialized. The object is an interface implementation. When this method is called, I receive an object that I want to pass to another object, hence using the doAnswer(...)-method. This is my code. InterfaceClass obj = mock(InterfaceClass.class, withSettings().serializable()); doAnswer(new Answer<Object>() { public Object answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); //Here I do something with the arguments } }).when(obj).someMethod( any(someObject.class)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeObject(obj); byte[] yourBytes = bos.toByteArray(); } finally { out.close(); bos.close(); } As far as I can tell this should be correct (I'm fairly new to Mockito). But when Serializing my object I get this error: java.io.NotSerializableException: com.trust1t.ocs.signcore.test.InvalidInputTestCase$1 at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1165) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:329) at java.util.concurrent.ConcurrentLinkedQueue.writeObject(ConcurrentLinkedQueue.java:644) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:950) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1482) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1535) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:329) at java.util.LinkedList.writeObject(LinkedList.java:943) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:950) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1482) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1535) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1535) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1535) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1535) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1413) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1159) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:329) at com.trust1t.ocs.signcore.test.InvalidInputTestCase.certificateValidationTest(InvalidInputTestCase.java:117) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) The invalidInputTestCase class is the class containing the test where I'm using this code. It looks as if the mock object references this TestCase somewhere (can't find it though). Am I not correctly implementing this or better ideas to mock?

    Read the article

  • Why can't Java servlet sent out an object ?

    - by Frank
    I use the following method to send out an object from a servlet : public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException { String Full_URL=request.getRequestURL().append("?"+request.getQueryString()).toString(); String Contact_Id=request.getParameter("Contact_Id"); String Time_Stamp=Get_Date_Format(6),query="select from "+Contact_Info_Entry.class.getName()+" where Contact_Id == '"+Contact_Id+"' order by Contact_Id desc"; PersistenceManager pm=null; try { pm=PMF.get().getPersistenceManager(); // note that this returns a list, there could be multiple, DataStore does not ensure uniqueness for non-primary key fields List<Contact_Info_Entry> results=(List<Contact_Info_Entry>)pm.newQuery(query).execute(); Write_Serialized_XML(response.getOutputStream(),results.get(0)); } catch (Exception e) { Send_Email(Email_From,Email_To,"Check_License_Servlet Error [ "+Time_Stamp+" ]",new Text(e.toString()+"\n"+Get_Stack_Trace(e)),null); } finally { pm.close(); } } /** Writes the object and CLOSES the stream. Uses the persistance delegate registered in this class. * @param os The stream to write to. * @param o The object to be serialized. */ public static void writeXMLObject(OutputStream os,Object o) { // Classloader reference must be set since netBeans uses another class loader to loead the bean wich will fail in some circumstances. ClassLoader oldClassLoader=Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(Check_License_Servlet.class.getClassLoader()); XMLEncoder encoder=new XMLEncoder(os); encoder.setExceptionListener(new ExceptionListener() { public void exceptionThrown(Exception e) { e.printStackTrace(); }}); encoder.writeObject(o); encoder.flush(); encoder.close(); Thread.currentThread().setContextClassLoader(oldClassLoader); } private static ByteArrayOutputStream writeOutputStream=new ByteArrayOutputStream(16384); /** Writes an object to XML. * @param out The boject out to write to. [ Will not be closed. ] * @param o The object to write. */ public static synchronized void writeAsXML(ObjectOutput out,Object o) throws IOException { writeOutputStream.reset(); writeXMLObject(writeOutputStream,o); byte[] Bt_1=writeOutputStream.toByteArray(); byte[] Bt_2=new Des_Encrypter().encrypt(Bt_1,Key); out.writeInt(Bt_2.length); out.write(Bt_2); out.flush(); out.close(); } public static synchronized void Write_Serialized_XML(OutputStream Output_Stream,Object o) throws IOException { writeAsXML(new ObjectOutputStream(Output_Stream),o); } At the receiving end the code look like this : File_Url="http://"+Site_Url+App_Dir+File_Name; try { Contact_Info_Entry Online_Contact_Entry=(Contact_Info_Entry)Read_Serialized_XML(new URL(File_Url)); } catch (Exception e) { e.printStackTrace(); } private static byte[] readBuf=new byte[16384]; public static synchronized Object readAsXML(ObjectInput in) throws IOException { // Classloader reference must be set since netBeans uses another class loader to load the bean which will fail under some circumstances. ClassLoader oldClassLoader=Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(Tool_Lib_Simple.class.getClassLoader()); int length=in.readInt(); readBuf=new byte[length]; in.readFully(readBuf,0,length); byte Bt[]=new Des_Encrypter().decrypt(readBuf,Key); XMLDecoder dec=new XMLDecoder(new ByteArrayInputStream(Bt,0,Bt.length)); Object o=dec.readObject(); Thread.currentThread().setContextClassLoader(oldClassLoader); in.close(); return o; } public static synchronized Object Read_Serialized_XML(URL File_Url) throws IOException { return readAsXML(new ObjectInputStream(File_Url.openStream())); } But I can't get the object from the Java app that's on the receiving end, why ? The error messages look like this : java.lang.ClassNotFoundException: PayPal_Monitor.Contact_Info_Entry Continuing ... java.lang.NullPointerException: target should not be null Continuing ... java.lang.NullPointerException: target should not be null Continuing ... java.lang.NullPointerException: target should not be null Continuing ...

    Read the article

  • Read files from directory to create a ZIP hadoop

    - by Félix
    I'm looking for hadoop examples, something more complex than the wordcount example. What I want to do It's read the files in a directory in hadoop and get a zip, so I have thought to collect al the files in the map class and create the zip file in the reduce class. Can anyone give me a link to a tutorial or example than can help me to built it? I don't want anyone to do this for me, i'm asking for a link with better examples than the wordaccount. This is what I have, maybe it's useful for someone public class Testing { private static class MapClass extends MapReduceBase implements Mapper<LongWritable, Text, Text, BytesWritable> { // reuse objects to save overhead of object creation Logger log = Logger.getLogger("log_file"); public void map(LongWritable key, Text value, OutputCollector<Text, BytesWritable> output, Reporter reporter) throws IOException { String line = ((Text) value).toString(); log.info("Doing something ... " + line); BytesWritable b = new BytesWritable(); b.set(value.toString().getBytes() , 0, value.toString().getBytes() .length); output.collect(value, b); } } private static class ReduceClass extends MapReduceBase implements Reducer<Text, BytesWritable, Text, BytesWritable> { Logger log = Logger.getLogger("log_file"); ByteArrayOutputStream bout; ZipOutputStream out; @Override public void configure(JobConf job) { super.configure(job); log.setLevel(Level.INFO); bout = new ByteArrayOutputStream(); out = new ZipOutputStream(bout); } public void reduce(Text key, Iterator<BytesWritable> values, OutputCollector<Text, BytesWritable> output, Reporter reporter) throws IOException { while (values.hasNext()) { byte[] data = values.next().getBytes(); ZipEntry entry = new ZipEntry("entry"); out.putNextEntry(entry); out.write(data); out.closeEntry(); } BytesWritable b = new BytesWritable(); b.set(bout.toByteArray(), 0, bout.size()); output.collect(key, b); } @Override public void close() throws IOException { // TODO Auto-generated method stub super.close(); out.close(); } } /** * Runs the demo. */ public static void main(String[] args) throws IOException { int mapTasks = 20; int reduceTasks = 1; JobConf conf = new JobConf(Prue.class); conf.setJobName("testing"); conf.setNumMapTasks(mapTasks); conf.setNumReduceTasks(reduceTasks); MultipleInputs.addInputPath(conf, new Path("/messages"), TextInputFormat.class, MapClass.class); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(BytesWritable.class); FileOutputFormat.setOutputPath(conf, new Path("/czip")); conf.setMapperClass(MapClass.class); conf.setCombinerClass(ReduceClass.class); conf.setReducerClass(ReduceClass.class); // Delete the output directory if it exists already JobClient.runJob(conf); } }

    Read the article

  • Java.lang.NullPointerException when using retreived Image (Unless method is used statically!)

    - by Emdiesse
    Hi there, This has been doing my head in all day and I have finally decided to resort to asking for help! In my MIDLet I have an instance of the java class ImageFetcher called anImg. Also within my MIDLet I have a command that simply say's fetch, a CommandListener that when detects fetch was clicked runs the function below. This function should simply run public getImage() from the anImg instance of class ImageFetcher which returns an image and then appends/sets this Image onto the form on the display. (You may recognise the getImage() function from the Nokia JavaME Wiki!!!) Instead of any image being displayed this is written to the output terminal in netbeans: Msg: Java.lang.NullPointerException HOWEVER, If I change public getImage() to public static getImage() and replace anImg.getImage() with ImageFetcher.getImage() the image is successfully displayed!!! Thank you for your replies on this issue :) I look forward to going my hair back after this ordeal! FetchImageApp.java ... ... ... private doThis(){ try { Image im; if ((im = anImg.getImage()) != null) { ImageItem ii = new ImageItem(null, im, ImageItem.LAYOUT_DEFAULT, null); // If there is already an image, set (replace) it if (form.size() != 0) { form.set(0, ii); } else // Append the image to the empty form { form.append(ii); } } else { form.append("Unsuccessful download."); } // Display the form with the image display.setCurrent(form); } catch (Exception e) { System.err.println("Msg: " + e.toString()); } } ... ... ... ImageFetcher.java ... ... ... /*-------------------------------------------------- * Open connection and download png into a byte array. *-------------------------------------------------*/ public Image getImage() throws IOException { String url = "http://kenai.com/attachments/wiki_images/chessgame/java-duke-logo.png"; ContentConnection connection = (ContentConnection) Connector.open(url); // * There is a bug in MIDP 1.0.3 in which read() sometimes returns // an invalid length. To work around this, I have changed the // stream to DataInputStream and called readFully() instead of read() // InputStream iStrm = connection.openInputStream(); DataInputStream iStrm = connection.openDataInputStream(); ByteArrayOutputStream bStrm = null; Image im = null; try { // ContentConnection includes a length method byte imageData[]; int length = (int) connection.getLength(); if (length != -1) { imageData = new byte[length]; // Read the png into an array // iStrm.read(imageData); iStrm.readFully(imageData); } else // Length not available... { bStrm = new ByteArrayOutputStream(); int ch; while ((ch = iStrm.read()) != -1) { bStrm.write(ch); } imageData = bStrm.toByteArray(); bStrm.close(); } // Create the image from the byte array im = Image.createImage(imageData, 0, imageData.length); } finally { // Clean up if (iStrm != null) { iStrm.close(); } if (connection != null) { connection.close(); } if (bStrm != null) { bStrm.close(); } } return (im == null ? null : im); } ... ... ...

    Read the article

  • How do I make java wait for boolean to run funciton

    - by TWeeKeD
    I'm sure this is pretty simple but I can't figure out and it sucks I'm up on suck on (what should be) an easy step. ok. I have a method that runs one function that give a response. this method actually handles the uploading of the file so o it takes a second to give a response. I need this response in the following method. sendPicMsg needs to complete and then forward it's response to sendMessage. Please help. b1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(!uploadMsgPic.equalsIgnoreCase("")){ Log.v("response","Pic in storage"); sendPicMsg(); sendMessage(); }else{ sendMessage(); } 1st Method public void sendPicMsg(){ Log.v("response", "sendPicMsg Loaded"); if(!uploadMsgPic.equalsIgnoreCase("")){ final SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", getActivity().MODE_PRIVATE); AsyncHttpClient client3 = new AsyncHttpClient(); RequestParams params3 = new RequestParams(); File file = new File(uploadMsgPic); try { File f = new File(uploadMsgPic.replace(".", "1.")); f.createNewFile(); //Convert bitmap to byte array Bitmap bitmap = decodeFile(file,400); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos); byte[] bitmapdata = bos.toByteArray(); //write the bytes in file FileOutputStream fos = new FileOutputStream(f); fos.write(bitmapdata); params3.put("file", f); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } params3.put("email", preferences.getString("loggedin_user", "")); params3.put("webversion", "1"); client3.post("http://peekatu.com/apiweb/msgPic_upload.php",params3, new AsyncHttpResponseHandler() { @Override public void onSuccess(String response) { Log.v("response", "Upload Complete"); refreshChat(); //responseString = response; Log.v("response","msgPic has been uploaded"+response); //parseChatMessages(response); response=picurl; uploadMsgPic = ""; if(picurl!=null){ Log.v("response","picurl is set"); } if(picurl==null){ Log.v("response", "picurl no ready"); }; } }); sendMessage(); } } 2nd Method public void sendMessage(){ final SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", getActivity().MODE_PRIVATE); if(preferences.getString("Username", "").length()<=0){ editText1.setText(""); Toast.makeText(this.getActivity(), "Please Login to send messages.", 2); return; } AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); if(type.equalsIgnoreCase("3")){ params.put("toid",user); params.put("action", "sendprivate"); }else{ params.put("room", preferences.getString("selected_room", "Adult Lobby")); params.put("action", "insert"); } Log.v("response", "Sending message "+editText1.getText().toString()); params.put("message",editText1.getText().toString() ); params.put("media", picurl); params.put("email", preferences.getString("loggedin_user", "")); params.put("webversion", "1"); client.post("http://peekatu.com/apiweb/messagetest.php",params, new AsyncHttpResponseHandler() { @Override public void onSuccess(String response) { refreshChat(); //responseString = response; Log.v("response", response); //parseChatMessages(response); if(picurl!=null) Log.v("response", picurl); } }); editText1.setText(""); lv.setSelection(adapter.getCount() - 1); }

    Read the article

< Previous Page | 1 2 3 4  | Next Page >