Authorize and Capture PayPal Order - paypal

I am trying to integrate PayPal Checkout SDK into my application.
I create the request like this:
protected int doPaypalOrderWithCustomer(PayPalPurchase purchase, Customer customer) throws PayPalException {
PayPalClient client = new PayPalClient();
// Creating an order
HttpResponse<Order> orderResponse = null;
try{
orderResponse = client.createCustomerOrder("Order", purchase.getTotalCheckoutCost(), 1, customer);
String orderId = "";
log.info("Creating Order...");
if(orderResponse.statusCode() == 201){
orderId = orderResponse.result().id();
log.info("Order ID: " + orderId);
log.info("Links:");
for(LinkDescription link : orderResponse.result().links()){
log.info(link.rel() + ": " + link.href());
if("approve".equalsIgnoreCase(link.rel())){
log.info("Request Approved");
ServletActionContext.getResponse().sendRedirect(link.href());
break;
}// end if
}// end for
}// end if
log.info("Created Successfully");
}catch(Exception e){
throw new PayPalException("Creating a PayPal order failed. Message is: " + e.getMessage(), e);
}finally{
if(null != orderResponse){
log.info("Order response status code is: " + String.valueOf(orderResponse.statusCode()));
}else{
log.info("Order response is null.");
}// end if/else
}// end try/catch/finally
return orderResponse.statusCode();
}// end doPaypalOrderWithCustomer
The second method is:
public HttpResponse<Order> createCustomerOrder(String desc, double cost, int quantity, Customer customer) throws Exception {
log.debug("Entering createCustomerOrder");
if(log.isDebugEnabled()){
log.debug("Method to create order with complete payload");
log.debug("Entry parameters are: desc=" + String.valueOf(desc) + ", cost=" + String.valueOf(cost) + ", quantity=" + String.valueOf(quantity) + ", Customer=" + String.valueOf(customer));
}// end if
double individualCost = cost / quantity;
NumberFormat format = NumberFormat.getNumberInstance();
format.setMaximumFractionDigits(2);
format.setMinimumFractionDigits(2);
OrdersCreateRequest request = new OrdersCreateRequest();
request.header("prefer", "return=representation");
OrderRequest orderRequest = new OrderRequest();
orderRequest.checkoutPaymentIntent("CAPTURE");
Payer payer = new Payer();
payer.email(customer.getEmail());
PhoneWithType phoneWithType = new PhoneWithType();
Phone phone = new Phone();
String phoneNumber = customer.getPhoneNo().replace("(", "");
phoneNumber = customer.getPhoneNo().replace(")", "");
phoneNumber = customer.getPhoneNo().replace("-", "");
phoneNumber = phoneNumber.replaceAll("\\D+", "");
phone.nationalNumber(phoneNumber);
phoneWithType.phoneNumber(phone);
payer.phoneWithType(phoneWithType);
orderRequest.payer(payer);
ApplicationContext applicationContext = new ApplicationContext() //
.brandName("LLC")//
.landingPage("BILLING")//
.cancelUrl(bundle.getString("RESPONSE_URL") + "?t=c")//
.returnUrl(bundle.getString("RESPONSE_URL") + "?t=r")//
.userAction("PAY_NOW").shippingPreference("NO_SHIPPING");
log.info("Method call to orderRequest.applicationContext(applicationContext)");
orderRequest.applicationContext(applicationContext);
List<PurchaseUnitRequest> purchaseUnitRequests = new ArrayList<>();
PurchaseUnitRequest purchaseUnitRequest = new PurchaseUnitRequest()//
.referenceId("PUHF")//
.description("Digital Content")//
.customId("CUST-DigitalContent")//
.softDescriptor("DigitalContent")//
.amountWithBreakdown(new AmountWithBreakdown()//
.currencyCode("USD")//
.value(format.format(cost))//
.amountBreakdown(new AmountBreakdown()//
.itemTotal(new Money()//
.currencyCode("USD")//
.value(format.format(cost)))//
.shipping(new Money()//
.currencyCode("USD")//
.value("0.00"))//
.handling(new Money()//
.currencyCode("USD")//
.value("0.00"))//
.taxTotal(new Money()//
.currencyCode("USD")//
.value("0.00"))//
.shippingDiscount(new Money()//
.currencyCode("USD")//
.value("0.00"))))
.items(new ArrayList<Item>(){
private static final long serialVersionUID = 1L;
{
add(new Item()//
.name(desc)//
.description(desc)//
.sku("sku01").//
unitAmount(new Money()//
.currencyCode("USD")//
.value(format.format(individualCost)))//
.tax(new Money()//
.currencyCode("USD")//
.value("0.00"))//
.quantity(String.valueOf(quantity))//
.category("DIGITAL_GOODS"));
}
});
purchaseUnitRequests.add(purchaseUnitRequest);
orderRequest.purchaseUnits(purchaseUnitRequests);
request.requestBody(orderRequest);
HttpResponse<Order> response = client().execute(request);
if(response.statusCode() == 201){
for(com.paypal.orders.LinkDescription link : response.result().links()){
log.info(link.rel() + ": " + link.href() + "; Call Type: " + link.method());
}// end for
log.info("Total Amount: " + response.result().purchaseUnits().get(0).amountWithBreakdown().currencyCode() + " " + response.result().purchaseUnits().get(0).amountWithBreakdown().value());
log.info(new JSONObject(new Json().serialize(response.result())).toString(4));
}// end if
if(log.isDebugEnabled()){
log.debug("Return value is: response=" + String.valueOf(response));
}// end if
log.debug("Exiting createCustomerOrder");
return response;
}// end createCustomerOrder
Using the sandbox I am forwarded to PayPal. I follow the steps to PAY for the purchase. I know I have to CAPTURE the order but I can't figure out how. Upon redirect from PAYPAL I am saving the purchase to the database. The problem is PAYPAL is forwarding to my site like the payment was made. When in fact there is nothing in PAYPAL indicating a payment.
I am currently using the checkout.jar
Is there a way to do this without using javascript? I don't want to have to complete restructure the application.

