I'm trying to send objects from a server to a rendering client, through a socket. The first list of Entity-objects consists of 8 entities, but many more are added to the list. My server can end up writing hundreds of objects to an ObjectOutputStream, but the client only reads the initial 8.   I have tried calling the flush() both before and after the writeObject method, but this does not seem to make a difference. I have narrowed the problem down to be client-sided.   The server writes an ArrayList to the stream using this method:  private void sendEntities() {     try {         ArrayList&lt;Entity&gt; entities = engine.requestEntities();         System.out.println("Entities sent: " + entities.size());         objectOut.writeObject(entities);         // objectOut.flush(); Does not fix the problem     } catch (IOException e) {         e.printStackTrace();     } }   The client reads and returns the objects to a setter-method that draws the them on the screen, but this is the only area that tries to read objects from the stream.  private ArrayList&lt;Entity&gt; requestEntities() {     try {         out.writeUTF("REQ_ENT()");         // The client only receives 8 entity-objects every time         ArrayList&lt;Entity&gt; entitiesReceived = (ArrayList&lt;Entity&gt;) objectIn.readObject();         in.readUTF();         return entitiesReceived;      } catch (IOException e) {         e.printStackTrace();     } catch (ClassNotFoundException e) {         e.printStackTrace();     }      return null; }   I expected the list of objects read from the inputstream to match the amount of objects written to the outputstream, but the list read from the inputstream stays the same. It works as expected the first time requestEntities() are called, but not on subsequent calls.  EDIT: a link to the github repository has been added  EDIT 2: The ObjectOutputStream sends a reference to a previously sent object, as pointed out by Johannes Kuhn.  I added a line of code that seems to have solved the issue. I make a copy of the entities list, and write this copy to the stream instead.   private void sendEntities() {     try {         ArrayList&lt;Entity&gt; entities = engine.requestEntities();         ArrayList&lt;Entity&gt; copy = new ArrayList&lt;&gt;(entities);         System.out.println("Entities sent: " + entities.size());         objectOut.writeObject(copy);     } catch (IOException e) {         e.printStackTrace();     } }
40009
I have the following code that shows either a bug or a misunderstanding on my part.  I sent the same list, but modified over an ObjectOutputStream.  Once as [0] and other as [1].  But when I read it, I get [0] twice.  I think this is caused by the fact that I am sending over the same object and ObjectOutputStream must be caching them somehow.  Is this work as it should, or should I file a bug?   import java.io.*; import java.net.*; import java.util.*;  public class OOS {      public static void main(String[] args) throws Exception {         Thread t1 = new Thread(new Runnable() {             public void run() {                 try {                     ServerSocket ss = new ServerSocket(12344);                     Socket s= ss.accept();                      ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());                     List same = new ArrayList();                     same.add(0);                     oos.writeObject(same);                     same.clear();                     same.add(1);                     oos.writeObject(same);                  } catch(Exception e) {                     e.printStackTrace();                 }             }         });         t1.start();          Socket s = new Socket("localhost", 12344);         ObjectInputStream ois = new ObjectInputStream(s.getInputStream());          // outputs [0] as expected         System.out.println(ois.readObject());          // outputs [0], but expected [1]         System.out.println(ois.readObject());         System.exit(0);     } }
11442
I have an application that writes information to file. This information is used post-execution to determine pass/failure/correctness of the application. I'd like to be able to read the file as it is being written so that I can do these pass/failure/correctness checks in real time.  I assume it is possible to do this, but what are the gotcha's involved when using Java? If the reading catches up to the writing, will it just wait for more writes up until the file is closed, or will the read throw an exception at this point? If the latter, what do I do then?   My intuition is currently pushing me towards BufferedStreams. Is this the way to go?
1840
I met an interesting issue about C#. I have code like below.  List&lt;Func&lt;int&gt;&gt; actions = new List&lt;Func&lt;int&gt;&gt;();  int variable = 0; while (variable &lt; 5) {     actions.Add(() =&gt; variable * 2);     ++ variable; }  foreach (var act in actions) {     Console.WriteLine(act.Invoke()); }   I expect it to output 0, 2, 4, 6, 8. However, it actually outputs five 10s.  It seems that it is due to all actions referring to one captured variable. As a result, when they get invoked, they all have same output.  Is there a way to work round this limit to have each action instance have its own captured variable?
73774
What's the best way to pipe the output from an java.io.OutputStream to a String in Java?  Say I have the method:    writeToStream(Object o, OutputStream out)   Which writes certain data from the object to the given stream. However, I want to get this output into a String as easily as possible.  I'm considering writing a class like this (untested):  class StringOutputStream extends OutputStream {    StringBuilder mBuf;    public void write(int byte) throws IOException {     mBuf.append((char) byte);   }    public String getString() {     return mBuf.toString();   } }   But is there a better way? I only want to run a test!
19673
I am getting FATAL_ERROR|System.QueryException: List has no rows for assignment to SObject. I know that it is because it is not returning any rows in the SOQL query but what I want is that if it returns any row, it should update ALO field on contact object, if it is null then ALO field should be set to null.  Here is my code:  ziptoLOD = [SELECT Id, Name, LOD__c             FROM Zip_3_to_LOD__c             WHERE Name =: contact.Extract_Zipcode__c ];  Zip_3_to_LOD__c ziptoLOD2 = (ziptoLOD != null) ? ziptoLOD : null;  if (ziptoLOD2 == null) {     contact.ALO__c = ' ';    } else {     System.debug(System.LoggingLevel.ERROR, 'Zip to LOD' + ziptoLOD2);     contact.ALO__c = ziptoLOD2.LOD__c; }   My code gets stuck at the SOQL query and gives me the list has no rows error.
2705
The upsert() DML operation requires a specific List based on a specific sObject type, for instance:List&lt;Account&gt; lstAccount = new List&lt;Account&gt;();   However, we are trying to generate a generic method which allows us to pass by an sObject list containing all data records to be upserted for a specific sObject. An insert() operation allows us to use a List&lt;sObject&gt; to be inserted but the upsert() function is rejecting it:  List&lt;sObject&gt; listWRecords = new List&lt;sObject&gt;(); listWRecords.add(new Foo__c(Name="Record1")); listWRecords.add(new Foo__c(Name="Record2"));  upsert(listWRecords, 'ExternalIdFieldFrom_Foo__c', false);   Which will result in an error saying that the upsert must be performed on a concrete entity type.   Dynamically casting an sObject list is also not possible; I've seen solutions to 'hard code' or create Wrapper classes for each sObject on your org. But we would like to create a generic option here.  Another possibility would be to create some logic mimicking an upsert by splitting it into an update() and an insert() operation. Keeping in mind Salesforce limits, I do not see an option to go this way.
48451
I want to call out my web service after the insert process of a custom object with a delay of 2 minutes. But i am getting that exception FATAL_ERROR|System.CalloutException: Read timed out How can i fix that problem ? Here is my implementation.  Callout class:  public class HttpCallout{     @Future(callout=true)     public static void getContent(String url){         Http h = new Http();          HttpRequest req = new HttpRequest();         req.setEndpoint(url);         req.setMethod('GET');         req.setTimeout(2000);          HttpResponse res = h.send(req);         String response = EncodingUtil.urlDecode(res.getBody(),'UTF-8');         System.debug('***response****'+response);     }      public void serviceCaller(){         getContent(url);     } }   Trigger:  trigger AfterInsertOrUpdate on Sales_Order__c (after insert) {     System.debug('Making future call to update account');     HttpCallout httpCallout = new HttpCallout();     httpCallout.serviceCaller();     System.debug('After Insert'); }   Any help would be appriciated.
9792
Yesterday I had a two-hour technical phone interview (which I passed, woohoo!), but I completely muffed up the following question regarding dynamic binding in Java.  And it's doubly puzzling because I used to teach this concept to undergraduates when I was a TA a few years ago, so the prospect that I gave them misinformation is a little disturbing...  Here's the problem I was given:  /* What is the output of the following program? */  public class Test {    public boolean equals( Test other ) {     System.out.println( "Inside of Test.equals" );     return false;   }    public static void main( String [] args ) {     Object t1 = new Test();     Object t2 = new Test();     Test t3 = new Test();     Object o1 = new Object();      int count = 0;     System.out.println( count++ );// prints 0     t1.equals( t2 ) ;     System.out.println( count++ );// prints 1     t1.equals( t3 );     System.out.println( count++ );// prints 2     t3.equals( o1 );     System.out.println( count++ );// prints 3     t3.equals(t3);     System.out.println( count++ );// prints 4     t3.equals(t2);   } }   I asserted that the output should have been two separate print statements from within the overridden equals() method: at t1.equals(t3) and t3.equals(t3).  The latter case is obvious enough, and with the former case, even though t1 has a reference of type Object, it is instantiated as type Test, so dynamic binding should call the overridden form of the method.  Apparently not.  My interviewer encouraged me to run the program myself, and lo and behold, there was only a single output from the overridden method: at the line t3.equals(t3).  My question then is, why?  As I mentioned already, even though t1 is a reference of type Object (so static binding would invoke Object's equals() method), dynamic binding should take care of invoking the most specific version of the method based on the instantiated type of the reference.  What am I missing?
98762
In a game I'm working on, there's a class responsible for collision detection. It's method detectCollisions(List&lt;Entity&gt; entities) is called from the main gameloop.  The code to update the entities (i.e. where the entities 'act': update their positions, invoke AI, etc) is in a different class, in the method updateEntities(List&lt;Entity&gt; entities). Also called from the gameloop, after the collision detection.  When there's a collision between two entities, usually something needs to be done. For example, zero the velocity of both entities in the collision, or kill one of the entities.  It would be easy to have this code in the CollisionDetector class. E.g. in psuedocode:  for(Entity entityA in entities){     for(Entity entityB in entities){         if(collision(entityA, entityB)){             if(entityA instanceof Robot &amp;&amp; entityB instanceof Robot){                 entityA.setVelocity(0,0);                 entityB.setVelocity(0,0);             }             if(entityA instanceof Missile || entityB instanceof Missile){                 entityA.die();                 entityB.die();             }         }     } }   However, I'm not sure if updating the state of entities in response to collision should be the job of CollisionDetector. Maybe it should be the job of EntityUpdater, which runs after the collision detection in the gameloop.  Is it okay to have the code responding to collisions in the collision detection system? Or should the collision detection class only detect collisions, report them to some other class and have that class affect the state of the entities?
115996
I'm trying to send a Blob Apex REST callout and it is keep failing. I tried all the examples in the web but didn't work. What is the standard and correct way to send Blob data via REST callouts?  //Parameters String strBody = 'flowIdentifier=1&amp;flowFilename=test.jpg&amp;flowTotalSize=14893&amp;flowCurrentChunkSize=14893&amp;flowChunkSize=14893&amp;flowChunkNumber=1&amp;flowTotalChunks=1';  bodyBlob = //Blob data  HttpRequest request = new HttpRequest(); request.setEndpoint(END_POINT); request.setMethod('POST'); request.setHeader('content-type', 'multipart/form-data'); request.setBodyAsBlob(bodyBlob); request.setBody(strBody);  try{ Http http = new Http(); HttpResponse response = http.send(request); System.debug(response.getBody()); } catch(Exception e) {      System.debug('ERROR:'+e);     }
85933
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.  Getting the field names is fairly simple, here is what a co-worker came up with:  public static List initFieldArray(String className) throws ClassNotFoundException {      Class c = Class.forName(className);     Field field[] = c.getFields();     List&lt;String&gt; classFields = new ArrayList(field.length);      for (int i = 0; i &lt; field.length; i++) {         String cf = field[i].toString();         classFields.add(cf.substring(cf.lastIndexOf(".") + 1));     }      return classFields; }   Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.  Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.
80465
I'm creating a game where I have an Entity class that contains basic entity info (pos, health,..) and some functions. Enemies and Player later on inherit from this class.   Public class Entity {  public Vector2 position; public float health; ,...   Lets say that I have a function like this inside the Entity class:  public GameObject movingIntoEnemy(Vector2 movingToPoint) {     foreach (GameObject go in GameObject.Find("GameMap").GetComponent&lt;GameMap&gt;().enemyList)     {         if (go.GetComponent&lt;EnemyScript&gt;().enemy.position == movingToPoint)         {             return go;         }     }     return null; }   This function looks for a GameObject called "GameMap" and then cycles through enemies in it's list. If an enemy is found, it returns it's GameObject. Using GameObject.Find() is pretty ineffective, so what would be a better approach to this? I mean, I can't just easily use  public GameObject GameMap;   since the code is in a class, and this class needs to be instantiated first in my player/enemy scripts.  My question is - how do I attach gameObjects to this class before it is even created? What is the appropriate approach to this? I guess that I might pass these GameObjects to the class through it's constructor, but it would make things much more complicated.   Thanks in advance ;)
13148
I have an application that reads a CSV file with piles of data rows.  I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause OutOfMemoryErrors.  Each row translates into an object.  Is there an easy way to find out the size of that object programmatically?  Is there a reference that defines how large primitive types and object references are for a VM?  Right now, I have code that says read up to 32,000 rows, but I'd also like to have code that says read as many rows as possible until I've used 32MB of memory.  Maybe that is a different question, but I'd still like to know.
31852
Hibernate has a handful of methods that, one way or another, takes your object and puts it into the database. What are the differences between them, when to use which, and why isn't there just one intelligent method that knows when to use what?  The methods that I have identified thus far are:   save() update() saveOrUpdate() saveOrUpdateCopy() merge() persist()
38591
class someclass {};  class base {     int a;     int *pint;     someclass objsomeclass;     someclass* psomeclass; public:     base()     {         objsomeclass = someclass();         psomeclass = new someclass();         pint = new int();          throw "constructor failed";         a = 43;     } }  int main() {     base temp(); }   In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided?  int main() {     base *temp = new base(); }   How about in the above code? How can the memory leaks be avoided after the constructor throws?
55180
So I have a method that takes as a parameter an Id of a object and uses it to make an external callout.  Unfortunately I can't seem to figure out any way to test it.  @isTest static void sometimes_salesforces_sucks() {    My_Object__c foo = new My_Object__c(Name='test');    insert foo;    MyClient client = new MyClient();    MyMockResponseGenerator mockResponse = new MyMockResponseGenerator();    Test.setMock(HttpCalloutMock.class,mockResponse);     Test.startTest();    client.bar(foo.Id);    Test.stopTest(); }    says that using start/stop test should work, but it doesn't work for me
12263
In Java, this code throws an exception when the HTTP result is 404 range:  URL url = new URL("http://stackoverflow.com/asdf404notfound"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.getInputStream(); // throws!   In my case, I happen to know that the content is 404, but I'd still like to read the body of the response anyway.  (In my actual case the response code is 403, but the body of the response explains the reason for rejection, and I'd like to display that to the user.)  How can I access the response body?