Android HttpClient problem - android-2.2-froyo

No errors in code according to Eclipse IDE. But when I'm trying to run this one in device it gives an error message.
package com.android.mypackage;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpEntity;
import android.widget.TextView;
public class MyActivity extends Activity
{
TextView textview;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.google.com");
HttpResponse httpresponse = httpclient.execute(httpget);
HttpEntity httpentity = httpresponse.getEntity();
if (httpentity != null)
{
httpentity = new BufferedHttpEntity(httpentity);
}
}
catch (Exception e)
{
System.out.println("Exception e");
textview.setText(e.getMessage());
}
};
});
}
}

Try this: add this line
httpget.addHeader("User-Agent", "Android");
Before you execute httpget.

Related

Google sign in integration

i tried integrating google signing in my app, I've done all I am supposes to do but when i run it on andoid device it telling me failed, please kindly help
this is my main Activity
package com.example.todo;
import static android.content.ContentValues.TAG;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.identity.BeginSignInRequest;
import com.google.android.gms.auth.api.identity.SignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.GoogleAuthProvider;
public class MainActivity extends AppCompatActivity {
private TextView todo;
private ImageView googleBtn;
GoogleSignInOptions gso;
GoogleSignInClient gsc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
todo = findViewById(R.id.todo);
googleBtn = findViewById(R.id.googleBtn);
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
gsc = GoogleSignIn.getClient(this,gso);
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);
if (acct != null){
navitgateToSecondActivity();
}
googleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
}
private void signIn() {
Intent signInIntent = gsc.getSignInIntent();
startActivityForResult(signInIntent,1000);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000){
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
task.getResult(ApiException.class);
navitgateToSecondActivity();
} catch (ApiException e) {
Toast.makeText(this, "Google Auth failed", Toast.LENGTH_SHORT).show();
}
}
}
}
void navitgateToSecondActivity(){
finish();
Intent intent = new Intent(this,secondActivity.class);
startActivity(intent);
}
}
this is the second activity
package com.example.todo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.navigation.NavigationView;
public class secondActivity extends AppCompatActivity {
private Button signOut;
private DrawerLayout drawer;
private NavigationView navigationView;
private MaterialToolbar toolbar;
GoogleSignInOptions gso;
GoogleSignInClient gsc;
private TextView profileName;
ImageView profilePic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
gsc = GoogleSignIn.getClient(this,gso);
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);
if (acct!=null){
String personName = acct.getDisplayName();
String personEmail = acct.getEmail();
Uri personPhoto = acct.getPhotoUrl();
profileName.setText(personName);
profilePic.setImageIcon(Icon.createWithContentUri(personPhoto));
}
initViews();
setSupportActionBar(toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,R.string.drawer_open,R.string.drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
logout();
}
});
}
void initViews(){
drawer = findViewById(R.id.drawer);
navigationView = findViewById(R.id.navigationView);
toolbar = findViewById(R.id.toolbar);
signOut = findViewById(R.id.signOut);
}
void logout(){
gsc.signOut().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
finish();
startActivity(new Intent(secondActivity.this,
MainActivity.class));
}
});
}
}
i tried integrating google signing in my app, I've done all I am supposes to do but when i run it on andoid device it telling me failed, please kindly help, i tried all that expecting to get a sign in but it keeps telling me failed

send data from spring boot to client with stomp websocket

I want to send data from Boot(Server) to client!
I am using stomp websocket!
WebSocketClient doesn't work with error that the HTTP response from the server [200] did not permit the HTTP upgrade to WebSocket!
It's my Java Stomp WebSocket client code!
In this code, I tried to config handShakeHeader.... but it doesn't work!
package refill.station.websocket;
import org.junit.jupiter.api.Test;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandler;
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.web.socket.WebSocketHttpHeaders;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class WebSocketTest {
#Test
public void WebSocketTest() {
WebSocketClient webSocketClient = new StandardWebSocketClient();
WebSocketStompClient stompClient = new WebSocketStompClient(webSocketClient);
stompClient.setMessageConverter(new MappingJackson2MessageConverter());
stompClient.setTaskScheduler(new ConcurrentTaskScheduler());
String url = "ws://localhost:8080/ws/websocket";
StompSessionHandler sessionHandler = new StompSessionHandlerAdapter() {};
List<String> protocols = new ArrayList<>();
protocols.add("v10.stomp");
protocols.add("v11.stomp");
WebSocketHttpHeaders handSahkeHeaders = new WebSocketHttpHeaders();
handSahkeHeaders.setUpgrade("websocket");
handSahkeHeaders.setConnection("Upgrade");
handSahkeHeaders.setSecWebSocketVersion("13");
handSahkeHeaders.setSecWebSocketKey("4hb9p5/JjeKLed5aXlBqnw==");
handSahkeHeaders.setSecWebSocketProtocol(protocols);
StompHeaders stompHeaders = new StompHeaders();
StompSession stompSession = null;
try {
stompSession = stompClient.connect(URI.create(url), handSahkeHeaders, stompHeaders, sessionHandler).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
stompSession.send("/app/control/complete", "msg");
// StompSession stompSession = stompClient.connect(url, sessionHandler).get();
}
}
I checked my WebSocket server with javascript and it works correctly!
This is my WebSocket server configuration!
package refill.station.config.websocket;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.RequestUpgradeStrategy;
import org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
RequestUpgradeStrategy upgradeStrategy = new TomcatRequestUpgradeStrategy();
registry.addEndpoint("/ws")
.withSockJS();
registry.addEndpoint("/ws")
.setHandshakeHandler(new DefaultHandshakeHandler(upgradeStrategy))
.setAllowedOrigins("*");
}
#Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/app");
registry.enableSimpleBroker("/control");
}
}
last, it's my controller for websocket!
package refill.station.controller.websocket;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
#RequiredArgsConstructor
#RestController
#Slf4j
public class RefillerCommunicateController {
#MessageMapping("/control/complete")
#SendTo("/control/operate")
public String test(#Payload String data) {
log.info("RefillerCommunicateController-test method");
return "test";
}
}