The payment does not complete at PayPal. For redirect integrations, after the return to your site you need to capture the order and show the result (success/thank you, or failure/try again). The URL will contain the necessary IDs for capture.
Current integrations don't use any redirects. At all. (API responses have redirect URLs for old websites using such an integration pattern)
Instead, create two routes on your server for the create order and capture order APIs, respectively. The capture route must take an id as input (path or body parameter), so it knows which to capture. Both routes should return/output only JSON data, no HTML or text.
Pair those two routes with the following approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server

After several weeks of trial and error, I finally got the js free PayPal implementation working.
There are 3 steps necessary to complete a PayPal Transaction.
Step 1. Create The Order. This step will take the customer to the PayPal site.
Class Variables: private PayPalClient client = new PayPalClient(); private PayPalHttpClient hClient = new PayPalHttpClient(client.getEnvironment());
protected int doPaypalOrderWithCustomer(PayPalPurchase purchase, Customer customer) throws PayPalException {
log.info("ENVIRONMENT: " + String.valueOf(client.getEnvironment()));
orderResponse = null;
try{
orderId = "";
// Creating an order payload
OrdersCreateRequest request = new OrdersCreateRequest();
// Build PayPal Request Body
request = client.createCustomerOrder("Company Order", purchase.getTotalCheckoutCost(), 1, customer);
// Create Order
orderResponse = hClient.execute(request);
log.info("Creating Order...");
if(orderResponse.statusCode() == 201){
log.info("Order with Complete Payload: ");
log.info("Status Code: " + orderResponse.statusCode());
log.info("Status: " + orderResponse.result().status());
log.info("Order ID: " + orderResponse.result().id());
log.info("Intent: " + orderResponse.result().checkoutPaymentIntent());
log.info("Links: ");
for(LinkDescription link : orderResponse.result().links()){
log.info("\t" + link.rel() + ": " + link.href() + "\tCall Type: " + link.method());
}// end for
log.info("Total Amount: " + orderResponse.result().purchaseUnits().get(0).amountWithBreakdown().currencyCode() + " " + orderResponse.result().purchaseUnits().get(0).amountWithBreakdown().value());
log.info("Full response body:");
log.info("Authorized Successfully\n");
orderId = orderResponse.result().id();
log.info("PURCHASE UNIT ORDER ID: " + orderId);
for(LinkDescription link : orderResponse.result().links()){
String check = link.rel();
log.info(link.rel() + ": " + link.href());
if(check.equalsIgnoreCase("approve")){
log.info("Request Approved");
ServletActionContext.getResponse().sendRedirect(link.href());
break;
}else{
log.info("CURRENT LINK: " + link.rel() + " NOT APPROVED");
}// end if
}// end for
sessionMap.put("orderId", orderId);
}// end if
log.info("Created Successfully");
}catch(Exception e){
throw new PayPalException("Creating a PayPal order failed. Message is: " + e.getMessage(), e);
}finally{
if(null != orderResponse){
log.info("Order response status code is: " + String.valueOf(orderResponse.statusCode()));
}else{
log.info("Order response is null.");
}// end if/else
}// end try/catch/finally
return orderResponse.statusCode();
}// end doPaypalOrderWithCustomer
public OrdersCreateRequest createCustomerOrder(String desc, double cost, int quantity, Customer customer) throws Exception {
log.debug("Entering createCustomerOrder");
if(log.isDebugEnabled()){
log.debug("Method to create order with complete payload");
log.debug("Entry parameters are: desc=" + String.valueOf(desc) + ", cost=" + String.valueOf(cost) + ", quantity=" + String.valueOf(quantity) + ", Customer=" + String.valueOf(customer));
}// end if
double individualCost = cost / quantity;
NumberFormat format = NumberFormat.getNumberInstance();
format.setMaximumFractionDigits(2);
format.setMinimumFractionDigits(2);
OrdersCreateRequest request = new OrdersCreateRequest();
request.header("prefer", "return=representation");
OrderRequest orderRequest = new OrderRequest();
orderRequest.checkoutPaymentIntent("AUTHORIZE");// This must be AUTHORIZE for the 3 step process
Payer payer = new Payer();
payer.email(customer.getEmail());
PhoneWithType phoneWithType = new PhoneWithType();
Phone phone = new Phone();
String phoneNumber = customer.getPhoneNo().replace("(", "");
phoneNumber = customer.getPhoneNo().replace(")", "");
phoneNumber = customer.getPhoneNo().replace("-", "");
phoneNumber = phoneNumber.replaceAll("\\D+", "");
phone.nationalNumber(phoneNumber);
phoneWithType.phoneNumber(phone);
payer.phoneWithType(phoneWithType);
orderRequest.payer(payer);
ApplicationContext applicationContext = new ApplicationContext() //
.brandName("Company, LLC")//
.landingPage("BILLING")//
.cancelUrl(bundle.getString("RESPONSE_URL") + "?t=c")//
.returnUrl(bundle.getString("RESPONSE_URL") + "?t=r")//
.userAction("CONTINUE").shippingPreference("NO_SHIPPING");
orderRequest.applicationContext(applicationContext);
List<PurchaseUnitRequest> purchaseUnitRequests = new ArrayList<>();
PurchaseUnitRequest purchaseUnitRequest = new PurchaseUnitRequest()//
.referenceId("PUHF")//
.description("Digital Content")//
.customId("CUST-DigitalContent")//
.softDescriptor("DigitalContent")//
.amountWithBreakdown(new AmountWithBreakdown()//
.currencyCode("USD")//
.value(format.format(cost))//
.amountBreakdown(new AmountBreakdown()//
.itemTotal(new Money()//
.currencyCode("USD")//
.value(format.format(cost)))//
.shipping(new Money()//
.currencyCode("USD")//
.value("0.00"))//
.handling(new Money()//
.currencyCode("USD")//
.value("0.00"))//
.taxTotal(new Money()//
.currencyCode("USD")//
.value("0.00"))//
.shippingDiscount(new Money()//
.currencyCode("USD")//
.value("0.00"))))
.items(new ArrayList<Item>(){
private static final long serialVersionUID = 1L;
{
add(new Item()//
.name(desc)//
.description(desc)//
.sku("sku01").//
unitAmount(new Money()//
.currencyCode("USD")//
.value(format.format(individualCost)))//
.tax(new Money()//
.currencyCode("USD")//
.value("0.00"))//
.quantity(String.valueOf(quantity))//
.category("DIGITAL_GOODS"));
}
}).shippingDetail(new ShippingDetail()//
.name(new Name()//
.fullName(customer.getFirstNm() + " " + customer.getLastNm()))//
.addressPortable(new AddressPortable()//
.addressLine1(customer.getAddress())//
.addressLine2(customer.getAddress2())//
.adminArea1(customer.getState())//
.adminArea2(customer.getCity())//
.postalCode(customer.getZipCode())//
.countryCode("US")));
purchaseUnitRequests.add(purchaseUnitRequest);
orderRequest.purchaseUnits(purchaseUnitRequests);
request.requestBody(orderRequest);
HttpResponse<Order> response = client().execute(request);
if(response.statusCode() == 201){
for(com.paypal.orders.LinkDescription link : response.result().links()){
log.info(link.rel() + ": " + link.href() + "; Call Type: " + link.method());
}// end for
log.info("Total Amount: " + response.result().purchaseUnits().get(0).amountWithBreakdown().currencyCode() + " " + response.result().purchaseUnits().get(0).amountWithBreakdown().value());
log.info(new JSONObject(new Json().serialize(response.result())).toString(4));
}// end if
if(log.isDebugEnabled()){
log.debug("Return value is: response=" + String.valueOf(request));
}// end if
log.debug("Exiting createCustomerOrder");
return request;
}// end createCustomerOrder
Step 2: We Approve the order and get an authorized order id from PayPal.
public String approve() throws Exception {
log.debug("Entering approve method.");
log.trace("This method is used to approce purchases Post PayPal redirect.");
log.info("Authorizing Order...");
HttpServletRequest request = ServletActionContext.getRequest();
String cancel = request.getParameter("t");
log.info("Parameter being returned from PayPal: " + String.valueOf(cancel));
if(cancel.equalsIgnoreCase("c")){
payPalCancel = true;
if(null != sessionMap.get("purchase")){
sessionMap.remove("purchase");
}// end if
if(null != sessionMap.get("cartCount")){
sessionMap.put("cartCount", 0);
}// end if
setCartCount(0);
if(null != sessionMap.get("images")){
sessionMap.remove("images");
}// end if
setPayPalCancel(true);
return INPUT;
}else{
if(null != sessionMap.get("orderId")){
orderId = (String) sessionMap.get("orderId");
}// end if
log.info("Order ID: " + String.valueOf(orderId));
OrdersAuthorizeRequest orderAuthorizeRequest = new OrdersAuthorizeRequest(orderId);
orderAuthorizeRequest.requestBody(new OrderRequest());
orderResponse = hClient.execute(orderAuthorizeRequest);
if(orderResponse.statusCode() == 201){
authOrderId = orderResponse.result().purchaseUnits().get(0).payments().authorizations().get(0).id();
log.info("AUTHORIZED ORDER ID: " + authOrderId);
}// end if
sessionMap.put("authOrderId", authOrderId);
log.debug("Exiting approve");
}// end if/else
return SUCCESS;
}// end approve
Step 3: As the developer we must Capture that approved order. This is the final step.
public String capture() throws Exception {
log.debug("Entering capture method.");
log.trace("This method is used to save capture Payment.");
// Capturing authorized order
if(null != sessionMap.get("authOrderId")){
authOrderId = (String) sessionMap.get("authOrderId");
}// end if
log.info("Authorized Order ID: " + String.valueOf(authOrderId));
log.info("Capturing Order...");
setCaptured(true);
HttpResponse<Capture> captureOrderResponse = new CaptureOrder().captureOrder(authOrderId, true);
if(captureOrderResponse.statusCode() == 201){
log.info("Captured Successfully");
log.info("Status Code: " + captureOrderResponse.statusCode());
log.info("Status: " + captureOrderResponse.result().status());
log.info("Capture ID: " + captureOrderResponse.result().id());
log.info("Links: ");
for(com.paypal.payments.LinkDescription link : captureOrderResponse.result().links()){
log.info("\t" + link.rel() + ": " + link.href() + "\tCall Type: " + link.method());
}// end for
}// end if
log.debug("Exiting capture");
return SUCCESS;
}// end capture
Thanks to everyone who helped. I'm new at this and may have done somethings wrong, but I was finally able to get it to work.

