How to issue a JSON POST request to Spring Data Rest with a JPA relation

25 November 2014 Leave a comment

Lets say we have a class Company which has a relation to a class User

@Entity
@Table(name = "company")
public class Company implements java.io.Serializable {

	private static final long serialVersionUID = 1L;
	
	private Long id;
	private String name;
	private User user;

	public Company() {
	}

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Long getId() {
		return this.id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	@Column(name = "name", nullable = false, length = 200)
	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@ManyToOne(fetch = FetchType.LAZY, optional = false, targetEntity=my.example.User.class)
	@JoinColumn(name = "user_id")
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

and their corresponding repositories:

@RepositoryRestResource(collectionResourceRel = "company", path = "company")
public interface CompanyRepository extends JpaRepository<Company, Long>  {
}

@RepositoryRestResource(collectionResourceRel = "user", path = "user")
public interface UserRepository extends JpaRepository<User, Long> {

}

In order to add a user to the company (let’s say we want to link this company to the user with id of 2) you will need to issue the following JSON request to the company repository:

{
"name" : "a company name",
"user" : "http://localhost:8086/user/2"
}

The “user” variable should be the URL that is pointing to the user repository.

Categories: Java, Spring, Spring Data Rest Tags: ,

Yet another WTF moment

4 June 2014 4 comments
boolean found = false;
for (int pr=0; pr<promotions.length; pr++) {
    Promotion promotion = promotions[pr];
    if (promotion!=null && promotion.getName().equals(""+availablePromotions[pr][a1].getPackageId())) {
        externalPromotions[pr] = externalPromotions[pr];    // WTF!!! Assigning a value to itself.
        found = true;  // Not sure what this is
        break;
    }
}
found = false;  // As soon as the loop exits this goes back to false again. WTF!!!

The above is an actual snippet of code from a production system (the comments are mine). And yes, I am serious.

Categories: WTF

How to call a web service from Android

24 May 2014 Leave a comment

By far the easiest way is to use the ksoap2-android API. You need the ksoap2 jar file (with all dependencies) which can be found here and you need to add this to your classpath. In the following sample code we call a free web service, called currency convertor, which has one operation (method) that is is called ConversionRate. If you look at the service dscription (the WSDL file), you will see that this operation takes two parameters, FromCurrency and ToCurrency. Lets say that we want to find out the conversion rate from USD to EUR. We implement the following Activity

package gr.panos.caller;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class ConvertorCaller extends Activity {

	public final static String URL = "http://www.webservicex.net/CurrencyConvertor.asmx";
	public static final String NAMESPACE = "http://www.webserviceX.NET/";
	public static final String SOAP_ACTION = "http://www.webserviceX.NET/ConversionRate";
	private static final String METHOD = "ConversionRate";
	private TextView textView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_convertor_caller);
		textView = (TextView) findViewById(R.id.textView1);
		AsyncTaskRunner runner = new AsyncTaskRunner();
		runner.execute();
	}

	 private class AsyncTaskRunner extends AsyncTask<String, String, String>{

		 private String resp;

		@Override
		protected String doInBackground(String... params) {
		     try {
		      SoapObject request = new SoapObject(NAMESPACE, METHOD);
		      request.addProperty("FromCurrency", "USD");
		      request.addProperty("ToCurrency", "EUR");

		      SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		      envelope.dotNet = true;
		      envelope.setOutputSoapObject(request);  
		      System.out.println("************ I AM SENDING: " + envelope.bodyOut);
		      
		       HttpTransportSE transport = new HttpTransportSE(URL);
		       try {
		         transport.call(SOAP_ACTION, envelope);
		       } catch (IOException e) {
		         e.printStackTrace();
		       } catch (XmlPullParserException e) {
		         e.printStackTrace();
		     }
		   if (envelope.bodyIn != null) {
			   if (envelope.bodyIn instanceof SoapFault) {
				   String s = ((SoapFault) envelope.bodyIn).faultstring;
				   System.out.println("************ ERROR: " + s);
				   resp = s;
			   } else if (envelope.bodyIn instanceof SoapObject) {
				   SoapObject obj = ((SoapObject) envelope.bodyIn); 
				   System.out.println("**** RESPONSE: " +obj);
				   
				   SoapPrimitive root = (SoapPrimitive) obj.getProperty(0);
				   System.out.println("**** CONVERSION RATE: " +root.toString());
				   
				   resp = root.toString();
			   }
				   
		   }
		 } catch (Exception e) {
		   e.printStackTrace();
		   resp = e.getMessage();
		 }
	     return resp;
	   }

