How can I call a C# WebMethod in my Java Applet ?
The method called EnrollClient in C#
My Try
public void enroll(String teste) {
URL u;
InputStream is = null;
try {
u = new URL("http://localhost:5154/lb.ashx?pwd=abci/EnrollClient");
is = u.openStream();
BufferedReader d = new BufferedReader(new InputStreamReader(is));
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
is.close();
} catch (IOException ioe) {
}
}
C# WebMethod
public class lb : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
strings pwd = context.Request["pwd"].ToString();
business.Client.lb cli = new business.Client.lb();
JavaScriptSerializer jss = new JavaScriptSerializer();
StringBuilder sbRes = new StringBuilder();
jss.Serialize(cli.ReturnJSon(), sbRes);
context.Response.Write(sbRes.ToString());
}
[WebMethod]
public void EnrollClient()
{
string template = string.Empty;
string client = string.Empty;
try
{
business.Client.lb cli = new business.Client.lb();
cli.EnrollClient(template, client);
}
catch (Exception e)
{
}
}
If I do the same code but with the code
u = new URL("http://localhost:5154/lb.ashx?pwd=abci");
it will access the ProcessRequest of my C# code.
Related
I have a method for retrieving some coordinates from a very slow page.
My method works fine but i cant help to feel like it can be greatly improved, specially the try/catch clauses.
The method looks like this:
public void getCoordinates(){
EventQueue.invokeLater(() -> loadingLabel.updateCoordinates(true));
consolePanel.getConsole().append("\nRetrieving coordinates from server\n");
shapes.clear();
URL url = null;
try {
url = new URL("http://TestServlet/");
} catch (MalformedURLException e) {
e.printStackTrace();
consolePanel.getConsole().append(e.toString());
}
try {
URLConnection connection = url.openConnection();
connection.setConnectTimeout(1000);
try (InputStream dataSource = url.openStream()) {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(
dataSource, StandardCharsets.ISO_8859_1));
double xCoordinate;
double yCoordinate;
String line;
while ((line = inputStream.readLine()) != null) {
if(!line.startsWith("#")) {
consolePanel.getConsole().append(line + "\n");
String[] text = line.split(",");
xCoordinate = Double.parseDouble(text[0]);
yCoordinate = Double.parseDouble(text[1]);
xCoordinate = Math.abs(xCoordinate)/4;
yCoordinate = Math.abs(yCoordinate)/4;
String name = text[2];
shapes.add(this.mapPanelState.getNewShape(xCoordinate, yCoordinate, 10, name));
}
}
}
} catch (IOException e) {
e.printStackTrace();
consolePanel.getConsole().append(e.toString());
}
EventQueue.invokeLater(this::repaint);
EventQueue.invokeLater(() -> loadingLabel.updateCoordinates(false));
}
Any help to improve on it would be much appreciated.
Your error handling is the same for both catch clauses. So you may easily merge those.
public void getCoordinates() {
try {
URL url = new URL("http://TestServlet/");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(1000);
try (InputStream dataSource = url.openStream()) {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(dataSource, StandardCharsets.ISO_8859_1));
double xCoordinate;
double yCoordinate;
String line;
while ((line = inputStream.readLine()) != null) {
if (!line.startsWith("#")) {
consolePanel.getConsole().append(line + "\n");
String[] text = line.split(",");
xCoordinate = Double.parseDouble(text[0]);
yCoordinate = Double.parseDouble(text[1]);
xCoordinate = Math.abs(xCoordinate) / 4;
yCoordinate = Math.abs(yCoordinate) / 4;
String name = text[2];
shapes.add(this.mapPanelState.getNewShape(xCoordinate, yCoordinate, 10, name));
}
}
}
} catch (Exception e) {
e.printStackTrace();
consolePanel.getConsole().append(e.toString());
}
EventQueue.invokeLater(this::repaint);
EventQueue.invokeLater(() -> loadingLabel.updateCoordinates(false));
}
Here is my improvement:
try {
URL url = new URL("http://TestServlet/");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(1000);
try (InputStream dataSource = url.openStream()) {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(
dataSource, StandardCharsets.ISO_8859_1));
/*
your logic here
*/
}
} catch (MalformedURLException e) {
e.printStackTrace();
//consolePanel.getConsole().append("URL is malformed! Try with a valid one");
} catch (IOException e) {
e.printStackTrace();
//consolePanel.getConsole().append("....");
} catch (Exception e) {
// runtime exceptions
}
If your action does not change whether it's a MalformedURLException, IOException etc., the following catch block is enough:
catch (Exception e) {
e.printStackTrace();
//consolePanel.getConsole().append(e.toString());
}
I'try to save my custom JSONObject into the file.Everything working correct but I can't append json into file.For example,If I click twice to save json,in my file I have one element.Here is a my source
public class TransactionFileManager {
public static final File path = Environment.
getExternalStoragePublicDirectory(Environment.getExternalStorageState() + "/myfolder/");
public static final File file = new File(path, "transaction1.json");
public static String read() {
String ret = null;
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
try {
String receiveString;
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
ret = stringBuilder.toString();
bufferedReader.close();
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
try {
file.createNewFile();
} catch (IOException ioe) {
ioe.printStackTrace();
}
e.printStackTrace();
}
return ret;
}
public static void writeToFile(JSONObject data) {
if (!path.exists()) {
path.mkdirs();
}
try {
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fOut);
outputStreamWriter.append(data.toString());
outputStreamWriter.close();
fOut.flush();
fOut.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
}
How I can append json object into my .json file.What's a wrong in my code
thanks
Here is my code. I did a "GET" method for have a response of my DB.
Then I read my own file csv. All is ok in this point, but... I have not idea how can i do a "POST" method. i know that i need to use "addRequestProperty"method.
Any idea for create vertex and edge?
public void run() throws MalformedURLException, JSONException, IOException {
String viaURl = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxx/mydb";
URL url = new URL(viaURl);
HttpURLConnection conexion = null;
String texto = null;
String json;
BufferedReader in = null, in2 = null;
int numDump = 5;
String dato;
String csvSplitBy = ";";
int numApps = 0;
OutputStreamWriter out;
try {
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxx", "xxxxxxxxxxxxx.".toCharArray());
}
});
conexion = (HttpURLConnection) url.openConnection();
conexion.setRequestMethod("GET");
conexion.connect();
System.out.println("¡¡¡Conectado!!!");
in = new BufferedReader(new InputStreamReader(conexion.getInputStream()));
out = new OutputStreamWriter(conexion.getOutputStream());
json = "";
while ((texto = in.readLine()) != null) {
json += texto;
}
in.close();
System.out.println(json);
conexion.setDoOutput(true);
try {
for (int i = 0; i < numDump; i++) {
String csvFile = "/home/danicroque/dump/dump_" + i;
try {
in2 = new BufferedReader(new FileReader(csvFile));
while ((dato = in2.readLine()) != null) {
numApps++;
String[] datos = dato.split(csvSplitBy, 15);
conexion.setRequestMethod("POST");
conexion.addRequestProperty("_id0" , datos[0]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("Fin");
}
}
}
Thank in advance.
You can use this POST methods to create class:
http://your_host:2480/class/mydb/className
to add property to a class
http://your_host:2480/property/mydb/className/propertyName
You can fine more detailed information here.
Hope it helps,
Alex.
UPDATE:
To insert use this POST method:
http://your_host:2480/command/mydb/sql/insert into className(propertyName) values(“yourValue”)
am making a simple ftp client/server program which on command from the clients lists files, tells the current directory, downloads files.
I want to create a server which is able to be connect with multiple clients and is capable of handling multiple commands at a time. I have used threading but my code gives the following error after the 1st command is executed.
socket closed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.DataInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Myserver$Connecthandle.run(Myserver.java:123)
at Myserver.main(Myserver.java:35)
java.net.SocketException: socket closed
Here's my server code:
public class Myserver {
static final int PortNumber = 120;
static ServerSocket MyService;
static Socket clientSocket = null;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
File directory;
directory = new File(System.getProperty("user.dir"));
try {
MyService = new ServerSocket(PortNumber);
String cd = directory.toString();
System.out.println(cd);
System.out.println("Listening on " + PortNumber);
while(true) {
clientSocket = MyService.accept();
Connecthandle a = new Connecthandle(clientSocket, directory);
a.start();
}
}
catch (IOException e) {
System.out.println(e);
}
}
static class Connecthandle extends Thread {
File Directory;
Socket clientsocket;
PrintWriter outgoing;
// Constructor for class
Connecthandle(Socket clients, File dir) {
clientsocket = clients;
Directory = dir;
}
// Works Fine
void listfiles() throws IOException {
String []Listfile = Directory.list();
String send = "";
for (int j = 0; j < Listfile.length; j++) {
send = send + Listfile[j] + ",";
}
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(send);
GoingOut.flush();
// GoingOut.close();
}
// Works Fine
void currentdirectory() throws IOException {
String cd = Directory.toString();
String cdd = "resp," + cd;
System.out.println(cdd);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(cdd);
GoingOut.flush();
GoingOut.close();
}
// Works fine
void sendfiles(String fileName) {
try {
File nfile = new File(fileName);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
if ( (! nfile.exists()) || nfile.isDirectory() ) {
GoingOut.writeBytes("file not present");
} else {
BufferedReader br = new BufferedReader(new FileReader(nfile));
int coun = 0;
String lin;
while ((lin = br.readLine()) != null) {
coun++;
}
GoingOut.writeBytes("resp," + fileName + "," + String.valueOf(coun) + "\n");
#SuppressWarnings("resource")
BufferedReader sr = new BufferedReader(new FileReader(nfile));
String line;
while ((line = sr.readLine()) != null) {
GoingOut.writeBytes(line+"\n");
GoingOut.flush();
}
GoingOut.close();
br.close();
}
} catch (IOException e) {
System.out.println("Unable to send!");
}
}
public void start() {
DataInputStream comingin = null;
try {
comingin = new DataInputStream(clientsocket.getInputStream());
} catch (IOException e2) {
e2.printStackTrace();
}
InputStreamReader isr = null;
try {
isr = new InputStreamReader(comingin, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(isr);
while (true) {
try {
String message = br.readLine();
if (message.contains("pwd")) {
currentdirectory();
} else if (message.contains("list")) {
listfiles();
} else if (message.contains("get")) {
String fileName = new String(message.substring(8, message.length()));
sendfiles(fileName);
} else if (message.contains("exit")) {
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
clientsocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
I moved all the methods into start() so i only needed to declare dataoutputstream once but now it gives a NULLPOINTEREXCEPTION whenever i use Outgoing.writeBytes
Updated:
static class Connecthandle extends Thread {
File Directory;
Socket clientsocket;
PrintWriter outgoing;
// Constructor for class
Connecthandle(Socket clients, File dir) {
clientsocket = clients;
Directory = dir;
}
public void run() {
DataInputStream comingin = null;
try {
comingin = new DataInputStream(clientsocket.getInputStream());
} catch (IOException e2) {
e2.printStackTrace();
}
InputStreamReader isr = null;
try {
isr = new InputStreamReader(comingin, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(isr);
while (true) {
try {
String message = br.readLine();
if (message.contains("pwd")) {
String cd = Directory.toString();
String cdd = "resp," + cd;
System.out.println(cdd);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(cdd);
GoingOut.flush();
} else if (message.contains("list")) {
String []Listfile = Directory.list();
String send = "";
for (int j = 0; j < Listfile.length; j++) {
send = send + Listfile[j] + ",";
}
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(send);
GoingOut.flush();
} else if (message.contains("get")) {
String fileName = new String(message.substring(8, message.length()));
try {
File nfile = new File(fileName);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
if ( (! nfile.exists()) || nfile.isDirectory() ) {
GoingOut.writeBytes("file not present");
} else {
BufferedReader wr = new BufferedReader(new FileReader(nfile));
int coun = 0;
String lin;
while ((lin = wr.readLine()) != null) {
coun++;
}
GoingOut.writeBytes("resp," + fileName + "," + String.valueOf(coun) + "\n");
#SuppressWarnings("resource")
BufferedReader sr = new BufferedReader(new FileReader(nfile));
String line;
while ((line = sr.readLine()) != null) {
GoingOut.writeBytes(line+"\n");
GoingOut.flush();
}
GoingOut.close();
br.close();
}
} catch (IOException e) {
System.out.println("Unable to send!");
}
} else if (message.contains("exit")) {
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
clientsocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
Closing the input stream or output stream of a socket closes the other stream and the socket. I don't see why you need to close anything here until the client disconnects or you time him out.
Has anyone tried this api ? I'm having some trouble implementing it on BlackBerry. Tweets do not always send and I cannot access posted tweets.
Here is my code -
private void twitterSetup(){
HttpRequest req = new HttpRequest("https://api.twitter.com/oauth/access_token");
req.setMethod(HttpConnection.POST);
XAuthSigner signer = new XAuthSigner("", "");
signer.signForAccessToken(req, "", "");
try {
HttpResponse resp = req.send();
if (resp.getCode() == HttpConnection.HTTP_OK)
{
Token accessToken = Token.parse(resp.getBodyContent());
req.close();
req = new HttpRequest("http://api.twitter.com/1/statuses/update.xml");
req.setMethod(HttpConnection.POST);
req.setBodyParameter("status", "new message");
req.setSigner(signer, accessToken);
resp = req.send();
Tweet[] twts = null;
try {
Credential c = new Credential("","","","");
UserAccountManager uam = UserAccountManager.getInstance(c);
List[] lists = null;
ListManager ter = null;
if (uam.verifyCredential()) {
ter = ListManager.getInstance(uam); //pode ser pela classe Timeline tambem.
ListManager listMngr = ListManager.getInstance(uam);
lists = listMngr.getLists();
}
ter.startGetListTweets(lists[0], null, new SearchDeviceListener() {
public void searchCompleted() {}
public void searchFailed(Throwable cause) {}
public void tweetFound(Tweet tweet) {
System.out.println(tweet);
}
});
}
catch(Exception e){
e.printStackTrace();
}
}
else { }
} catch (IOException e) {
e.printStackTrace();
}
catch(Exception e){
}finally {
try {
req.close();
} catch (IOException e) {}
}
}
Thanks for any help.
Ok,
Here is the class im using to get the twitter content based on type and tag. method getContent is not the most elegant but it works. It just downloads and parses a json file.
Look at http://search.twitter.com/api/
public class GetTwitterContent implements Runnable {
private String tag;
private String type;
public GetTwitterContent(String type, String tag) {
this.type = type;
this.tag = tag;
}
public void run() {
try {
Hashtable twitterValuesHashtable = new Hashtable();
String serviceUrl = "";
if (type.equalsIgnoreCase(Constants.TWITTER_CONTENT_TYPE_HASHTAG)) {
serviceUrl = Constants.TWITTER_CONTENT_HASHTAG_CONTENT;
} else if (type.equalsIgnoreCase(Constants.TWITTER_CONTENT_TYPE_USER)) {
serviceUrl = Constants.TWITTER_CONTENT_USER_CONTENT;
}
ByteArrayOutputStream baos = getContent(serviceUrl + this.tag);
JSONObject jsonObject = new JSONObject(new String(baos.toByteArray(), 0, baos.size(), "utf-8"));
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int counter = 0; counter < jsonArray.length(); ++counter) {
JSONObject thisJsonObject = (JSONObject) jsonArray.get(counter);
TwitterResponse twitterResponse = new TwitterResponse();
twitterResponse.setCreatedAt(thisJsonObject.optString("created_at", "na"));
twitterResponse.setTweetText(thisJsonObject.optString("text","na"));
twitterResponse.setFromUser(thisJsonObject.optString("from_user", "na"));
twitterValuesHashtable.put(new Integer(counter),twitterResponse);
}
ServerContent.future.addContent(Constants.TWITTER_KEY, twitterValuesHashtable);
} catch (Exception e) {
e.printStackTrace();
}
}
private ByteArrayOutputStream getContent(String url) {
ByteArrayOutputStream baos = null;
// len = 0;
try {
javax.microedition.io.HttpConnection connection = (javax.microedition.io.HttpConnection) Connector
.open(url);
connection.setRequestMethod(HttpConnection.GET);
// connection.setRequestProperty("Connection", "close");
java.io.InputStream inputStream = connection.openDataInputStream();
// inputStream = getClass().getResourceAsStream(url);
baos = new ByteArrayOutputStream();
int c;
while (true) {
c = inputStream.read();
if (c == -1)
break;
// ++len;
baos.write(c);
}
} catch (Exception e) {
e.printStackTrace();
}
return baos;
}
}