My Sites


Thursday, May 28, 2015

Apache Http HttpClient

GET

 HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.dvd-shop.com/getDvd");
HttpResponse response = client.execute(request);

// Get the response
BufferedReader rd = new BufferedReader
  (new InputStreamReader(response.getEntity().getContent()));
   
String line = "";
while ((line = rd.readLine()) != null) {
  textView.append(line);
}

URI uri = new URIBuilder(ConfigurationTest.ADMIN_TOOLS_URL)
                    .addParameter("userID", ConfigurationTest.MLPUser.USERID)
                    .addParameter("time", "5")
                    .addParameter("type", ConfigurationTest.SYNC.ACTIVE_SYNC)
                    .addParameter("semisterId", "")
                    .addParameter("clientId",
                            ConfigurationTest.MLPUser.CLIENTID)
                    .addParameter("clientString",
                            ConfigurationTest.MLPUser.CLIENTSTRING).build();

HttpResponse response = client.execute(post);
ResponseHandler<String> handler = new BasicResponseHandler();
String body = handler.handleResponse(response);
JSONObject object = new JSONObject(body);

object.get("authValue").toString();

POST
 HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://www.dvd-shop.com/login");
    try {
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
      nameValuePairs.add(new BasicNameValuePair("registrationid",
          "20122"));
      post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

      HttpResponse response = client.execute(post);
      BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      String line = "";
      while ((line = rd.readLine()) != null) {
        System.out.println(line);
      }

    } catch (IOException e) {
      e.printStackTrace();
    }

Wednesday, May 27, 2015

Basic HttpURLConnection /JSON parsing tutorial

http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
 (org.json-20120521.jar)
            String result = "";
            String url1 = "http://localhost:8080/getDVDList";
             URL url = new URL(url1);
          
            URL obj = url;
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // optional default is GET
            con.setRequestMethod("GET");

            //add request header
            con.setRequestProperty("User-Agent", "Mozilla/5.0");

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'GET' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            //print result
            result = response.toString();
            // Parse to get translated text



            JSONObject jsonObject = new JSONObject(result);
           JSONArray dvdList = jsonObject.getJSONArray("body");

                        List<Dvd> list = null;
                      
                        if(dvdList != null){
                                 list = new ArrayList<>();
                                 for(int i = 0; i < dvdList.length(); i++){
                                    JSONObject c = dvdList.getJSONObject(i);
                                    Dvd d = new Dvd(c.getInt("code"), c.getString("title"), c.getString("actors"), c.getInt("rating"),c.getString("definiiton"), c.getString("year"));
                                    list.add(d);
                             }

                        }
                       

 2.)

                JSONObject jsonObject = new JSONObject(result);
                int code = jsonObject.getJSONObject("responseCode").getInt("code");

                if (code == 201) {
                    errorLabel.setForeground(Color.BLACK);
                    errorLabel.setText("DVD Successfully Added.");
                } else {
                    errorLabel.setForeground(Color.RED);
                    errorLabel.setText("Adding DVD failed");
                }



3.)      String url1 = "http://localhost:8080/addDVD?title=" + URLEncoder.encode(title, "UTF-8").replace("+", "%20") + "&year=" + year + "&actors=" + URLEncoder.encode(actors, "UTF-8").replace("+", "%20") + "&ratings=" + ratings + "&definitions=" + definitions;
 

   con.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                con.setRequestProperty("Content-Language", "en-US");
                // optional default is GET
                con.setRequestMethod("POST");



 

 URLDecoder.decode (title);

Sunday, May 24, 2015

Hibernate common errors

*org.hibernate.HibernateException: /hibernate.cfg.xml not found
put hibernate.cfg.xml in the src/main/resources

*Caused by: org.hibernate.MappingException: invalid configuration
*Caused by: org.xml.sax.SAXParseException; lineNumber: 3; columnNumber: 25; Document is invalid: no grammar found.

Add this before <hibernate-configuration> tag:
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

Table doesnt exist --> Mysql table name and DAO class name should be equal

org.hibernate.MappingException: Unknown entity
check hibernate cfg file -->  <mapping class="com.dvdshop.model.dao.user"></mapping>

Hibernate Error – Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/dom4j/DocumentException
http://www.mkyong.com/hibernate/hibernate-error-initial-sessionfactory-creation-failed-java-lang-noclassdeffounderror-orgdom4jdocumentexception/