		  /**
		   * 
		   * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		   */
		  @Override
		  protected void onPostExecute(String result) {
			  textView.setText(resp);
		  }
	
		  /**
		   * 
		   * @see android.os.AsyncTask#onPreExecute()
		   */
		  @Override
		  protected void onPreExecute() {
		  }
		  /**
		   * 
		   * @see android.os.AsyncTask#onProgressUpdate(Progress[])
		   */
		  @Override
		  protected void onProgressUpdate(String... text) {
		  }
	}

}

You also need to define a text view in your layout as well as give the activity INTERNET permission in your manifest file.

And more!

30 January 2014 Leave a comment
if(canBeMultiplied && renewalOfferMultiplier > 0)
    discount = discount * renewalOfferMultiplier;
else
    discount = discount;
Categories: WTF

Even more WTF

29 January 2014 2 comments

And I thought that I had seen everything. But I hadn’t yet seen a wrapper to a String!!

public class OneVariableGenericVO implements java.io.Serializable
{

  private String varName;

  public OneVariableGenericVO()
  {
  }


  public OneVariableGenericVO(String varName)
  {
  	setVarName(varName);
  }

  public String getVarName()
  {
  	return this.varName;
  }

  public void setVarName(String varName)
  {
  	this.varName = varName;
  }

}

SO instead of using a String someone had the brilliant idea to wrap a String into an object and use this instead. What can I say? I am speechless.

Categories: WTF

java.lang.ArrayIndexOutOfBoundsException with EmbeddedLDAP

11 December 2013 Leave a comment

If you forcefully stop the Weblogic Admin Server you might end up with corrupted LDAP files, and your admin server won’t start up with the following exception

####<Dec 7, 2013 2:45:18 AM BST> <Critical> EmbeddedLDAP <AdminServer> <VDE Replication Thread> <<anonymous>> <> <BEA-000000> <java.lang.ArrayIndexOutOfBoundsException
     at com.octetstring.vde.EntryChanges.readBytes(EntryChanges.java:279)
     at com.octetstring.vde.EntryChanges.<init>(EntryChanges.java:72)
     at com.octetstring.vde.replication.BackendChangeLog.getChange(BackendChangeLog.java:548)
     at com.octetstring.vde.replication.Replicator.run(Replicator.java:180)
     at com.octetstring.vde.replication.Replication.run(Replication.java:339)

Before you do anything make sure that you have a copy or you know all the groups and users you have created in your domain.

The solution on Weblogic 7.x was to delete the EmbeddedLDAP.tran file. But with later Weblogic versions this might not work. Another solution is to backup and delete the servers/<admin server>/data/ldap folder. If this still does not work then backup and delete the servers/<admin server>/data folder. This will fix it but once the Admin server is up and running make sure that all the groups and users are still there. If not you will have to recreate all of them manually from the console.

Categories: WebLogic

More WTF!

15 November 2013 Leave a comment
if (true)
{
    if (externalCreditDeposit == 0)
        creditDeposit = internalCreditDeposit;
    else
        creditDeposit = intWeight * internalCreditDeposit + extWeight * externalCreditDeposit;
}

Just to make sure that it will always be executed!

// Variable declaration
        String oldMsisdn = "";
        String newMsisdn = "";
        int rows = 0;
        int cols = 0;
        int tmp = 0;
        int listPtr = 0;

Just to make sure that we know there are variable declarations!

if (request.getParameter("hasBlackberyFromTor")!=null && request.getParameter("hasBlackberyFromTor").equals("1")) {
       
                 
         }else{
        
        
         blackberryExtraPlus  = "-22";
             
         } 

Unnecessary empty if statement.

Categories: Java, WTF
Follow

Get every new post delivered to your Inbox.

Join 44 other followers