Related

android display arraylist items in dialog

I am having an arraylist fetching name and status of a person. Arraylist is storing the status and name. Its displaying one name at a time. How can I be able to display multiple names at once in alert dialog?
private ArrayList getunfiledRogspDoctorList() {
SqlDataStore sd = new SqlDataStore(this);
sd.open();
String gspQuery = " SELECT * FROM "+ TABLE_DOCTOR + " WHERE " + Queryclass.DOCTOR_ROGSP_STATUS + " == " + 0 + " AND " + Queryclass.DOCTOR_DATE_ID + " = '" + selectionID + "'";
Cursor gspCu = sd.getData(gspQuery);
if(gspCu.moveToFirst()){
do {
rogspname = gspCu.getString(gspCu.getColumnIndex(Queryclass.DOCTOR_CONTACTNAME));
unfiledrogspDoctorList.add(gspCu.getString(gspCu.getColumnIndex(Queryclass.DOCTOR_ROGSP_STATUS)) + rogspname);
}while (gspCu.moveToNext());
}
gspCu.close();
sd.close();
System.out.println("unfiledrogspDoctorList "+unfiledrogspDoctorList);
return unfiledrogspDoctorList;
}
From the code, you are having an ArrayList of your target display String in unfiledrogspDoctorList:
// Suggest to also define the type of your returning ArrayList
private ArrayList<String> getunfiledRogspDoctorList() {
// Define a local ArrayList
ArrayList<String> unfiledrogspDoctorList = new ArrayList<>();
SqlDataStore sd = new SqlDataStore(this);
sd.open();
String gspQuery = " SELECT * FROM "+ TABLE_DOCTOR + " WHERE " + Queryclass.DOCTOR_ROGSP_STATUS + " == " + 0 + " AND " + Queryclass.DOCTOR_DATE_ID + " = '" + selectionID + "'";
Cursor gspCu = sd.getData(gspQuery);
if(gspCu.moveToFirst()){
do {
rogspname = gspCu.getString(gspCu.getColumnIndex(Queryclass.DOCTOR_CONTACTNAME));
unfiledrogspDoctorList.add(gspCu.getString(gspCu.getColumnIndex(Queryclass.DOCTOR_ROGSP_STATUS)) + rogspname);
}while (gspCu.moveToNext());
}
gspCu.close();
sd.close();
System.out.println("unfiledrogspDoctorList "+unfiledrogspDoctorList);
return unfiledrogspDoctorList;
}
You can consider to convert your ArrayList of String into just a String.
private String concat(ArrayList<String> unfiledrogspDoctorList) {
StringBuilder sb = new StringBuilder();
for (String item : unfiledrogspDoctorList) {
sb.append(item);
sb.append(","); // Or change into other separate you would like to display
}
sb.setLength(Math.max(0, sb.length() - 1)); // Remove the appending character
return sb.toString();
}
Then you can make use of an AlertDialog to display that concatenated String.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setMessage(concat(getunfiledRogspDoctorList()))
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Do anything upon pressing OK button
}
);
AlertDialog alert = builder.create();
alert.show();
You could use :-
SELECT group_concat(name) FROM ....
or to place each on a line you could change the default comma separator to a line feed using
SELECT group_concat(name,'\n') FROM ....
.... representing the rest of the SQL in the question
See https://www.sqlite.org/lang_aggfunc.html#group_concat
note that the GROUP as no GROUP BY clause is provided is a single group (and therefore output row) made up of ALL extracted rows.

