ksoap connection with web service, no android (using ksoap) - java-me

well i am doing a connection... sql server with web service, web service with j2me, but now i am doing one helloworld...i could it, but now than i want to do one "hello world "+nombre...
parameter is not receive in web service, here the web service
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// Para permitir que se llame a este servicio web desde un script, usando ASP.NET AJAX, quite la marca de comentario de la línea siguiente.
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
public Service () {
}
[WebMethod]
public string HelloWorld(String nombre)
{
return "Que onda " + nombre;
}
}
and this is the code for call it with ksoap...
String nombremetodo="HelloWorld";
String url="http://localhost:49175/WebSite1/Service.asmx";
String namespace="http://tempuri.org/";
String SOAP_ACTION=namespace+nombremetodo;
public void traer()
{
SoapObject busqueda =new SoapObject(namespace,nombremetodo);
HttpTransport transportacion = new HttpTransport(url);
busqueda.addProperty(new String("nombre"),new String("Angel"));
System.out.println("parametro agregado");
//busqueda.addProperty(PropertyInfo.OBJECT_TYPE, "Angel");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
transportacion.debug=true;
envelope.bodyOut=busqueda;
System.out.println("todo ok");
try{
System.out.println("comenzando transportacion");
transportacion.call(SOAP_ACTION, envelope);
System.out.println("transportacion ok");
respuesta = envelope.getResponse().toString();
System.out.println("respuesta ok");
}
catch(Exception e)
{
texto.setString("fallo");
System.out.println("falla en el try");
System.out.println(e);
}
}
i get it returns "que onda " with a space, because so i put it in web service, but never it returns "que onda "+nombre ... it is a application for j2me not for
android, i watch for android it is soo...
PropertyInfo p1 = new PropertyInfo();
p1.setName("nombre");
p11.setValue("Angel");
busqueda.addProperty(p1);
but ksoap for j2me doesn't have those methods.. "setName, setValue";
i have downloades this library but i get a ugly bug and application doesn't run...
with this i see parameter is added so..
busqueda.addProperty("nombre","Angel");
but this it doesn't work...
it does run it doesn't have any bug, but web service never receive the parameter...
thank you people of STACKOVERFLOW
my english is not very well sorry

i solved it, it is necesary write
envelope.dotNet=true;

Related

httpcontextaccessor null reference on app service but not debug

I have a weird issue I can't explain.
I have a helper class in my Blazor Server Side app that does arb functions for my app. I added services.AddHttpContextAccessor(); in startup,
declared it in my helper class
public GlobalHelper(IHttpContextAccessor accessor,
IOptions<AzureADB2COptions> azureAdB2COptions,
IConfiguration configuration
)
{
_accessor = accessor;
AzureAdB2COptions = azureAdB2COptions.Value;
Configuration = configuration;
}
and then have a function to return the userid:
public string GetUserID()
{
var context = _accessor.HttpContext;
return context.User.FindFirst(ClaimTypes.NameIdentifier).Value;
and then in my page, I just want to display it first on a button click event:
#inject Classes.GlobalHelper _helper
<h1>Counter</h1>
<p>Current count: #currentCount</p>
<button class="btn btn-primary" #onclick="IncrementCount">Click me</button>
#code {
string currentCount = "test";
void IncrementCount()
{
var test4 = httpContextAccessor.HttpContext;
var authState = AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.Result.User;
if (user.Identity.IsAuthenticated)
{
try
{
currentCount = _helper.GetUserID().Result;
}
catch (Exception ex)
{
currentCount = ex.ToString();
}
}
else
{
Console.WriteLine("The user is NOT authenticated.");
}
}
}
If I just debug locally, this works fine. As soon as I publish this to an app service in Azure... I get a nullreferenceexception on accessing the httpcontextaccessor in the globalhelper class. This line:
return context.User.FindFirst(ClaimTypes.NameIdentifier).Value;
What could I be doing wrong so that the httpcontext is null in the app service and not in debug on my local machine?
The HttpContext is not available, at least most of the time, in Blazor Server App. You shouldn't try to access it, and you shouldn't use IHttpContextAccessor. Read more here:
https://github.com/aspnet/AspNetCore/issues/14090
https://github.com/aspnet/AspNetCore/issues/13903
https://github.com/aspnet/AspNetCore/issues/12432#issuecomment-534315513
https://github.com/aspnet/AspNetCore/issues/5330#issuecomment-413928731
Note: You may access Authentication State in Blazor Server App via the AuthenticationStateProvider object and authorization components such as AuthorizeView, AuthorizeRouteView and CascadingAuthenticationState depending on what you want to do.

