Hello

This is a demo showing Java interacting with Daniweb's new API ( http://www.daniweb.com/api/documentation ) You introduce a member's name and it should show you the total number of posts he has made. Demo is a proof of concept: No bug checking, error checking, etc is in this code.

In order to make this work you need the Jersey library. Download here:

http://jersey.java.net/nonav/documentation/latest/chapter_deps.html#core_client

Any comments, bugs, glitches, etc, please say and Ill look into it.

package DaniWebClient;


import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ws.rs.core.MultivaluedMap;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class DaniWebClient 
{

	
	public static void main(String[] args) 
	{
		/*I prepare the API*/
		Client client = Client.create();
		WebResource webResource = client.resource("http://www.daniweb.com/api/members");
		
		/*User introduces name*/
		System.out.println("Enter the member who's post you want to see: ");
		String user;	 
		Scanner scanIn = new Scanner(System.in);
	    user = scanIn.nextLine();
	    StringBuilder username=new StringBuilder(user);
	    
	    	/*I remove whitespaces except actual spaces*/
	        for (int i=0;i<username.length();i++)
	        {
	        	if ((Character.isWhitespace(username.charAt(i))) && (username.charAt(i)!=' '))
	        			{
	        				username.deleteCharAt(i);
	        			}
	        }
	        user = username.toString();
	        /*For some stupid reason, Java is stupid (no surprise there) and doesnt consider ALT+0160 a whitespace. I have to remove it manually*/
	        user = user.replace("\u00A0","");
	        
	        /*I make sure that the user name isnt empty */
	        if (user.length()==0)
	        {
	        	System.out.println("Please insert a valid member");
	        }
	        else
	        {
	        	
	        	/*I call the members method of the API and pass parameters by GET. POST not tested in Java*/
	        	MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
	    		queryParams.add("username", user);
	    		
	    		/*Send it and wait for reply*/
	    		String output = webResource.queryParams(queryParams).get(String.class);
	
				int first=0;
				int next=0;

				/*Finding where it says the post number in the response...*/
				first=output.indexOf("\"posts\":\"");
				
				if (first==-1) /*-1 means it could not find it therefore no member exists*/
				{
					System.out.println("Member not found!");
				}
				else
				{
					do
					{
						/*I find the next quote that actually begins the post number*/
						next = output.indexOf("\"",Integer.valueOf(first));
						
						/*Not neccesary but in case Dani changes the array to something else....*/
						if (next==-1)
						{
							break;
						}
						
					}while(next==0);
					
					 /*VERY Ugly hack to get posts numbers. Tried with largest post numbers I could find (Dani's AFAIK)*/
					String str2 = output.substring(first, next +15);
					Pattern replace = Pattern.compile("[^.0-9]");
				    Matcher matcher2 = replace.matcher(str2);
				    String stringne=matcher2.replaceAll("");
				    
				    if (output.length()==0)
				    {
				    	System.out.println("Please insert a valid member");
				    }
				    else
				    {
				    	System.out.println("The total amounts of posts this member has is " + stringne );
				    }
	
				}
	
			
	        }

	}

}
 if (user.length()==0)
            {
                System.out.println("Please insert a valid member");
            }

wouldn't

while ( user.length() == 0 ){
  System.out.println("Please insert a valid member");
  }

or

while ( user.isEmpty()){
  System.out.println("Please insert a valid member");
}

be better?

now, I don't really know about this:

/For some stupid reason, Java is stupid (no surprise there) and doesnt consider ALT+0160 a whitespace. I have to remove it manually/

user = user.replace("\u00A0","");

but chances are, that was implemented like that for a reason.
"Java is stupid (no surprise there)", could just as well be you have questions that have very solid answers, yet you don't know them yet.

my advice: don't assume Java is stupid, you 'll be a lot more motivated if you considered it to be a language with parts you don't understand yet.

Comments
This is the correct way to do validation in a production application.

Again, this is a demo app........In a serious app, yes, Id use a while loop until the user actually inserts something valid.