reading the date from sqlite in android

I am storing some date in sqlite and when I try to retrieve data, it is returning null.
private ArrayList<String> file_list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> _list = db.get_file
(String.valueOf(myFiles.get(position).getId()), file_list);
Log.e("TAG","_list " + _list);
case R.id.get_file:
boolean save_file = db.add_file(String.valueOf(myFiles.get(position).getId()),
file_list);
if (save_file){
Toast.makeText(this, "saved successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "saved failed", Toast.LENGTH_SHORT).show();
}
public ArrayList<String> get_file(String id, ArrayList<String> arrayList){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + COL_FILE + " FROM "
+TABLE_NAME+" WHERE " + _ID +" =? " , new String[] {String.valueOf(id)});
if(cursor.moveToFirst()){
return arrayList;
} else {
return null;
}
}
public TrackGroupArray read_tga_file(String id, TrackGroupArray tga)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + TGA_FILE + " FROM "
+TABLE_NAME+" WHERE " + _ID +" =? " , new String[] {String.valueOf(id)});
if(cursor.moveToFirst()){
return tga;
} else {
return null;
}
}
TrackGroupArray read_tga = db.read_tga_file(String.valueOf(myFiles.get(position).getId()),
trackGroupArray);
Every time I save a file, it is saved successfully, I have checked in the db and the file is there. But when I want to retrieve it, Log.e("TAG","_list " + _list); returns null.
Your get_File method, even if there is a row and the moveToFirst succeeds, will always return null as in the event that a row is located/selected you do nothing other than return an un-instantiated arrayList.
You need to
a) instantiate the arrayList (otherwise it will be null) and then
b) add elements to the arrayList for each row that exists if any.
So something like :-
#SuppressLint("Range")
public ArrayList<String> get_file(String id, ArrayList<String> arrayList) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + COL_FILE + " FROM "
+ TABLE_NAME + " WHERE " + _ID + " =? ", new String[]{String.valueOf(id)});
ArrayList<String> rv = new ArrayList<>(); //<<<<< A instantiate the ArrayList<String>
/* Loop through the returned row(s) if any */
while (cursor.moveToNext()) {
/* for each iteration add an element to rv (the ArrayList) */
rv.add(cursor.getString(cursor.getColumnIndex(COL_FILE)));
}
cursor.close(); //<<<<< should ALWAYS close Cursors when done with them
return rv; // return the arraylist
}

