Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Jun 20, 2013

Java: How to get cookie from HttpURLConnection

Here the simple code to get the site response cookie.

URL urlReq = new URL("http://www.google.com");

conn = (HttpURLConnection) urlReq.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(8000);
conn.setConnectTimeout(8000);

// Start building other http request parameter
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:21.0) Gecko/20100101 Firefox/21.0");
conn.setRequestProperty("Accept-Language","en-us,en;q=0.5");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
conn.setRequestProperty("Connection", "close");

conn.setDoOutput(true);
conn.setDoInput(true);

conn.connect();
resCode = conn.getResponseCode(); 
if (resCode==HttpURLConnection.HTTP_OK){
 for(Map.Entry<String, List<String>> headers : conn.getHeaderFields().entrySet()){
 if (headers.getKey().equals("set-cookie")){
      logger.info("\t==>"+headers.getKey());
      for(String hval : headers.getValue()){
       logger.info("\t\t==>"+hval);
      }
 }else{
  logger.info("\t==>"+headers.getKey() +" = "+conn.getHeaderField(headers.getKey()));
 }
}





You can also use
conn.getHeaderField("Set-Cookie")
However, the bad thing is you can one get one cookie, I suggest to use
conn.getHeaderFields()

Happy Reading

Jan 28, 2013

GAE - How to to handle DeadlineExceededException

Before we do. Lets recap how this Exception encounter or what is the cause?

This Exception encounter when a request runtime exceed the 60 sec runtime. Some you are working with loop.


Lets take some example. Somehow you are looping some data and update some properties of every record.


Possible solutions/workaround

Somehow you must have extract servlet the equivalent process to every record. Lets take you have servlet /updateData and /updateDataBackend. You updateDataBackend will process the other data that will possible reach by Deadline. By the use getRemainingMillis() method you can able determine if the extra will be reach by Deadline.



/updateDataBackend

import com.google.apphosting.api.ApiProxy;

...

for(Entity ent : myDataEntities){
  if (ApiProxy.getCurrentEnvironment().getRemainingMillis() > 5000){
     // I think 5 seconds can still do the job
  // Update data
  }else{
    // Opps, It almost reach DeadlineExceededException better create a backend procress
    // for extra data
    //  Please the updateDataBackend to run in backend
  }
}

Hope that helps. Also try to read The_Request_Timer

Happy reading

Dec 12, 2012

GAE- Generate Child Entity key

Here the simple way to make.

ParentEntity.getKey().getChild(ChildKind, keyname);

GAE- The method addFilter(String, Query.FilterOperator, Object) from the type Query is deprecated

In this situation, we can fixed this by changing out code.


Import the Libraries
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.FilterOperator;

Sample:
Query query = new Query(Kind);
query.addFilter("active", FilterOperator.EQUAL, 1l);
query.addFilter("user", FilterOperator.EQUAL, _user);

Solution1:
Filter activeFilter =
  new FilterPredicate("active",FilterOperator.EQUAL,1l);
Filter userFilter =
  new FilterPredicate("user",FilterOperator.EQUAL,_user);

// Combine the Two filter
Filter queryFilter =
  CompositeFilterOperator.and(activeFilter, userFilter);

// Use class Query to assemble a query
Query q = new Query("Person").setFilter(queryFilter);

Solution 2
query = new Query(Kind);
query.setFilter(CompositeFilterOperator.and(
  FilterOperator.EQUAL.of("active", 1l),
  FilterOperator.EQUAL.of("user", _user)
  )
);

If you want look more info you cant find Datastore Queries and GAE Query

Happy Reading

Sep 19, 2012

Java - Convert Staring to Date

Here's simple example how to do.
import java.util.*;
import java.text.*;
public class StringToDate {
  public static void main(String[] args) {
    try {
      String myDate="11-Sept-07";
      DateFormat formatter ; 
      Date date ; 
      // NOTE: myDate value must be same format so that 
      //     it will not get exception error
      formatter = new SimpleDateFormat("dd-MMM-yy");
      date = (Date)formatter.parse(str_date);  
      System.out.println("Today is " +date );
    } catch (ParseException e){
      System.out.println("Exception :"+e);
    }
  }
}

Sep 14, 2012

How to setup alternative on redhat(fedora)/Opensuse?

To view the help and we get more info.
alternatives version 1.3.59 - Copyright (C) 2001 Red Hat, Inc.
This may be freely redistributed under the terms of the GNU Public License.

usage: alternatives --install <link> <name> <path> <priority>
                    [--initscript <service>]
                    [--slave <link> <name> <path>]*
       alternatives --remove <name> <path>
       alternatives --auto <name>
       alternatives --config <name>
       alternatives --display <name>
       alternatives --set <name> <path>

common options: --verbose --test --help --usage --version
                --altdir <directory> --admindir <directory>

Here's the exmaple
root@syntax3rror ~]# /sbin/alternatives --install /usr/bin/java java /opt/jdk1.6.0_23/bin/java 1
[root@syntax3rror ~]# /sbin/alternatives --config java