Java is the shittiest language known to man. I hate it to death and I work on it at my workplace daily. If I had time (and knowledge) I would port every known software written in Java to a better language (for example C#).

And Im not even talking about the security issues (which dont really exist if you control your browser settings correctly); Im talking about the language itself.

Edited 3 Years Ago by riahc3

hmm ... again makes me wonder .... getting flagged as bad post, yet no reason stated as to what was "bad" at it.
message to the person who flagged it as being a bad post, since it was a direct answer to the question asked: either inform me why my post is bad, or don't expect any "improvements" in my future replies.

hmm ... again makes me wonder .... getting flagged as bad post, yet no reason stated as to what was "bad" at it.
message to the person who flagged it as being a bad post, since it was a direct answer to the question asked: either inform me why my post is bad, or don't expect any "improvements" in my future replies.

I agree...why was your post flagged down?

I upvoted your post because it truely is not fair that you got downvoted.

Edited 3 Years Ago by riahc3

have no idea, which is why I asked. the best way to give criticism, is to actually let know what it is you're criticizing.

while ( user.length() == 0 ){
    System.out.println("Please insert a valid member");
}

This is the correct way to do validation in a production application.

I don't know why it got voted down, but as a user of a production application I would find that sort of validation highly unpleasant. I object to that being called "the correct way" as though this loop were the best of all possibly ways to ask for valid input in a production application. It is overly insistent and I think most users would mistake it for a bug.

nobody did call it the correct way, or the best way. it was merely a question of mine, whether it wouldn't be "better".
usually when someone starts up the application, they intend to run the logic (in this case, the else block of the original code), for which a valid user is needed.

I'm aware that (even for a simple demo) there should be the possibility to end the program with a certain value (for instance, input = "stop") and that there has to be an actual change of the value of user, but there was no need to code that to ask what I intended to ask.

well ... sure. there are several ways of validation that are way better for a production application, but we were merely talking about a single-class application, that runs in a simple main method, not a JEE project using Spring, Struts, ...

Because Dani hates me, the above is outdated so:

package DaniWebClient;


import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ws.rs.core.MultivaluedMap;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class DaniWebClient 
{


    public static void main(String[] args) 
    {
        /*I prepare the API*/
        Client client = Client.create();
        WebResource webResource = client.resource("http://www.daniweb.com/api/members");

        /*User introduces name*/
        System.out.println("Enter the member who's post you want to see: ");
        String user;     
        Scanner scanIn = new Scanner(System.in);
        user = scanIn.nextLine();
        StringBuilder username=new StringBuilder(user);

            /*I remove whitespaces except actual spaces*/
            for (int i=0;i<username.length();i++)
            {
                if ((Character.isWhitespace(username.charAt(i))) && (username.charAt(i)!=' '))
                        {
                            username.deleteCharAt(i);
                        }
            }
            user = username.toString();
            /*For some stupid reason, Java is stupid (no surprise there) and doesnt consider ALT+0160 a whitespace. I have to remove it manually*/
            user = user.replace("\u00A0","");

            /*I make sure that the user name isnt empty */
            if (user.length()==0)
            {
                System.out.println("Please insert a valid member");
            }
            else
            {

                /*I call the members method of the API and pass parameters by GET. POST not tested in Java*/
                MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
                queryParams.add("username", user);

                /*Send it and wait for reply*/
                String output = webResource.queryParams(queryParams).get(String.class);
                System.out.println(output);

                int first=0;
                int next=0;

                /*Finding where it says the post number in the response...*/
                //first=output.indexOf("\"posts\":\"");
                first=output.indexOf("\"posts_count\":\"");

                if (first==-1) /*-1 means it could not find it therefore no member exists*/
                {
                    System.out.println("Member not found!");
                }
                else
                {
                    do
                    {
                        /*I find the next quote that actually begins the post number*/
                        next = output.indexOf("\"",Integer.valueOf(first));

                        /*Not neccesary but in case Dani changes the array to something else....*/
                        if (next==-1)
                        {
                            break;
                        }

                    }while(next==0);

                     /*VERY Ugly hack to get posts numbers. Tried with largest post numbers I could find (Dani's AFAIK)*/
                    //String str2 = output.substring(first, next +15);
                    String str2 = output.substring(first, next +20);
                    Pattern replace = Pattern.compile("[^.0-9]");
                    Matcher matcher2 = replace.matcher(str2);
                    String stringne=matcher2.replaceAll("");

                    if (output.length()==0)
                    {
                        System.out.println("Please insert a valid member");
                    }
                    else
                    {
                        System.out.println("The total amounts of posts this member has is " + stringne );
                    }

                }


            }

    }

}

There are so many JSON Java libraries that would make returned JSON marshaling so easy and simple to do Jackson, Gson, JSON and in 2 months time you didn't come up with something better...

There are so many JSON Java libraries that would make returned JSON marshaling so easy and simple to do Jackson, Gson, JSON and in 2 months time you didn't come up with something better...

You really did not read the thread did you?

This is a proof of conecept; NOT a real application. It was just made to show how the API interacts with different lanaguages.

This thread was made about 3 months ago and YOU didnt come up with anything, right? So then shut the fuck up :) or make "something better".

@riahc3 to tell moderator shut the up is very stupid as I do not care if you team colleague or not. I made comment after seeing your last post (1 week ago). So cut juicy part from "timely" replies as next time you may not find me in good mood

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.