Butuh Jawaban ?
Tanyakan disini
http://tanyajawab.evo-training.com
Untuk request penambahan kategori, bisa melakukan request via email di boylevantz@gmail.com
Tag Cloud
accordion
(1)
admin
(1)
administration
(1)
android
(2)
angel love
(2)
answer
(1)
app
(1)
archangel
(2)
auto complete
(1)
axis2 json
(1)
backup
(1)
barcode
(3)
bb
(1)
binary decimal convert c
(1)
blackberry
(9)
boylevantz
(1)
browser error
(1)
c
(1)
C#
(1)
career
(1)
certification
(1)
ci
(1)
codeigniter
(1)
color
(1)
connection
(1)
contenga
(1)
create
(1)
csharp
(1)
css
(1)
database
(2)
db
(1)
demo
(1)
dev
(2)
developer
(2)
download
(1)
eclipse
(1)
enterprise deploy
(1)
eval
(1)
evo
(1)
expression
(2)
facelets
(1)
free
(1)
golden ratio
(1)
grant
(1)
hash md5 encrypt encryption
(1)
heap size
(1)
hibernate
(1)
html
(1)
ibm
(3)
index.php
(1)
installation manager
(1)
ios
(1)
java
(14)
javascript
(3)
jawab
(1)
job
(1)
jquery
(1)
jquery mobile
(2)
js
(2)
jsf
(2)
juel
(1)
kerjaan
(1)
kernel
(1)
language
(1)
launchpad
(1)
linux
(1)
list
(1)
listfield
(1)
location
(1)
log
(1)
log4j
(1)
logging
(1)
lowongan
(1)
magang
(1)
maven
(1)
memory
(1)
message
(1)
mobile
(3)
mysql
(3)
native
(1)
opportunity
(1)
orion
(1)
out of memory
(1)
php
(2)
pin
(1)
pom.xml maven pom sort sortpom mvn
(1)
postgre
(1)
program
(1)
programmer
(2)
programming
(1)
psql
(1)
Q&A
(1)
qrcode barcode java
(1)
question
(1)
remote
(1)
remove index.php
(1)
servlet
(1)
simple
(1)
solusi
(1)
spring
(1)
swap
(1)
tab
(1)
tanya
(1)
tcp rinetd linux suse redirection
(1)
tips
(1)
Tomcat
(1)
tooltip
(1)
training
(1)
ui
(1)
url
(1)
user
(1)
user interface
(1)
vacancy
(3)
web
(4)
webworks
(1)
worklight
(3)
zxing
(1)
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
Thursday, October 24, 2013
Butuh jawaban ?
Labels:
android,
answer,
c,
evo,
java,
jawab,
php,
program,
programmer,
programming,
Q&A,
question,
solusi,
tanya,
training
Saturday, December 15, 2012
Create servlet to serving Download
This tutorial shows how to create a link button on web for "Download". You will need have a servlet on the server side to provide this feature. In the end of this tutorial you will have a download link to download a text file.
Create a servlet
public class DownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
// Set the response content type
response.setContentType("text/plain"); // for text file
response.addHeader("Content-disposition","attachment; filename=yourfilename.txt");
out.print("HELLO");
out.close();
}
}
Register servlet in web.xml
<web-app>
<servlet>
<servlet-name>DownloadServlet</servlet-name>
<servlet-class>com.mycompany.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
</web-app>
Create HTML page
<a href="download">Go to download</a>
Create logging using log4j
Put log4j.properties in your classpath
#Set the level of the root loger to DEBUG and set its appender
log4j.rootCategory=DEBUG, CONSOLE, DAILY
log4j.logger.com.dappit.Dapper.parser=ERROR
log4j.logger.org.w3c.tidy=FATAL
# CONSOLE - Console Appender
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
#set the layout for the appender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%p] %c:%L - %m%n
# FILE - File Appender
#log4j.appender.FILE=org.apache.log4j.FileAppender
#log4j.appender.FILE.File=logs/jlego.log
# Define the layout for file appender
#log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.FILE.layout.conversionPattern=%m%n
# DAILY - DailyRollingFile Appender
log4j.appender.DAILY=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DAILY.File=${catalina.home}/logs/mylog.log
log4j.appender.DAILY.DatePattern='.'yyyy-MM-dd
# Define the layout for DAILY file appender
log4j.appender.DAILY.layout=org.apache.log4j.PatternLayout
log4j.appender.DAILY.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%p] %c:%L - %m%n
# Rolling file appender in HTML
#------------------------------------------------------------------------------
#
# The following properties configure the Rolling File appender in HTML.
# See http://logging.apache.org/log4j/docs/api/index.html for details.
#
#------------------------------------------------------------------------------
log4j.appender.HTML=org.apache.log4j.RollingFileAppender
log4j.appender.HTML.File=${catalina.home}/logs/mylog.html
log4j.appender.HTML.MaxFileSize=100KB
log4j.appender.HTML.Append=false
log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout
log4j.appender.HTML.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%p] %c:%L - %m%n
Set this
log4j.logger.org.w3c.tidy=FATAL
Will cause org.w3c.tidy log only will shown if FATAL occurs
Saturday, September 8, 2012
Java Developer / Mobile Web Developer Needed
Java Developer Needed
- at least have little experience in Java
- will have training for enablement
- will work with our framework, including using Spring, JPA Hibernate, Java Server Faces, Maven, etc.
- Mail me now for detail at boylevantz@gmail.com
Mobile Web Developer Needed
- have experience in HTML, CSS is a must
- strong experience in Javascript, jQuery
- experience in jQuery mobile would be an advantages
- Mail me now for detail at boylevantz@gmail.com
Labels:
boylevantz,
css,
dev,
developer,
hibernate,
html,
java,
javascript,
jquery,
jquery mobile,
js,
jsf,
maven,
mobile,
spring,
web
Saturday, August 25, 2012
Orion BB Start! for BlackBerry Java Development
Start a project on google code for BlackBerry Java Development
http://code.google.com/p/orion-bb/
For BlackBerry Java Development
Features
- Splash Screen
- Advanced UI Components such as Accordions, Tab, Tooltip, etc.
- Barcode scanner
- More features
Anyone interested in contributing please email me at boylevantz@gmail.com
Check it out!
Labels:
bb,
blackberry,
java,
native,
orion,
ui,
user interface
Jakarta, Indonesia
Jakarta Capital Region, Indonesia
Monday, August 13, 2012
Executing Javascript code in Java
Here some snippet how to execute Javascript code in Java
final String script = "function test(){ return 'abc' + 'def'; } test();";
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval(script);
Assert.assertEquals("java.lang.String", result.getClass().getName());
Assert.assertEquals("abcdef", result.toString());
And some other code
final String script = "function execute(){ return { 'U.1' : function(){ return { 'u': '2', 'r': '', 'f':'U' }; }, 'R.5': function(){ return 'B' } } } execute();";
ScriptEngine js = new ScriptEngineManager().getEngineByExtension("js");
js.getContext().setAttribute("out", System.out, ScriptContext.ENGINE_SCOPE);
Object jsResult = js.eval(script);
NativeObject obj = (NativeObject) jsResult;
Object objUserRole = NativeObject.getProperty(obj, "U.1");
SimpleBindings bindings = new SimpleBindings();
bindings.put("foomethod", objUserRole);
log.debug("RESULT: " + js.eval("foomethod();", bindings));
log.debug("RESULT: " + js.eval("foomethod().u", bindings));
log.debug("RESULT: " + js.eval("foomethod().r", bindings));
log.debug("RESULT: " + js.eval("foomethod().f", bindings));
Assert.assertEquals("2", js.eval("foomethod().u", bindings).toString());
Assert.assertEquals("", js.eval("foomethod().r", bindings).toString());
Assert.assertEquals("U", js.eval("foomethod().f", bindings).toString());
objUserRole = NativeObject.getProperty(obj, "R.5");
bindings.put("foomethod", objUserRole);
log.debug("RESULT: " + js.eval("foomethod();", bindings));
Assert.assertEquals("B",js.eval("foomethod();", bindings).toString());
final String script = "function test(){ return 'abc' + 'def'; } test();";
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval(script);
Assert.assertEquals("java.lang.String", result.getClass().getName());
Assert.assertEquals("abcdef", result.toString());
And some other code
final String script = "function execute(){ return { 'U.1' : function(){ return { 'u': '2', 'r': '', 'f':'U' }; }, 'R.5': function(){ return 'B' } } } execute();";
ScriptEngine js = new ScriptEngineManager().getEngineByExtension("js");
js.getContext().setAttribute("out", System.out, ScriptContext.ENGINE_SCOPE);
Object jsResult = js.eval(script);
NativeObject obj = (NativeObject) jsResult;
Object objUserRole = NativeObject.getProperty(obj, "U.1");
SimpleBindings bindings = new SimpleBindings();
bindings.put("foomethod", objUserRole);
log.debug("RESULT: " + js.eval("foomethod();", bindings));
log.debug("RESULT: " + js.eval("foomethod().u", bindings));
log.debug("RESULT: " + js.eval("foomethod().r", bindings));
log.debug("RESULT: " + js.eval("foomethod().f", bindings));
Assert.assertEquals("2", js.eval("foomethod().u", bindings).toString());
Assert.assertEquals("", js.eval("foomethod().r", bindings).toString());
Assert.assertEquals("U", js.eval("foomethod().f", bindings).toString());
objUserRole = NativeObject.getProperty(obj, "R.5");
bindings.put("foomethod", objUserRole);
log.debug("RESULT: " + js.eval("foomethod();", bindings));
Assert.assertEquals("B",js.eval("foomethod();", bindings).toString());
Labels:
eval,
expression,
java,
javascript,
js
Jakarta, Indonesia
Jakarta Capital Region, Indonesia
Using Expression Language
This is an example using expression language in Java
import javax.el.ValueExpression;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.jlego.core.Dto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.odysseus.el.util.SimpleContext;
public class TestExpression extends TestCase {
private static final Logger log = LoggerFactory.getLogger(TestExpression.class);
public void testJuel(){
java.util.Properties properties = new java.util.Properties();
properties.put("javax.el.cacheSize", "5000");
javax.el.ExpressionFactory factory = new de.odysseus.el.ExpressionFactoryImpl(properties);
Map map= new HashMap();
map .put("data", "ali");
SimpleContext context = new SimpleContext();
context.setVariable("request", factory.createValueExpression(map, HashMap.class));
ValueExpression expr = factory.createValueExpression(context, "${request.data == 'ali'}", Object.class);
Assert.assertEquals("true", expr.getValue(context).toString());
ValueExpression expr2 = factory.createValueExpression(context, "${ (1==0) ? 'ali' : ((2==2) ? 'not not ali' : 'not ali') }", Object.class);
Assert.assertEquals("not not ali",expr2.getValue(context));
}
}
I'm using Maven, so make sure you have these dependencies:
<dependency>
<groupId>de.odysseus.juel</groupId>
<artifactId>juel</artifactId>
<version>2.1.3</version>
</dependency>
Of course JUnit as well
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
import javax.el.ValueExpression;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.jlego.core.Dto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.odysseus.el.util.SimpleContext;
public class TestExpression extends TestCase {
private static final Logger log = LoggerFactory.getLogger(TestExpression.class);
public void testJuel(){
java.util.Properties properties = new java.util.Properties();
properties.put("javax.el.cacheSize", "5000");
javax.el.ExpressionFactory factory = new de.odysseus.el.ExpressionFactoryImpl(properties);
Map map= new HashMap();
map .put("data", "ali");
SimpleContext context = new SimpleContext();
context.setVariable("request", factory.createValueExpression(map, HashMap.class));
ValueExpression expr = factory.createValueExpression(context, "${request.data == 'ali'}", Object.class);
Assert.assertEquals("true", expr.getValue(context).toString());
ValueExpression expr2 = factory.createValueExpression(context, "${ (1==0) ? 'ali' : ((2==2) ? 'not not ali' : 'not ali') }", Object.class);
Assert.assertEquals("not not ali",expr2.getValue(context));
}
}
I'm using Maven, so make sure you have these dependencies:
<dependency>
<groupId>de.odysseus.juel</groupId>
<artifactId>juel</artifactId>
<version>2.1.3</version>
</dependency>
Of course JUnit as well
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
Labels:
expression,
java,
juel,
language
Jakarta, Indonesia
Jakarta Capital Region, Indonesia
Wednesday, December 7, 2011
Java OutofMemoryError on Tomcat
Edit your catalina.sh (find in tomcat-folder/bin/catalina.sh)
Add following lines at the beginning
JAVA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 -server -Xms512m -Xmx1024m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m -XX:MaxPermSize=256m -XX:+DisableExplicitGC"
Then start your tomcat, using startup.sh
Friday, October 28, 2011
Creating HTTP or HTTPS Connection programmatically in Java
I create a class HttpUtil
Usage example
HttpUtil http = new HttpUtil();
http.setDoOutput(true);
http.setDoInput(true);
http.setContentType("application/x-www-form-urlencoded");
http.setAllowUserInteractions(false);
String response = http.request("www.mydomain.com/process.php", params, "POST");
params should be a HashMap for example
Usage example
HttpUtil http = new HttpUtil();
http.setDoOutput(true);
http.setDoInput(true);
http.setContentType("application/x-www-form-urlencoded");
http.setAllowUserInteractions(false);
String response = http.request("www.mydomain.com/process.php", params, "POST");
System.out.println(response);
params should be a HashMap for example
HashMap<String, String> params = new HashMap<String, String> ();
params.put("username","ali");
params.put("password","somepassword");
Using Batik Rasterizer in Java
In this example will create a exporting server for Highchart in Java. Since the default example is in PHP, and I'm using Java and tomcat as my web server.
I convert the PHP exporting script example to Java servlet code.
public class ReportExporter extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
ServletContext application = this.getServletContext();
String type = request.getParameter("type");
String svg = request.getParameter("svg");
String filename = request.getParameter("filename");
System.out.println("type: " + type);
System.out.println("svg: " + svg);
System.out.println("filename: " + filename);
System.out.println("width: " + request.getParameter("width"));
if (filename == null && filename.equals("")) {
filename = "chart";
}
String typeString = "";
String ext = "";
String outFile = "";
String width = null;
String tempName = null;
try {
tempName = SecurityUtil.md5(String.valueOf(System
.currentTimeMillis()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if (type.equals("image/png")) {
typeString = "-m image/png";
ext = "png";
} else if (type.equals("image/jpeg")) {
typeString = "-m image/jpeg";
ext = "jpg";
} else if (type.equals("application/pdf")) {
typeString = "-m application/pdf";
ext = "pdf";
} else if (type.equals("image/svg+xml")) {
ext = "svg";
}
outFile = "temp/" + tempName + "." + ext;
if (!typeString.equals("")) {
width = request.getParameter("width");
if (width != null && !width.equals(""))
width = "-w " + width;
}
// Generate temporary file
File f = new File(application.getRealPath("/temp/" + tempName
+ ".svg"));
IOUtil.writeToFile(f, svg);
String batikPath = application.getRealPath("/WEB-INF/lib/batik-rasterizer.jar");
String classPath = "-cp " + application.getRealPath("/WEB-INF/lib");
String outFileFullPath = application.getRealPath(outFile);
String tempFileFullPath = application.getRealPath("temp/"+tempName+".svg");
try {
// Convert SVG file into specified type
SystemUtil.runCommand("java",classPath, "-jar",batikPath, typeString,"-d",outFileFullPath,width,tempFileFullPath);
// Show the file to user as download
response.setHeader("Content-disposition", "attachment; filename=" + filename + "." +ext);
response.setHeader("Content-type", type);
ServletOutputStream out = response.getOutputStream();
IOUtil.fileToStream(new File(outFileFullPath), out);
out.flush();
out.close();
} catch (Throwable e) {
e.printStackTrace();
response.getOutputStream().print("Error on exporting");
}
}
}
You will need these classes
SystemUtil
IOUtil
This example use Batik rasterizer. Please download it here. Then place it your web application folder
WEB-INF/lib/batik-rasterizer.jar
WEB-INF/lib/batik-slideshow.jar
WEB-INF/lib/batik-squiggle.jar
WEB-INF/lib/batik-svgpp.jar
WEB-INF/lib/batik-ttf2svg.jar
WEB-INF/lib/lib -> contains lib for batik (see batik distribution batik-version/lib)
I convert the PHP exporting script example to Java servlet code.
public class ReportExporter extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
ServletContext application = this.getServletContext();
String type = request.getParameter("type");
String svg = request.getParameter("svg");
String filename = request.getParameter("filename");
System.out.println("type: " + type);
System.out.println("svg: " + svg);
System.out.println("filename: " + filename);
System.out.println("width: " + request.getParameter("width"));
if (filename == null && filename.equals("")) {
filename = "chart";
}
String typeString = "";
String ext = "";
String outFile = "";
String width = null;
String tempName = null;
try {
tempName = SecurityUtil.md5(String.valueOf(System
.currentTimeMillis()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if (type.equals("image/png")) {
typeString = "-m image/png";
ext = "png";
} else if (type.equals("image/jpeg")) {
typeString = "-m image/jpeg";
ext = "jpg";
} else if (type.equals("application/pdf")) {
typeString = "-m application/pdf";
ext = "pdf";
} else if (type.equals("image/svg+xml")) {
ext = "svg";
}
outFile = "temp/" + tempName + "." + ext;
if (!typeString.equals("")) {
width = request.getParameter("width");
if (width != null && !width.equals(""))
width = "-w " + width;
}
// Generate temporary file
File f = new File(application.getRealPath("/temp/" + tempName
+ ".svg"));
IOUtil.writeToFile(f, svg);
String batikPath = application.getRealPath("/WEB-INF/lib/batik-rasterizer.jar");
String classPath = "-cp " + application.getRealPath("/WEB-INF/lib");
String outFileFullPath = application.getRealPath(outFile);
String tempFileFullPath = application.getRealPath("temp/"+tempName+".svg");
try {
// Convert SVG file into specified type
SystemUtil.runCommand("java",classPath, "-jar",batikPath, typeString,"-d",outFileFullPath,width,tempFileFullPath);
// Show the file to user as download
response.setHeader("Content-disposition", "attachment; filename=" + filename + "." +ext);
response.setHeader("Content-type", type);
ServletOutputStream out = response.getOutputStream();
IOUtil.fileToStream(new File(outFileFullPath), out);
out.flush();
out.close();
} catch (Throwable e) {
e.printStackTrace();
response.getOutputStream().print("Error on exporting");
}
}
}
You will need these classes
SystemUtil
IOUtil
This example use Batik rasterizer. Please download it here. Then place it your web application folder
WEB-INF/lib/batik-rasterizer.jar
WEB-INF/lib/batik-slideshow.jar
WEB-INF/lib/batik-squiggle.jar
WEB-INF/lib/batik-svgpp.jar
WEB-INF/lib/batik-ttf2svg.jar
WEB-INF/lib/lib -> contains lib for batik (see batik distribution batik-version/lib)
Thursday, October 27, 2011
Reset programmatically in Blackberry device
Create a dummy application
public class DummyApp extends Application{
public static void main( String[] args )
{
new DummyApp().enterEventDispatcher();
}
}
Compile the code into .cod file and place in your project
let's say MyProject/res/DummyApp
in your main program add this method
private void reset() {
try {
byte[] codData = getResource("/DummyApp");
int dummycodhandle = CodeModuleManager.createNewModule(codData.length, codData, codData.length);
//Save the module
int result = CodeModuleManager.saveNewModule(dummycodhandle, true);
if (result != CodeModuleManager.CMM_OK && result != CodeModuleManager.CMM_OK_MODULE_OVERWRITTEN)
{
//The cod file was not saved.
throw new Exception("Failed to save dummy cod.");
}
int dummycodhandle2=CodeModuleManager.getModuleHandle("DummyApp");
ApplicationDescriptor[] desc = CodeModuleManager.getApplicationDescriptors(dummycodhandle2);
ApplicationManager.getApplicationManager().runApplication( desc[0], false );
// Make sure the application is already started, assume 5 seconds is enough
Thread.currentThread().sleep(5000);
CodeModuleManager.deleteModuleEx(dummycodhandle2,true);
CodeModuleManager.promptForResetIfRequired();
}
catch (Exception e) {
e.printStackTrace();
}
}
private byte[] getResource(String name)
{
DataBuffer db = new DataBuffer();
byte[] data = new byte[1024];
DataInputStream input = new DataInputStream(UiApplication.getUiApplication().getClass().getResourceAsStream(name));
int len = 0;
try{
while ( -1 != (len = input.read(data)) )
{
db.write(data, 0, len);
}
}catch(Throwable e)
{
e.printStackTrace();
}
return db.getArray();
}
When you want to ask your device to restart, just call the method reset()
public class DummyApp extends Application{
public static void main( String[] args )
{
new DummyApp().enterEventDispatcher();
}
}
Compile the code into .cod file and place in your project
let's say MyProject/res/DummyApp
in your main program add this method
private void reset() {
try {
byte[] codData = getResource("/DummyApp");
int dummycodhandle = CodeModuleManager.createNewModule(codData.length, codData, codData.length);
//Save the module
int result = CodeModuleManager.saveNewModule(dummycodhandle, true);
if (result != CodeModuleManager.CMM_OK && result != CodeModuleManager.CMM_OK_MODULE_OVERWRITTEN)
{
//The cod file was not saved.
throw new Exception("Failed to save dummy cod.");
}
int dummycodhandle2=CodeModuleManager.getModuleHandle("DummyApp");
ApplicationDescriptor[] desc = CodeModuleManager.getApplicationDescriptors(dummycodhandle2);
ApplicationManager.getApplicationManager().runApplication( desc[0], false );
// Make sure the application is already started, assume 5 seconds is enough
Thread.currentThread().sleep(5000);
CodeModuleManager.deleteModuleEx(dummycodhandle2,true);
CodeModuleManager.promptForResetIfRequired();
}
catch (Exception e) {
e.printStackTrace();
}
}
private byte[] getResource(String name)
{
DataBuffer db = new DataBuffer();
byte[] data = new byte[1024];
DataInputStream input = new DataInputStream(UiApplication.getUiApplication().getClass().getResourceAsStream(name));
int len = 0;
try{
while ( -1 != (len = input.read(data)) )
{
db.write(data, 0, len);
}
}catch(Throwable e)
{
e.printStackTrace();
}
return db.getArray();
}
When you want to ask your device to restart, just call the method reset()
Monday, October 17, 2011
Get Latitude and Longitude based on provided data using Java
We can get Latitude and Longitude based on MCC, MNC, LAC, Cell ID
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* GetLocation provide mechanism to get location based on MCC, MNC, LAC, and Cell ID
*
* @author Ali Irawan
* @version 1.0
*/
public class GetLocation {
/**
* Get location based on MCC, MNC, LAC, and Cell ID
*
* @param mcc mobile country code
* @param mnc mobile network code
* @param lac location area code
* @param cellId cell id
* @param requestAddress true if want to get address
* @return JSON String representation of position
* * @throws IOException
*/
@SuppressWarnings("unused")
public static String getLocation(String mcc, String mnc, String lac,
String cellId, boolean requestAddress) throws IOException {
final String data = "{\"cell_towers\": [{\"location_area_code\": \""
+ lac + "\", \"mobile_network_code\": \"" + mnc
+ "\", \"cell_id\": \"" + cellId
+ "\", \"mobile_country_code\": \"" + mcc
+ "\"}], \"version\": \"1.1.0\", \"request_address\": \""
+ requestAddress + "\"}";
final String url = "https://www.google.com/loc/json";
URL anUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) anUrl.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-type", "application/jsonrequest");
OutputStream out = conn.getOutputStream();
out.write(data.getBytes());
out.close();
InputStream in = conn.getInputStream();
StringBuilder builder = new StringBuilder();
Reader reader = new InputStreamReader(in);
char[] buf = new char[1024];
int read = 0;
while ((read = reader.read(buf)) >= 0) {
builder.append(String.valueOf(buf, 0, read));
}
in.close();
conn.disconnect();
return builder.toString();
}
}
Example of use:
Output:
{
"location":
{
"latitude":-6.2452443,
"longitude":106.7908857,
"address": {
"country":"Indonesia",
"country_code":"ID",
"region":"Jakarta Capital Region",
"city":"Jakarta Capital Region",
"street":"Jalan Gandaria Tengah 4",
"postal_code":"12240"
},
"accuracy":713.0
},
"access_token":"2:C5RroEdSGjSfnq9X:7oAhDHrp_5xzgTeU"
}
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* GetLocation provide mechanism to get location based on MCC, MNC, LAC, and Cell ID
*
* @author Ali Irawan
* @version 1.0
*/
public class GetLocation {
/**
* Get location based on MCC, MNC, LAC, and Cell ID
*
* @param mcc mobile country code
* @param mnc mobile network code
* @param lac location area code
* @param cellId cell id
* @param requestAddress true if want to get address
* @return JSON String representation of position
* * @throws IOException
*/
@SuppressWarnings("unused")
public static String getLocation(String mcc, String mnc, String lac,
String cellId, boolean requestAddress) throws IOException {
final String data = "{\"cell_towers\": [{\"location_area_code\": \""
+ lac + "\", \"mobile_network_code\": \"" + mnc
+ "\", \"cell_id\": \"" + cellId
+ "\", \"mobile_country_code\": \"" + mcc
+ "\"}], \"version\": \"1.1.0\", \"request_address\": \""
+ requestAddress + "\"}";
final String url = "https://www.google.com/loc/json";
URL anUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) anUrl.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-type", "application/jsonrequest");
OutputStream out = conn.getOutputStream();
out.write(data.getBytes());
out.close();
InputStream in = conn.getInputStream();
StringBuilder builder = new StringBuilder();
Reader reader = new InputStreamReader(in);
char[] buf = new char[1024];
int read = 0;
while ((read = reader.read(buf)) >= 0) {
builder.append(String.valueOf(buf, 0, read));
}
in.close();
conn.disconnect();
return builder.toString();
}
}
Example of use:
String location = GetLocation.getLocation("510", "89", "9250", "851", true);
System.out.println(location);
System.out.println(location);
Output:
{
"location":
{
"latitude":-6.2452443,
"longitude":106.7908857,
"address": {
"country":"Indonesia",
"country_code":"ID",
"region":"Jakarta Capital Region",
"city":"Jakarta Capital Region",
"street":"Jalan Gandaria Tengah 4",
"postal_code":"12240"
},
"accuracy":713.0
},
"access_token":"2:C5RroEdSGjSfnq9X:7oAhDHrp_5xzgTeU"
}
Thursday, June 23, 2011
Wednesday, May 18, 2011
Implementing Tab Control in Blackberry Java Application
Currently I'm on the project in the Blackberry, and wondering how to implement Tab Control UI for the Java Application Development. So after research, and do some deep search and learning, and of course some modifications base on my need. I have this kind of pattern
First, I create TabButton, this component is extended from Field. You can use built-in BitmapField, LabelField, or any other Field. In my case, I need to make my own field for full customization.
Download samples here
First, I create TabButton, this component is extended from Field. You can use built-in BitmapField, LabelField, or any other Field. In my case, I need to make my own field for full customization.
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
public class TabButton extends Field {
String _label;
Bitmap _image;
static int _height = 44; // according to image size
static int _weight = 44;
int _backgroundColor;
int _focusColor;
private int _statusBit;
public TabButton(String label,
Bitmap image,
long style) {
super(style);
this._label = label;
this._image = image;
this._backgroundColor = 0x00cccccc;
this._focusColor = 0x00ffcc00;
}
protected void paint(Graphics graphics) {
// Draw background
graphics.setBackgroundColor(_backgroundColor);
graphics.clear();
graphics.setColor(
isFocus() ? _focusColor : _backgroundColor);
graphics.fillRoundRect(
0, 0, _image.getHeight(), _image.getWidth(),
15, 15);
if (_image != null) {
graphics.drawBitmap(0, 0, _image.getWidth(),
_image.getHeight(), _image, 0, 0);
}
}
protected void layout(int maxWidth, int maxHeight) {
setExtent(_weight, _height);
}
public boolean isFocusable() {
return true;
}
protected void drawFocus(Graphics graphics,
boolean on) {
// Don't draw the default focus
}Now the TabControlScreen (the main screen of our application)
protected void onFocus(int direction) {
super.onFocus(direction);
invalidate();
}
protected void onUnfocus() {
super.onUnfocus();
invalidate();
}
protected boolean navigationClick(int status,
int time) {
fieldChangeNotify(1);
return true;
}
}
public class TabControlScreen extends MainScreen
implements FieldChangeListener {
//to manage the tab buttonHorizontalFieldManager _tabManager;
TabButton _tab1;
TabButton _tab2;
TabButton _tab3;
VerticalFieldManager _tabArea;
LabelField _title1;
LabelField _title2;
LabelField _title3;
VerticalFieldManager _tab1Mgr;
VerticalFieldManager _tab2Mgr;
VerticalFieldManager _tab3Mgr;
private Bitmap bmp1;private Bitmap bmp2;private Bitmap bmp3;
public TabControlScreen() {
super();
//set main manager background colorgetMainManager().setBackground(
BackgroundFactory.createSolidBackground(0x00eeeeee));
bmp1 = Bitmap.getBitmapResource("img/image1.png");bmp2 = Bitmap.getBitmapResource("img/image2.png");bmp3 = Bitmap.getBitmapResource("img/image3.png");
_tab1 = new TabButton("Tab 1", bmp1, Field.FOCUSABLE | Field.FIELD_HCENTER);_tab2 = new TabButton("Tab 2", bmp2, Field.FOCUSABLE | Field.FIELD_HCENTER);_tab3 = new TabButton("Tab 3", bmp3, Field.FOCUSABLE | Field.FIELD_HCENTER);
_tab1.setChangeListener(this);_tab2.setChangeListener(this);_tab3.setChangeListener(this);_tabManager= new HorizontalFieldManager(USE_ALL_WIDTH);_tabManager.setBackground(BackgroundFactory
.createSolidBackground(0x00cccccc));_tabManager.add(_tab1);
_tabManager.add(_tab2);
_tabManager.add(_tab3);
add(_tabManager); //add to main manager
add(new SeparatorField());
_tab1Mgr = new VerticalFieldManager(Field.USE_ALL_WIDTH);
_tab2Mgr = new VerticalFieldManager(Field.USE_ALL_WIDTH);
_tab3Mgr = new VerticalFieldManager(Field.USE_ALL_WIDTH);
_tabArea = displayTab1();add( _tabArea);}
private VerticalFieldManager displayTab1(){if(_title1==null){_title1 = new LabelField("Content 1", Field.USE_ALL_WIDTH);_tab1Mgr.add( _title1);}return _tab1Mgr;}
private VerticalFieldManager displayTab2(){if(_title2==null){_title2 = new LabelField("Content 2", Field.USE_ALL_WIDTH);_tab2Mgr.add( _title2);}return _tab2Mgr;}private VerticalFieldManager displayTab3(){if(_title3==null){_title3 = new LabelField("Content 3", Field.USE_ALL_WIDTH);_tab3Mgr.add( _title3);}return _tab3Mgr;}
public void fieldChanged(Field field, int context) {}
if (_tabArea != null) {
if (field == _tab1) {
delete(_tabArea);
_tabArea = displayTab1();
add(_tabArea);
} else if (field == _tab2) {
delete(_tabArea);
_tabArea = displayTab2();
add(_tabArea);
} else if (field == _tab3) {
delete(_tabArea);
_tabArea = displayTab3();
add(_tabArea);
}
}
}
Download samples here
Subscribe to:
Posts (Atom)