Error while processing request in AzureMobile Apps HTTP2 error

This question is specific to a lately strange behavior of the Azure mobile Apps Android sdk. Everything was working fine for weeks. Now, my android client app suddenly can't connect to my web app any more. A Toast says "Error while processing request". In Android Studio debugger, I found the exception inside the SDK file MobileServiceConnection.java.
java.io.IOException: stream was reset: PROTOCOL_ERROR
In Azure Portal, my app shows "Healthy" status, but I can see the HTTP errors. Please help.
Following is my code, which was working fine and now throws error.
// Create the Mobile Service Client instance, using the provided mobile app URL.
try {
mClient = new MobileServiceClient(mMobileBackendUrl, activityContext).withFilter(
new ServiceFilter() {
#Override
public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilter) {
// Get the request contents
String url = request.getUrl();
String content = request.getContent();
if (url != null) {
Log.d("Request URL:", url);
}
if (content != null) {
Log.d("Request Content:", content);
}
// Execute the next service filter in the chain
ListenableFuture<ServiceFilterResponse> responseFuture = nextServiceFilter.onNext(request);
Futures.addCallback(responseFuture, new FutureCallback<ServiceFilterResponse>() {
#Override
public void onFailure(Throwable exception) {
Log.d("Exception:", exception.getMessage());
}
#Override
public void onSuccess(ServiceFilterResponse response) {
if (response != null && response.getContent() != null) {
Log.d("Response Content:", response.getContent());
}
}
});
return responseFuture;
}
}
);
setAzureClient(mClient);
}catch(MalformedURLException e){
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}catch(Exception e){
createAndShowDialog("There was an error creating the Mobile Service. "+ e.toString(), "Error");
}
Toast.makeText(context, context.getString(R.string.online_authentication), Toast.LENGTH_SHORT).show();
authenticate();
}
private void authenticate() { // give access only to authenticated users via Google account authentication
HashMap<String, String> parameters = new HashMap<>();
parameters.put("access_type", "offline");//use "Refresh tokens"
//login with the Google provider. This will create a call to onActivityResult() method inside the context Activity, which will then call the onActivityResult() below.
mClient.login(MobileServiceAuthenticationProvider.Google, url_scheme_of_your_app, GOOGLE_LOGIN_REQUEST_CODE, parameters);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When request completes
if (requestCode == 1) {
try {
MobileServiceActivityResult result = mClient.onActivityResult(data);
if (result.isLoggedIn()) {
Toast.makeText(context, context.getString(R.string.azure_auth_login_success) /*+ " " + mClient.getCurrentUser().getUserId()*/, Toast.LENGTH_SHORT).show();
mUserId = mClient.getCurrentUser().getUserId();
} else {//>>>>THIS IS WHERE I AM GETTING THE ERROR
String errorMessage = result.getErrorMessage();
Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();// Error While processing request (it comes form the MobileServiceConnection.java file inside sdk)
}
}catch(Exception e){
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
I found the answer myself. The error was due to an Azure App Service HTTP2 connection issue. It has nothing to do with the app code. For anyone facing the same problem, here is the solution.
Go to https://resources.azure.com/
Make sure you are in Read/Write mode by clicking in the option to the left of your name.
From the left column, browse to: https://resources.azure.com/subscriptions/yourSubscriptionId/resourceGroups/yourWebAppResourceGroup/providers/Microsoft.Web/sites/yourWebAppName/config/web
Find and Change the property: "http20Enabled": from true to false by clicking EDIT, Update value to “false” and then clicking in Save or PATCH.

Implementation of push notification using oracle maf

Iam able to register using device token.but I didn't receive message from my server.I have registered my project with GCM and got project Id ,server key.
enter code here
public void onMessage(Event event) {
String msg;
msg = event.getPayload();
System.out.println("#### Message from the Server :" + msg);
String one="";
AdfmfContainerUtilities.invokeContainerJavaScriptFunction(AdfmfJavaUtilities.getFeatureId(), "usercheck", new Object[]{msg});
// Parse the payload of the push notification
HashMap payload = null;
String pushMsg = "No message received";
try
{
payload = (HashMap)JSONBeanSerializationHelper.fromJSON(HashMap.class, msg);
pushMsg = (String)payload.get("alert");
}
catch(Exception e) {
e.printStackTrace();
}
// Write the push message to app scope to display to the user
AdfmfJavaUtilities.setELValue("#{applicationScope.pushMessage}", pushMsg);
}
public void onError(AdfException adfException) {
System.out.println("#### Error: " + adfException.toString());
// Write the error into app scope
AdfmfJavaUtilities.setELValue("#{applicationScope.errorMessage}", adfException.toString());
}
public void onOpen(String token) {
System.out.println("#### Registration token:" + token);
// Clear error in app scope
AdfmfJavaUtilities.setELValue("#{applicationScope.errorMessage}", null);
// Write the token into app scope
AdfmfJavaUtilities.setELValue("#{applicationScope.deviceToken}", token);
}
}
I think this article will help you. I was able to get them done for GCM but not for APN yet.
For registering with Google Cloud Messaging, go to this link, then click on "Get configuration" button.
In the server application, set your device token and sender id properly. The message is sent using these.
Since you got the deviceId from the server then i think the issue is not with the code. Did you enable PushPlugin in maf-application.xml ?

How to send string data to socket connection via telnet or any other program?

I am trying to send and receive string data to socket connection via telnet, but I am not able to type or see anything in the telnet window. I am able to connect to the server via telnet, but not able to send the string data.
Is there any other alternate method to send string data over socket connection.
Telnet, unless it negotiates parameters to the contrary, does "remote echo" meaning that you won't see anything you type unless the server echos it back.
A lot of people use the term "Telnet" when really it is a raw socket connection that does no configuration negotiation upon connect.
If you're sending data from a file or source other than the keyboard (and even often when sending from the keyboard), you're better of using a program like socket or nc (netcat) which don't attempt to do any processing of the data stream and so provide simple 8-bit clean connections.
In the case of both those problems, you can simply redirect stdin from a file or echo a string to them through a pipe.
i have a example of a server that talks to with many telnet client.
You must use the class DataInputStream and DataOutputStream
You must use A Class Implements Runnable for establish multiple sessions
You must use a ServerSocket Class.
Good, this is the code of the main class called SocketServerExample:
import java.net.*;
import java.io.*;
import socketserverexample.ThreadServer;
/**
*
* #author JuanLuisHiciano
*/
public class SocketServerExample {
public static void main(String args[]) throws InterruptedException {
ServerSocket mi_servicio = null;
String linea_recibida;
DataInputStream entrada = null;
DataOutputStream salida = null;
Socket socket_conectado = null;
try {
mi_servicio = new ServerSocket(2017);
}
catch (IOException excepcion) {
System.out.println(excepcion);
}
try {
int n=1;
while(n<2){
socket_conectado = mi_servicio.accept();
System.out.println("Un cliente se a conectado "+socket_conectado.getPort());
entrada= new DataInputStream(socket_conectado.getInputStream());
String nombre = entrada.readUTF();
// Se instancia una clase para atender al cliente y se lanza en
// un hilo aparte.
Runnable nuevoCliente = new ThreadServer(nombre, socket_conectado); //Input and Output data Channels
Thread hilo = new Thread(nuevoCliente);
hilo.start();
}
salida.writeUTF("Fin de la conexion....");
salida.close();
entrada.close();
socket_conectado.close();
}
catch (IOException excepcion) {
System.out.println(excepcion);
}
}
}
ok,This run de Main Server with the UTP port (2017) and delivering sessions to other threads to receive new connections.
Good , below is the code of the class Called ThreadServer :
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author JuanLuisHiciano
*/
public class ThreadServer implements Runnable{
DataInputStream entrada;
DataOutputStream salida;
Socket socket_conectado = null;
String linea_recibida;
String cliente;
ThreadServer(String cliente,Socket socket) {
socket_conectado = socket;
this.cliente=cliente;
}
#Override
public void run() {
int n=0;
while(n<3){
try {
salida = new DataOutputStream(socket_conectado.getOutputStream());
entrada = new DataInputStream(socket_conectado.getInputStream());
//System.out.println("Confirmando Conexion al cliente .....");
salida.writeUTF("Conexion Exitosa\n");
salida.writeUTF("Puede compartir un mensaje : ");
//recepcion de mensaje
linea_recibida = entrada.readUTF();
System.out.println(cliente+" dice: "+linea_recibida);
System.out.println(socket_conectado.getPort());
n++;
} catch (IOException ex) {
Logger.getLogger(ThreadServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
With this code you can talk to each of the clients connecting.
Goodbye Saludos de Republica Dominicana
I hope you serve something this code.

Redirect to page in liferay Login

I am creating a Hook to check-user on login, and depending on some parameters it will be redirected to one custom page or another.
I am doing this:
Portal.properties
#Gestion evento login
login.events.post=com.liferay.portal.events.AccionLogin
auth.forward.by.last.path=true
Action Class
public class AccionLogin extends Action {
#Override
public void run(HttpServletRequest request, HttpServletResponse response) throws ActionException {
try {
doRun(request, response);
} catch (Exception e) {
throw new ActionException(e);
}
}
protected void doRun(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession sesion = request.getSession();
User usuarioLogin = PortalUtil.getUser(request);
// Recupero la lista de roles
ArrayList<Role> roles = UtilRoles.getIntExtRol();
// Compruebo si el usuario pertenece al grupo
if (UtilLdap.esGrupo(request, usuarioLogin.getScreenName())) {
Constantes._log.info("El usuario es Interno en el Ldap vector. Gestiono su rol");
UtilRoles.setRoleIfNotHave(usuarioLogin, roles, Constantes.INTERNOS);
sesion.setAttribute(WebKeys.LAST_PATH, UtilUrls.generaLasthPath(request, Constantes.INTERNOS));
} else {
Constantes._log.info("El usuario es externo en el Ldap vector. Gestiono su rol");
UtilRoles.setRoleIfNotHave(usuarioLogin, roles, Constantes.EXTERNOS);
sesion.setAttribute(WebKeys.LAST_PATH, UtilUrls.generaLasthPath(request, Constantes.EXTERNOS));
}
}
}
This method:
sesion.setAttribute(WebKeys.LAST_PATH, UtilUrls.generaLasthPath(request, Constantes.EXTERNOS));
do it:
return new LastPath(StringPool.BLANK,Constantes.GROUPINTRANET+Constantes.SEPARADOR+Constantes.INICIOINTERNOS,
new HashMap<String, String[]>());
Generates group/intranet/pageforexterns, and same for interns but when I login I have a cookies error and a redirect error.
What am I doing wrong?
Thanks
Instead creating new instance of LastPath, you just get LastPath object by LastPath lastPath=(LastPath)session.getAttribute(WebKeys.LAST_PATH); and use lastPath.setPath(PATH) to avoid any errors.

Resources