There are 4 programs which provide 'java'.

  Selection    Command
-----------------------------------------------
*+ 1           /usr/lib/jvm/jre-1.7.0-openjdk/bin/java
   2           /opt/jdk1.6.0_23/bin/java

Enter to keep the current selection[+], or type selection number: 2

INFO: In openSuse the command was update-alternatives

Sep 11, 2012

Struts2 - Iterating List of Map in struts jsp.

Java Object Declaration

Assume that the declaration was on servlet class that the getListMapmethod can access on your JSP file.
public List<Map<String, String>> getListMap(String pRatingCriteria){

  List<Map<String, String>> myList = new ArrayList<Map<String,String>>();
  Map<String, String> myMap = null;

  myMap = new HashMap<String, String>();
  myMap.put("fname", "Winzter");
  myMap.put("lname", "Corpuz");
  myList.add(myMap);


  myMap = new HashMap<String, String>();
  myMap.put("fname", "Winzter");
  myMap.put("lname", "Corpuz");
  myList.add(myMap);


  myMap = new HashMap<String, String>();
  myMap.put("fname", "Juan");
  myMap.put("lname", "Dela Cruz");
  myList.add(myMap);

  return myList;
}

Here your JSP code to iteration the List Map

<s:iterator var="myMap" value="getListMap()" status="rowStatus">
<tr>
  <td><s:property value="key" /></td>
  <td><s:property value="value" />%</td>
</tr>
</s:iterator>

Sep 5, 2012

Sep 4, 2012

Struts - Iteration Map in jsp using Struts

This just one example from.

<logic:iterate id="mapEntry" name="yourHashMap">
  <bean:define id="gift" name="mapEntry" property="value">
  <tr>
    <td><bean:write name="mapEntry" property="key"></td>
    <td><bean:write name="gift" property="productName"></td>
    <td><bean:write name="gift" property="price"></td>
  </tr>
</logic:iterate>
Or maybe like this one.
<s:iterator value="YourListMap" status="stat">
  <tr>
    <th><s:property value="#stat.index"/></th>
    <td><s:property value="key"/></td>
    <td><s:property value="value"/></td>
  </tr>
