Friday, August 24, 2018

Java Android Client Socket not working

Am I missing something. I've checked other posts and have thses set in my manifest.



Whenever I try to create a new socket on Samsung Galaxy Express it never gets past this line.

Socket s = new Socket("10.0.2.2", 4736); 

This is my class for starting a socket in a runnable.

private class SendThread implements Runnable {

    @Override
    public void run() {
        try {
            Socket s = new Socket("10.0.2.2", 4736);       <---never gets past this
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);
            out.println(sendString);
            new BufferedReader(new InputStreamReader(s.getInputStream()));
            Log.d(TAG, "sent");
            s.close();
        } catch (Exception e) {
            Log.d(TAG, "error");
            e.printStackTrace();
        }
        Log.d(TAG, "end");
    }

}

Server Socket

private class ReceiveThread implements Runnable {
    private ServerSocket receiverSocket;
    private BufferedReader input;
    private Socket socket = null;

    public void run() {
        try {
            receiverSocket = new ServerSocket(receivePort);
            receiverSocket.setReuseAddress(true);
            while (killConnection == false) {
                Log.d(TAG, "listening");
                socket = receiverSocket.accept();
                this.input = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
                Log.d(TAG, "Input from server" + input.toString());
                String s = input.readLine();
                //UpdateUi(s);
                socket.close();
            }
            receiverSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Ok yes the server-side socket isn't listening

Monday, August 20, 2018

pasing json using javascript or jQuery [duplicate]

This question already has an answer here:

I have the following JSON code. How do I parse using JavaScript or jQuery an convert to variables: name, meetup tags ?

Here is my code:

{
    "MYID": 1,
    "module": [
        {
            "name": "Manchester",
            "meetup": "First Monday of every month",
            "tags": [
                "gtug",
                "google",
                "manchester",
                "madlab"
            ]
        },
        {
            "name": "jQuery Group",
            "meetup": "First Tuesday of every month",
            "tags": [
                "jquery",
                "javascript",
                "jresig",
                "madlab"
            ]
        },
        {
            "name": "Hybrid!",
            "meetup": "First Monday of every month",
            "tags": [
                "jquery",
                "javascript",
                "jresig",
                "madlab"
            ]
        }
    ]
}

Solved

Hopefully this will answer your question?

var json = JSON.parse("...");
for (var i = 0; i < json.module.length; i++) {
    var mod = json.module[i];

    var name = mod.name;
    var meetup = mod.meetup;
    var tags = mod.tags;
}

Sunday, August 19, 2018

Setting PBS/Torque/qsub parameters in script via command line arguments

I want to be able to easily change how many nodes, ppn, etc I submit to qsub via script. That is, I want run somthing like this:

qsub script.sh --name=test_job --nodes=2 --ppn=2 --arg1=2

With a script like the following:

#/bin/bash
#PBS -N ${NAME}
#PBS -l nodes=${NODES}:ppn=${PPN},walltime=${WALLTIME}
#PBS -q ${QUEUE}
#PBS -m ${MAILOPTS}
#PBS -M ${EMAIL}

/some/command ${ARG1}

So, I want to be able to pass in arguments that both change the PBS environment as well as some that go to the executable itself.

I've tried using the -v argument of qsub:

qsub script.sh -v NAME=test_job,NODES=16,PPN=16,ARG1=2

But the job submitted with the name script.sh and 1 node, 1 ppn.

Any ideas on a solution to this?

Solved

In Torque, all of the #PBS arguments are overridden when a matching argument is specified on the command line. For example, if your script has:

#PBS -l nodes=2

You can submit:

qsub script.sh -l nodes=4

and the command line will take precendence over the script. The docs have a complete list of the command line arguments.


@dbeer's answer gave me a little more insight. The solution to my problem is as follows:

#PBS args are overwritten by the command line. In such case, the args to PBS and the script itself must be separated. Therefore, rather than trying to do something like:

#PBS -l nodes=${NODES}:ppn=${PPN},walltime=${WALLTIME}

/some/command ${ARG1}

inside the script and running like

qsub script.sh -v NODES=2,PPN=2,WALLTIME=160:00:00,ARG1=2

these can all be set with args to qsub itself:

qsub script.sh -l nodes=2:ppn=2,walltime=160:00:00

Then, any args that need to be passed to the executable can be passed through the -v argument to qsub:

qsub script.sh -l nodes=2:ppn=2,walltime=160:00:00 -v ARGS1=2

Saturday, August 18, 2018

jersey 2.2: ContainerResponseFilter and ContainerRequestFilter never get executed

Following the getting started guide on the Jersey website:

I executed the following build command:

$ mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-grizzly2 \
-DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false \
-DgroupId=com.example -DartifactId=simple-service -Dpackage=com.example \
-DarchetypeVersion=2.2

I then followed the tutorial on

https://jersey.java.net/documentation/latest/filters-and-interceptors.html#d0e6783

to add a custom ContainerResponseFilter:

@NameBinding
@Retention(RetentionPolicy.RUNTIME)
static @interface CORSBinding {}

@Provider
@Priority(Priorities.HEADER_DECORATOR)
@CORSBinding
static class CrossDomainFilter implements ContainerResponseFilter {
    @Override
    public void filter(ContainerRequestContext creq, ContainerResponseContext cres) {
        Logger.getLogger("com.example").log( Level.INFO, "before: {0}", cres.getHeaders());
        cres.getHeaders().add("Access-Control-Allow-Origin", "*");
        cres.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        cres.getHeaders().add("Access-Control-Allow-Credentials", "true");
        cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        cres.getHeaders().add("Access-Control-Max-Age", "1209600");
        Logger.getLogger("com.example").log( Level.INFO, "after: {0}", cres.getHeaders());
    }
}

@Provider
static class MyResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        System.out.println("MyResponseFilter.postFilter() enter");
        responseContext.setEntity(
                responseContext.getEntity() + ":" + getClass().getSimpleName(), null, MediaType.TEXT_PLAIN_TYPE);
        System.out.println("MyResponseFilter.postFilter() exit");
    }
}

...
@GET
@Produces(MediaType.TEXT_PLAIN)
@CORSBinding
public String helloWorld() {
    return "hello world";
}

I tried to register this filter with Named Binding and with Dynamic Binding, nothing works.

To easily reproduce, I also tried an example from the official resources:

https://github.com/jersey/jersey/tree/2.2/examples/exception-mapping

The same problem: the custom filters do not get executed.

Is this a Grizzly problem?

Solved

As it turns out you have to manually register the custom classes - as in:

rc.register(com.dummy.mypackage.CORSResponseFilter.class);

Full example:

/**
 * Main class.
 *
 */
public class Main {
    // Base URI the Grizzly HTTP server will listen on
    public static final String BASE_URI = "http://192.168.1.34:8080/myapp/";

    /**
     * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
     * @return Grizzly HTTP server.
     */
    public static HttpServer startServer() {
        // create a resource config that scans for JAX-RS resources and in com.example package
        final ResourceConfig rc = new ResourceConfig().packages("com.dummy.mypackage");

        //NEW: register custom ResponseFilter
        rc.register(com.dummy.mypackage.CORSResponseFilter.class);

        // Register Jackson JSON
        rc.packages("org.glassfish.jersey.examples.jackson").register(JacksonFeature.class);

        // create and start a new instance of grizzly http server
        // exposing the Jersey application at BASE_URI
        return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
    }
    ...
}

Adding the following code in web.xml using Tomcat container is what worked for me:


    jersey.config.server.provider.classnames
    my.package.SecurityRequestFilter;org.glassfish.jersey.filter.LoggingFilter
`

My thanks goes to:

http://blog.dejavu.sk/2013/11/19/registering-resources-and-providers-in-jersey-2/