freshworks / fresh-samples

Samples of code created by freshdesk
184 stars 181 forks source link

Add an example using JavaSE with as few third party dependencies as possible #27

Open ghost opened 8 years ago

ghost commented 8 years ago

The current examples depend on Apache Commons HTTPClient API, Jersey, Glassfish and javax.json (part of JavaEE since its 7th version, can be used separately) whereas only the very last dependency is necessary. Why not providing an example using only JavaSE and javax.json?

At first, you simply create a URL: URL url = new URL("http://YOUR_OWN_DOMAIN.freshdesk.com//helpdesk/tickets/filter/all_tickets?format=json&wf_order=updated_at&wf_order_type=desc&page=0");

Then, you open a connection: HttpURLConnection con = (HttpURLConnection) url.openConnection();

After that, you prepare the connection parameters for the authentication:

con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
String base64encodedApiKey = DatatypeConverter.printBase64Binary(YOUR_FRESHDESK_API_KEY.getBytes(Charset.forName("UTF-8")));
con.setRequestProperty("Authorization", "Basic " + base64encodedApiKey);

Finally, you get the input stream and you try to read the JSON content from it:

InputStream inputStream = con.getInputStream();
JsonReader jsonReader = Json.createReader(inputStream);
JsonArray jsonTicketPageArray = jsonReader.readArray();

Each JsonObject represents a ticket.

N.B: If the returned array is empty, then the page is empty, there is no need to try reading other pages. You can get the error stream when something goes wrong but the provided information isn't worth it, simply catch the IOException. My source code uses the first version of the FreshDesk API. I have decided to report this issue at least to give some information to other developers with similar requirements. Imagine that someone uses JBoss instead of Glassfish, why should we use org.glassfish.jersey.client.authentication.HttpAuthenticationFeature? Best regards.

sudhircirra commented 8 years ago

The V2 API samples are currently dependent only on Apache HTTP client. We can add a sample based on the recommendations you have made.

Also, if you would like to make the changes or add a new Java sample, we would be happy to accept pull requests.

Thanks!

ghost commented 8 years ago

You can use java.nio.charset.StandardCharsets.UTF_8 (requires at least Java 1.7) instead of Charset.forName("utf-8"): https://github.com/freshdesk/fresh-samples/blob/master/JAVA/httpclient4x/src/main/java/com/freshdesk/httpclient4x/CreateTicketWithAttachments.java#L97

I can try to find some spare time to provide 2 examples similar to the new ones but following my "recommendations". If you see no pull request before the end of the week, go ahead.

The new samples are much better IMHO :)