http://www.mkyong.com/hibernate/hibernate-error-initial-sessionfactory-creation-failed-java-lang-noclassdeffounderror-orgdom4jdocumentexception/
hibernate-jpa-2.0-api-1.0.0.Final 

java.lang.ClassNotFoundException : javassist.util.proxy.MethodFilter
http://www.mkyong.com/hibernate/java-lang-classnotfoundexception-javassist-util-proxy-methodfilter/ 

 
 

Thursday, May 21, 2015

Node js Express Session Handlling

http://blog.modulus.io/nodejs-and-express-sessions

var express = require('express');
var app = express();
app.use(express.cookieParser());
app.use(express.session({secret: '1234567890QWERTY'}));
 
app.get('/awesome', function(req, res) {
  req.session.lastPage = '/awesome';
  res.send('Your Awesome.');
});

Wednesday, May 20, 2015

Setup Rabbit MQ on ubuntu

RabbitMQ is open source message broker software (sometimes called message-oriented middleware) that implements the Advanced Message Queuing Protocol (AMQP). The RabbitMQ server is written in the Erlang programming language.Messaging enables software applications to connect and scale. Applications can connect to each other, as components of a larger application, or to user devices and data. Messaging is asynchronous, decoupling applications by separating sending and receiving data.



echo "deb http://www.rabbitmq.com/debian/ testing main"  | sudo tee  /etc/apt/sources.list.d/rabbitmq.list > /dev/null
sudo wget http://www.rabbitmq.com/rabbitmq-signing-key-public.asc
sudo apt-key add rabbitmq-signing-key-public.asc
sudo apt-get update
sudo apt-get install rabbitmq-server -y
sudo service rabbitmq-server start
sudo rabbitmq-plugins enable rabbitmq_management
sudo service rabbitmq-server restart


sudo rabbitmqctl add_user user_name password_for_this_user
sudo rabbitmqctl set_user_tags user_name administrator
sudo rabbitmqctl set_permissions -p / user_name ".*" ".*" ".*"

sudo rabbitmqctl delete_user guest


You can log in to rabbit MQ using http://10.52.82.215:15672/#/queues

Saturday, May 16, 2015

JSTL essentials

<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<c:forEach items="${requestScope.empList}" var="emp">
<c:out value="${emp.id}"></c:out>
<c:out value="${emp.name}"></c:out>
</c:forEach>

JavaBean Requirements

  • It provides a default, no-argument constructor.
  • It should be serializable and implement the Serializable interface.
  • It may have a number of properties which can be read or written.
  • It may have a number of "getter" and "setter" methods for the properties.
Accessing JavaBean from jsp
<jsp:useBean id="students" 
                    class="com.amila.StudentsBean"> 
   <jsp:setProperty name="students" property="firstName" value="Zara"/>
   <jsp:setProperty name="students" property="lastName"  value="Ali"/>
   <jsp:setProperty name="students" property="age" value="10"/>
</jsp:useBean>

Thursday, May 14, 2015

Useful online tools for Dev development

Beautify/ Tree view XML

http://codebeautify.org/xmlviewer
http://codebeautify.org

JSON Viewer

http://jsonlint.com/

SQL vs NOSQL (MongoDB) Queries

 http://docs.mongodb.org/manual/reference/sql-comparison/
http://www.hacksparrow.com/the-mongodb-tutorial.html

string comparison
db.records.find( { "endDate": { $gt: "2015-05-01T00:00:00" ,$lt: "2015-05-18T00:00:00" } } )

ssh -i ~/.ssh/aws.pem ubuntu@10.199.2.187
mongo
use portello
rs status()
show collections
db.Card.count()
db.Card.remove()
db.User.find().pretty()
db.Card.find({'parentId':123}).pretty()

db.User.find({'userId':123}).pretty()

db.Course.find({title:{$regex: /PERF/ }})

db.Course.find({"courseCallNo": {$in : ["123456"]}})

/opt/mongodb/mongodb/bin/mongo localhost:27017/portello -u app_user  -p 123@123

ps -ef | grep mongo

Node.js / Mongo Example

http://blog.modulus.io/mongodb-tutorial
https://www.youtube.com/watch?v=5e1NEdfs4is

Express.js and mongoose