</s:iterator>
For more example:
  • Sep 1, 2012

    GAE - Truncating Datastore Data

    At this time there were no quick truncate for the Entities. Solution: Create data script in your servlet to delete.
    import com.google.appengine.api.datastore.DatastoreService;
    import com.google.appengine.api.datastore.DatastoreServiceFactory;
    import com.google.appengine.api.datastore.Entity;
    import com.google.appengine.api.datastore.PreparedQuery;
    import com.google.appengine.api.datastore.Query;
    ....
    @SuppressWarnings("serial")
    public class GreetingServiceImpl extends RemoteServiceServlet implements
      GreetingService {
    
      protected void doGet(HttpServletRequest req,
        HttpServletResponse resp)
        throws ServletException, IOException
      {
    
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
          Query query = new Query("YourKind");
          PreparedQuery pq = datastore.prepare(query);
          // Iterate the date
          for (Entity result : pq.asIterable()) {
          Transaction txn = datastore.beginTransaction();
          try {
            datastore.delete(result.getKey());
            txn.commit();
          } finally {
            if (txn.isActive()) {
              txn.rollback();
            }
          } 
        }
    
        }// doGet
    
    }// Class
    
    

    Aug 28, 2012

    Tomcat: Change timezone setting.

    As default tomcat use GMT timezone. To set this one, modify your catalina.sh or starup.sh a the location before the execution of the tomcat boostrap and add data below.
    $JAVA_OPTS="$JAVA_OPTS -Duser.timezone=Asia/Manila"
    Please find the timezone By Continent or in Asia

    Aug 17, 2012

    Java - Iterating Java HashMap Oject

    Let create the Object. HashMap<String, Object> map = new HashMap<String, Object>();
    for (String key : map.keySet()) {
        System.our.println("My HashMap Key"+key);
    }
    If you only need the values, use values():
    for (Object value : map.values()) {
        System.our.println("My HashMap Vaslue"+value.toString()); // I issue toString to convert the object into String value
    }
    Finally, if you want both the key and value, use entrySet():
    for (HashMap.Entry<String, Object> entry : map.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        // ... Print here if you want or do something
    }

    Aug 11, 2012

    GAE - Querying on the Datastore Entity with limit

    Just share this simple statement in querying the Entity With limit. Assume the we want only specific number of report to be retrieve from our entity.
    Query query = new Query(dataStoreKind);
    PreparedQuery pq = datastore.prepare(query);
    Iterable<Entity> users  = pq.asIterable(FetchOptions.Builder.withLimit(30));
    for (Entity user : users) { // Scroll the data
      // user.getKey().getName(); // this how to get the Entity key
       // (Long)user.getProperty("EntityName"); // Get Entity value 
    
    }

    Jun 28, 2012

    Struts - How to access Method from your action class to you JSP file.

    From you action class
    public class YourAction extends ActionSupport{ // NOTE to public this data so you can access in JSP public String name="Winzter"; public String getName() { return this.name; } } // class
    From you JSP file.
    <c:out value="${action.getName()}" escapeXml="false"></c:out>
    If the property name was declare public, you can access by this one.
    <c:out value="${name}" escapeXml="false"></c:out>
    NOTE:${action.getName()} in only working on Tomcat7.x.x.

    Jun 18, 2012

    GAE - Handing Custom Error Page

    Java

    <static-error-handlers>
      <handlerfile="default_error.html" />
      <handlerfile="over_quota.html"error-code="over_quota" />
    </static-error-handlers>
    

    Python

    error_handlers:
     -file:default_error.html
     -error_code:over_quota
      file:over_quota.html
    

    Jun 13, 2012

    GAE - JSON implementation

    Most of us also looking how to implement JSON on GAE. In one blog, posted how and he made it by create a POJO or maybe this was also called entity. Here's the impementation:
    Class Response{
     public enum Status {
      ERROR, OK, WARNING
     }
     private Status status;
     private String message;
    
     public Response(Status status, String message)
     {
      this.status = status;
      this.message = message;
     }
     public String toJson() {
      Gson gson = new Gson();
      String json = gson.toJson(this);
      return json;
     }
     public static Response constructFromJson(String json)
     {
      Gson gson = new Gson();
      return gson.fromJson(json, Response.class);
     }
    }
    Here's how he implement:
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException
    {
     resp.setContentType("text/plain");
     //do your work here
     ...
     PrintWriter out = resp.getWriter();
     Response response = new Response(Response.Status.OK, "A success!");
     out.print(response.toJson());
    }
    
    Here's response looks:
    {“status”:”OK”,”message”:”A success”}

    TODO: Maybe someone ask. What if I want a array. Maybe try to looks at it and see how the implementation. This maybe we create a ArrayList properity or array it self. :) Give credit to nadacode.com

    May 9, 2012

    Struts - Formating Text, Date or Number


    Formating Pattern

    format.time = {0,time}
    format.number = {0,number,#0.0##}
    format.percent = {0,number,##0.00'%'}
    format.money = {0,number,\u00A4##0.00}

    Formatting a number

    <s:property value="getText('{0,number,#,##0.00}',{product.price})" />

    May 2, 2012

    Java: org.hibernate.ObjectNotFoundException: No row with the given identifier exists:

    None-annotated

    <many-to-one name="employee" class="Employee"
    column="CITY_ID" not-null="false" lazy="false" not-found="ignore">
    </many-to-one>
    

    Annotated

    @NotFound(action=NotFoundAction.IGNORE)
    @OneToOne
    @JoinColumn(name="CITY_ID")
    private City city;
    // your getter and setter here
    

    Jan 10, 2012

    Java - JSON Tutorials

    New updated JSON API for java can be found here.
    https://github.com/douglascrockford/JSON-java/blob/master/

    I put this a my reference coz I was use this api before and I was encounter problem on delete record on JSON Array. As googling my problem I found a method remove but not include in my library so I try to find the source again.

    For next time Found problem may be it solve again by updating my API.. :)