Spring Boot - readMessageInternal of AbstractHttpMessageConverter implementation not getting invoked

Trying to write very simple http message converter to add encryption around request & respose.
Implemented rest controller and messageConverter. writeInternal does get invoked during response. However readInternal does not get invoked when request is sent to the rest end point.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.techm.bm.util.EncryptDecryptUtil;
#Component
public class MessageEncryptionConverter extends AbstractHttpMessageConverter<Object> {
#Autowired
private ObjectMapper objectMapper;
public MessageEncryptionConverter() {
super(MediaType.ALL);
}
#Override
protected boolean supports(Class<?> clazz) {
return true;
}
#Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
return objectMapper.readValue(decrypt(inputMessage.getBody()), clazz);
}
#Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
outputMessage.getBody().write(encrypt(objectMapper.writeValueAsBytes(o)));
}
The below code is for encryption and decryption of request and response body For overall Project to modify response body and request parameters. Please check this code is works for me
For Request Encryption refer readInternal
below is the front-end or postman request sending, you have to add encrypted request in Json formate
Ex.{data : "+++++++++++++YOUR_ENCRYPTED_STRING++++++++++"}
For Response Descryption refer writeInternal
sending back to your front-end or postman request response with encrypted string
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.techm.bm.util.EncryptDecryptUtil;
#Component
public class MessageEncryptionConverter extends AbstractHttpMessageConverter<Object> {
#Autowired
private ObjectMapper objectMapper;
public MessageEncryptionConverter() {
super(MediaType.ALL);
}
#Override
protected boolean supports(Class<?> clazz) {
return true;
}
#Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
return objectMapper.readValue(decrypt(inputMessage.getBody()), clazz);
}
#Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
outputMessage.getBody().write(encrypt(objectMapper.writeValueAsBytes(o)));
}
// Convert request to input stream for sending to the controller
private InputStream decrypt(InputStream inputStream) throws IOException {
//this is API request params
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (UnsupportedEncodingException e) {
logger.error("UnsupportedEncodingException" + e.getMessage());
} catch (IOException e) {
logger.error("IOException" + e.getMessage());
} finally {
inputStream.close();
}
try {
JSONObject requestJsonObject = new JSONObject(writer.toString().replace("\n", ""));
// Add your decryption method the object data will get your encrypted string data and return with string of your JSON object
String decryptRequestString = EncryptionUtils.decryptText(requestJsonObject.getString("data"));
if (decryptRequestString != null) {
return new ByteArrayInputStream(decryptRequestString.getBytes(StandardCharsets.UTF_8));
} else {
return inputStream;
}
} catch (JSONException err) {
logger.error("Error" + err.toString());
} catch (NoSuchAlgorithmException | BadPaddingException | DigestException | InvalidKeyException
| InvalidAlgorithmParameterException | NoSuchPaddingException | IllegalBlockSizeException e) {
logger.info("NoSuchAlgorithmException | BadPaddingException | DigestException | InvalidKeyException | " +
"InvalidAlgorithmParameterException | NoSuchPaddingException | IllegalBlockSizeException:: " + e.getMessage());
}
return inputStream;
}
private byte[] encrypt(Object obj) throws JsonProcessingException {
// do your encryption here
try {
String stringFromObject = objectMapper.writeValueAsString(obj);
// Add your encryption method
String encrypt = EncryptionUtils.encryptText(stringFromObject);
return objectMapper.writeValueAsBytes(encrypt);
} catch (Exception e) {
logger.info("Error While Encrypt data :: " + e.getMessage());
return objectMapper.writeValueAsBytes(obj);
}
}
}
Reference code Spring Boot - Encrypt JSON data
Hope this code is working for you
It is invoking if the request has body and "supports" method return ture