.net core 3.1 Worker Service

I am trying to create a TCP Listener as worker service. Any how managed to achieve the flow for Client Request and Server Response. But from browser when I try to browse the Url for the Application debugger hits the action method and writes the response in a stream but not able to return any response from the Main Thread of worker service i.e. ExecuteAsync method.
Any help in this regards would really help min completing this task.
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
Task.Run(() => _serverStatus = _tcpHandler.StartServer().Result).Wait();
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now
+ Environment.NewLine
+ String.Format("Server Started with status : {0}", _serverStatus)
+ Environment.NewLine
+ String.Format("Client Message : {0}", _tcpHandler.GetServerResponse())
+ Environment.NewLine
+ String.Format("Number of Requests recieved : {0}", _tcpHandler.GetRequestCounter()));
// _logger.LogInformation("Server running at: {0}", _tcpHandler.StartServer().Result);
await Task.Delay(1000, stoppingToken);
}
}
public async Task<string> StartServer()
{
string serverResponse = String.Empty;
try
{
await Task.Delay(1000);
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
serverResponse = "Status - Active";
// Perform a blocking call to accept requests.
// You could also use server.AcceptSocket() here.
_tcpClient = _tcpListener.AcceptTcpClientAsync().Result;
Console.WriteLine("Connected!");
Console.WriteLine(Environment.NewLine + "Waiting for Requests ...");
Thread t = new Thread(() => {
serverResponse = RequestHandler(_tcpClient).Result;
});
t.Start();
return serverResponse;
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
return "Status - Inactive";
}
}
public async Task<string> RequestHandler(object client)
{
string response = String.Empty;
try
{
// Set the TcpListener on port 13000.
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
// while (true)
//{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also use server.AcceptSocket() here.
TcpClient tcpClient = (TcpClient)client;
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
using (NetworkStream stream = tcpClient.GetStream())
{
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
_requestCounter++;
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
_requestedMessage = data;
Console.WriteLine("Message Received by Server: {0}", data);
// Process the data sent by the client.
data = "Hey ! Client ..." + data.ToUpper();
string xml = Environment.NewLine + "<Messages>"
+ Environment.NewLine + "<Message>"
+ Environment.NewLine + "<Date>" + DateTime.Now.ToString() + "</Date>"
+ Environment.NewLine + "<Text>" + data + "</Text>"
+ Environment.NewLine + "<status>" + "accepted" + "</status>"
+ Environment.NewLine + "<statuscode>" + "1" + "</statuscode>"
+ Environment.NewLine + "</Message>"
+ Environment.NewLine + "</Messages>";
// Send back a response.
byte[] httpHeaders = System.Text.Encoding.ASCII.GetBytes("HTTP/1.1 200 OK");
byte[] httpContentType = System.Text.Encoding.ASCII.GetBytes("Content-Type: text/xml");
byte[] httpContentLength = System.Text.Encoding.ASCII.GetBytes("Content - Length: " + xml.Length);
byte[] newLine = System.Text.Encoding.ASCII.GetBytes(Environment.NewLine);
byte[] msg = System.Text.Encoding.ASCII.GetBytes(xml);
stream.Write(httpHeaders, 0, httpHeaders.Length);
stream.Write(httpContentType, 0, httpContentType.Length);
stream.Write(httpContentLength, 0, httpContentLength.Length);
stream.Write(newLine);
stream.Write(msg, 0, msg.Length);
response = xml;
Console.WriteLine("Reply sent from Server: {0}", data);
}
stream.Close();
}
// Loop to receive all the data sent by the client.
// Shutdown and end connection
tcpClient.Close();
//}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
return response;
}
found solution for getting xml response in browser from a tcp background service, instead of using NetworkStream StremReader will do the job for handling passed arguments and StreamWriter will write a response back to client.

Getting FormPanel's field values

I'm having problems with getting the value of the fields coming from a FormPanel. Theonly thing I get is the image included in the form here is the servlet code, I'm using Apache Commons:
// Create a new file upload handler
ServletFileUpload upload1 = new ServletFileUpload();
// Parse the request
FileItemIterator iter;
try {
iter = upload1.getItemIterator(req);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
System.out.println("Form field " + name + " with value "
+ Streams.asString(stream) + " detected.");
} else {
System.out.println("File field " + name + " with file name "
+ item.getName() + " detected.");
// Process the input stream
}
}
} catch (FileUploadException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I have seen this post but it didn't really explain what to do
Like #Colin Alworth said, the name property must be set for each field!
TextBox lastName = new TextBox();
lastName.setName("LastName");

Stackmob is giving 401 error while registering device

I am registering the device to stackmob with username and device token . I am getting valid tokens from c2dn and then storing it into db for that user and then while registering to stackmob i am using these parameters. On dev environment its working fine but same piece of code is giving 401 while registering the device. Please suggest me in this.
The code for this is below :
public String registerWithNotificationServiceProvider(final String userName, final String deviceToken) throws UserException
{
if (userName.isEmpty() || deviceToken.isEmpty()) {
throw new UserException(ResponseCodes.STATUS_BAD_REQUEST, "User Name or device token is null",## Heading ## "label.invalid.user.device.details");
}
StackMobRequestSendResult deviceRegisterResult = null;
deviceRegisterResult = StackMob.getStackMob().registerForPushWithUser(userName, deviceToken,
new StackMobRawCallback() {
#Override
public void done(HttpVerb requestVerb, String requestURL,
List<Map.Entry<String, String>> requestHeaders, String requestBody,
Integer responseStatusCode, List<Map.Entry<String, String>> responseHeaders,
byte[] responseBody) {
String response = new String(responseBody);
logger.info("request Body is " + requestBody);
logger.info("request Url is " + requestURL);
for(Map.Entry<String, String> entry : requestHeaders){
logger.info("Request Header is " + entry.getKey());
logger.info("Request Header content is " + entry.getValue());
}
for(Map.Entry<String, String> entry : responseHeaders){
logger.info("Response Header is " + entry.getKey());
logger.info("Response Header content is " + entry.getValue());
}
logger.info("response while registering the device is " + response);
logger.info("responseCode while registering device " + responseStatusCode);
}
});
String status = null;
if (deviceRegisterResult.getStatus() != null) {
status = deviceRegisterResult.getStatus().name();
logger.debug("For user : " + userName + " Status for registering device is " + status);
}
if (Status.SENT.getStatus().equalsIgnoreCase(status)) {
return Status.SUCCESS.getStatus();
} else {
return Status.FAILURE.getStatus();
}
}
When you setup your StackMob object with the api key and secret, do you remember to use apiVersion 1 with your production key and secret? That's the most likely problem.
StackMobCommon.API_KEY = KEY;
StackMobCommon.API_SECRET = SECRET;
StackMobCommon.USER_OBJECT_NAME = "user";
StackMobCommon.API_VERSION = 1; //! 0 for dev, 1 for production
If that doesn't work also set
StackMob.getStackMob().getLogger().setLogging(true);
at the beginning and post the resulting logs