Fatal error:An error occured while executing doInBackground()

I am new to android and i am getting this error.Maths1 code:
package com.materialdesign.geniusmathsandphysics;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class Maths1 extends Activity{
MainActivity async;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maths1);
async=new MainActivity();
Button m15,d15;
m15 = (Button) findViewById(R.id.but_m1may15);
d15 = (Button) findViewById(R.id.but_m1dec15);
m15.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File pdf = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/GeniusPhysicsandMaths/" + "M1_May_15.pdf");
if (pdf.exists()) {
//file= new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/pdf/Area.pdf");
Intent i=new Intent(Maths1.this,PdfViewer.class);
i.putExtra("FileName",pdf);
startActivity(i);
} else {
if (isNetworkConnected() == true) {
Toast.makeText(Maths1.this, "Starting Download....please wait.", Toast.LENGTH_LONG).show();
async.new Connect().execute("166.62.10.29", "M1_May_15.pdf");
} else {
Toast.makeText(Maths1.this, "No internet connection \n Please try again", Toast.LENGTH_SHORT).show();
}
}
}
});
d15.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File pdf = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/GeniusPhysicsandMaths/" + "M1_Dec_15.pdf");
if (pdf.exists()) {
ViewPDF();
} else {
if (isNetworkConnected() == true) {
async.new Connect().execute("166.62.10.29", "M1_Dec_15.pdf");
Toast.makeText(Maths1.this, "Starting Download....please wait.", Toast.LENGTH_LONG).show();
ViewPDF();
} else {
Toast.makeText(Maths1.this, "No internet connection \n Please try again", Toast.LENGTH_SHORT).show();
}
}
}
});
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
public void ViewPDF()
{
Intent i=new Intent(Maths1.this,PdfViewer.class);
SavePreferences("name", "M1_Dec_15.pdf");
startActivity(i);
}
private void SavePreferences(String key, String value) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
}
pdf viewer code:
package com.materialdesign.geniusmathsandphysics;
import android.content.SharedPreferences;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.File;
public class PdfViewer extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pdfviewer);
com.joanzapata.pdfview.PDFView Pdf = (com.joanzapata.pdfview.PDFView) findViewById(R.id.pdfview1);
//String filepath=getIntent().getExtras().getString("name");
String file=showPreferences("name");
File fd = new File(file);
//Log.i("hhhhdsdada",filepath);
Pdf.fromFile(fd).defaultPage(1).swipeVertical(true).load();
}
private String showPreferences(String key){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String savedPref = sharedPreferences.getString(key, "");
File files= new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/GeniusPhysicsandMaths/"+savedPref);
String file=files.toString();
return file;
}
}
this is my logcat:
FATAL EXCEPTION: AsyncTask #3 Process: com.materialdesign.geniusmathsandphysics, PID: 18871
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: PDF file is corrupted
at org.vudroid.pdfdroid.codec.PdfDocument.open(Native Method)
at org.vudroid.pdfdroid.codec.PdfDocument.openDocument(PdfDocument.java:28)
at org.vudroid.pdfdroid.codec.PdfContext.openDocument(PdfContext.java:18)
at org.vudroid.core.DecodeServiceBase.open(DecodeServiceBase.java:59)
at com.joanzapata.pdfview.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:52)
at com.joanzapata.pdfview.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:31)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:818) 
i am using joanzapata library to view pdf files.for that i am trenter code hereying to pass that file name from maths 1 class on button click listner. The library takes file as input so i had to convert string to file previously using intent i was getting null pointer exception but now with shared preferences i am getting this error. Please help me to solve it. Thanks in advance.

Jfree bar chart servlet code with oracle database

I am new to jfree chart I have the following code it runs without any error, however the browser shows me an empty page .. do not know where is the problem.
I am trying to create a bar chart using jfree chart in servlet and the data will be retrieved from oracle data base.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartUtilities;
public class BarChar extends HttpServlet {
#Override
public void init() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("JDBC driver loaded");
}
catch (ClassNotFoundException e) {
System.out.println(e.toString());
}
}
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
OutputStream out = response.getOutputStream();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","FATIMAH", "FATIMAH");
DefaultCategoryDataset bar = new DefaultCategoryDataset();
Statement stmt = conn.createStatement();
ResultSet r = stmt.executeQuery("select category,marks from chart_data");
while (r.next())
{
String category = r.getString("CATEGORY");
int marks = r.getInt("MARKS");
bar.addValue(marks,"Mark",category);
}
JFreeChart BarChartObject=ChartFactory.createBarChart("Subject Vs Marks Bar Chart","Subject","Marks",bar,PlotOrientation.VERTICAL,true,true,false);
response.setContentType("image/png");
ChartUtilities.writeChartAsPNG(out, BarChartObject, 400, 300);
}
catch (Exception e) {
System.err.println(e.toString());
}
finally {
out.close();
}
}
}

Resources