EzDevInfo.com

mojo

Mojolicious - Perl real-time web framework Mojolicious - Perl real-time web framework

What is MOJO in Maven?

I'm reading about Maven right now and everywhere in a text I see this word (mojo). I approximately understand what it means, but I would not refuse from a good explanation. I tried to google, but found only non-maven explanations.

POJO - ok, but MOJO? Maven Old Java Object?


Source: (StackOverflow)

Java Maven MOJO - getting information from project POM

I am working on a maven plugin. I seem to have a hard time figuring out, what would be a good way to get POM information from project in which you execute the MOJO ?

For instance if I execute my mojo in another maven project I would like to get project name or some other parameters.

And one more thing, there is a context MAP in AbstractMojo.java class there is private Map pluginContext, could someone correct me if I am wrong but this is suppose to be used for passing information between mojos ?


Source: (StackOverflow)

Advertisements

How do you force a maven MOJO to be executed only once at the end of a build?

I have a MOJO I would like executed once, and once only after the test phase of the last project in the reactor to run.

Using:

if (!getProject().isExecutionRoot()) {
        return ;
}

at the start of the execute() method means my mojo gets executed once, however at the very beginning of the build - before all other child modules.


Source: (StackOverflow)

Maven: How to get all transitive dependencies programatically in a MOJO [duplicate]

Possible Duplicate:
How to get access to Maven’s dependency hierarchy within a plugin.

The dependency:tree plugin:goal has an option 'verbose' which displays all conflicts & duplicates in the dependency tree. I am trying to reuse that information in my own mojo to generate reports, however - I can't seem to figure out exactly how that plugin is gathering all transitive dependencies\artifacts.

I've tried:

ArtifactResolutionResult result = _artifactCollector.collect( _project.getDependencyArtifacts(), _project.getArtifact(), _project.getManagedVersionMap(),
    		_localRepository, _project.getRemoteArtifactRepositories(), _artifactMetadataSource, null, Collections.EMPTY_LIST );

As far as I can tell this is how the tree goal is doing it with the exception of the listener.

Does anyone out there know how to do what I am asking?

UPDATE: I didn't search well enough apparently, my question is a duplicate of: this. Please vote to close as I have already done, thanks.


Source: (StackOverflow)

How to add and remove routes dynamically in Mojolicious?

I am trying to put together a maintenance page in my Mojolicious app which all of my users will be shown whenever a file or DB entry is present on the server.

I know I can check for this file or entry on startup and if its there add in my 'catch all' route. However I'm not sure how to do this dynamically? I don't want to have to restart the backend whenever I want to go into maintenance.

Is there a way to add and remove routes from a hook? for example use the before dispatch hook to monitor for the file/db entry and if it exists modify the routes?

I tried this but I didn't seem to be able to access the routes from the hooked function, only in the startup function.

Thank you.


Source: (StackOverflow)

Can't post json in a Mojo::UserAgent request

I can't get the following Mojo::UserAgent call to post JSON to the server:

use Mojo::UserAgent;
my $ua=Mojo::UserAgent->new;
my $json = $ua->post("localhost:6767" => {} => json =>{ val=>10 })->res->json;

Using a fake debug server on the other side with nc -l 6767 gives the following output:

POST / HTTP/1.1
User-Agent: Mojolicious (Perl)
Connection: keep-alive
Content-Length: 0
Host: localhost:6767 

It's not just the json method, the form, and the whole Transactor seems to be broken on 2 of my machines. From the docs:

perl -MMojo::UserAgent::Transactor -E 'say Mojo::UserAgent::Transactor->new->tx(PUT => "http://kraih.com" => json => {a => "b"})->req->to_string;'
PUT / HTTP/1.1
Content-Length: 4
Host: kraih.com

json

Hard to believe my eyes. What am I missing?


Source: (StackOverflow)

perl Mojo and JSON for simultaneous requests

I'm usually no Perl coder. However I've got to complete this task.

The following code works for me:

#!/usr/bin/perl

use LWP::UserAgent;
use JSON;
use strict;

my $md5 = $ARGV[0];
$md5 =~ s/[^A-Fa-f0-9 ]*//g;
die "invalid MD5" unless ( length($md5) == 32 );

my $ua = LWP::UserAgent->new(ssl_opts => { verify_hostname => 1 }, timeout => 10);
my $key="12345...7890";
my $url='https://www.virustotal.com/vtapi/v2/file/report';
my $response = $ua->post( $url, ['apikey' => $key, 'resource' => $md5] );
die "$url error: ", $response->status_line unless $response->is_success;
my $results=$response->content;

my $json = JSON->new->allow_nonref;
my $decjson = $json->decode( $results);

print "md5: ",$md5,"\n";
print "positives: ", $decjson->{"positives"}, "\n";
print "total: ", $decjson->{"total"}, "\n";
print "date: ", $decjson->{"scan_date"}, "\n";

Now I would like to recode the above for using asynchronous http using Mojo. I'm trying this:

#!/usr/bin/perl

use warnings;
use strict;
use Mojo;
use Mojo::UserAgent;

my $md5 = $ARGV[0];
$md5 =~ s/[^A-Fa-f0-9 ]*//g;
die "invalid MD5" unless ( length($md5) == 32 );

my ($vt_positives, $vt_scandate, $response_vt);
my $url='https://www.virustotal.com/vtapi/v2/file/report';
my $key="12345...7890";
my $ua = Mojo::UserAgent->new;
my $delay = Mojo::IOLoop->delay;

$ua->max_redirects(0)->connect_timeout(3)->request_timeout(6);
$ua->max_redirects(5);
$delay->begin;

$response_vt = $ua->post( $url => ['apikey' => $key, 'resource' => $md5] => sub {
    my ($ua, $tx) = @_;
    $vt_positives=$tx->res->json->{"positives"};
    print "Got response: $vt_positives\n";
    });

Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

The first code is OK, the second isn't working. I must be doing something wrong when sending the request since I seem to get a 403 response (incorrect API usage). I also tried -> json calls but it didn't work out.

And even if I had done the request correctly, I'm not sure if I'm correctly decoding the json results with Mojo.

Help will be appreciated!


Source: (StackOverflow)

Parallel requests in Mojolicious application

I have perl application which, for example, parallel searching in google:

use Mojo::UserAgent;
use Mojo::IOLoop;

my $ua = Mojo::UserAgent->new();

my $delay = Mojo::IOLoop->delay(sub { say 'DONE1 (should be before render)'; });

foreach my $i ( 1 .. 10 ) {
    $delay->begin();

    $ua->get("http://www.google.ru/search?q=$i" => sub {
        say $i;
        $delay->end();
    });
}

$delay->wait() unless $delay->ioloop->is_running();

say 'DONE2 (should be before render)';
say 'Found! (render)';

And it's works fine:

6
1
7
10
3
9
2
5
8
4
DONE1 (should be before render)
DONE2 (should be before render)
Found! (render)

When I use this code in Mojolicious application in controller:

package MyApp::Google;

use Mojo::Base 'Mojolicious::Controller';

sub search {

    my $self = shift;

    my $delay = Mojo::IOLoop->delay(sub { $self->app->log->debug('DONE1 (should be before render)') });

    foreach my $i ( 1 .. 10 ) {
        $delay->begin();

        $self->ua->get("http://www.google.ru/search?q=$i" => sub {
            $self->app->log->debug($i);
            $delay->end();
        });
    }

    $delay->wait() unless $delay->ioloop->is_running();

    $self->app->log->debug('DONE2 (should be before render)');

    return $self->render_text('Found!');

}

It is going in a wrong way:

[Wed May 15 11:07:32 2013] [debug] Routing to controller "MyApp::Google" and action "search".
[Wed May 15 11:07:32 2013] [debug] DONE2 (should be before render)
[Wed May 15 11:07:32 2013] [debug] 200 OK (0.005689s, 175.778/s).
[Wed May 15 11:07:32 2013] [debug] 1
[Wed May 15 11:07:32 2013] [debug] 8
[Wed May 15 11:07:32 2013] [debug] 10
[Wed May 15 11:07:32 2013] [debug] 5
[Wed May 15 11:07:32 2013] [debug] 3
[Wed May 15 11:07:32 2013] [debug] 9
[Wed May 15 11:07:32 2013] [debug] 6
[Wed May 15 11:07:32 2013] [debug] 2
[Wed May 15 11:07:32 2013] [debug] 4
[Wed May 15 11:07:32 2013] [debug] 7
[Wed May 15 11:07:32 2013] [debug] DONE1 (should be before render)

I guess so $delay->wait() is not waiting. Why is it going?


Source: (StackOverflow)

Maven, Webstart, and Java 8 Headaches

I am trying to convert a project from compiling with Java 6 to Java 8. We are using the webstart-maven-plugin for which there is currently a workaround (http://mojo.10943.n7.nabble.com/jira-MWEBSTART-269-Java-8-support-td44357.html) for compiling with Java 8 by adding the following dependencies to the plugin definition.

...
<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>webstart-maven-plugin</artifactId>
                <version>1.0-beta-6</version>
                <dependencies>
                    <dependency>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>webstart-pack200-impl</artifactId>
                        <version>1.0-beta-6</version>
                    </dependency>
                    <dependency>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>keytool-api-1.7</artifactId>
                        <version>1.4</version>
                    </dependency>
                </dependencies>
                ...
            </plugin>
        </plugins>
    </pluginManagement>
</build>
...

This got me past my initial issues.

I am now receiving the following error.

[ERROR] Failed to execute goal org.codehaus.mojo:webstart-maven-plugin:1.0-beta-6:jnlp-inline (default) on project <redacted>: Unable to parse configuration of mojo org.codehaus.mojo:webstart-maven-plugin:1.0-beta-6:jnlp-inline for parameter pack200: Cannot find default setter in class org.codehaus.mojo.webstart.Pack200Config -> [Help 1]

The Help link goes to the following page. https://cwiki.apache.org/confluence/display/MAVEN/PluginConfigurationException

As far as I can figure out, the webstart-pack200-impl dependency requires some configuration to define which setter is used. Any information regarding setters that I have found online seems to be a different issue from this. I can't figure out if there is a way to set a configuration for a dependency.

Or am I looking at this in a completely incorrect way?

Many thanks in advance


Source: (StackOverflow)

Your thoughts on a proposal to manage JavaScript dependencies

I've recently done a great deal of JavaScript programming in the context of developing a Rich Internet Application. My view at the start of development is pretty much what it is now; JS RIA works but the development tools are lacking.

One tool that I missed in particular was for managing dependencies. What I found was that I ended up with lots of HTML pages declaring all of their JS file dependencies and that this became hard to maintain.

What I'd like to know are your thoughts on a project I've embarked upon: Maven JavaScript Import. My intent is to ultimately release the project as open source but at the moment I'm just tinkering around with it (a great deal has been developed already though).

Declaring dependencies

My thoughts based on using Maven to declare JS files as dependencies. This is how I'd declare a project dependency on jQuery in my pom file:

<dependency>
  <groupId>com.jquery</groupId>
  <artifactId>jquery</artifactId>
  <version>1.4.2</version>
  <type>js</type>
</dependency>

A file that then depends on jQuery has two methods of declaring its dependence:

  1. via an @import statement within a comment block; or
  2. simply declaring a global variable that's required.

Imports

Explicit imports take the form:

/**
 * @import com.jquery:jquery
 */

As you can see the format of the import is <groupId>:<artifactId>. The approach holds the advantage that there is no file/version information declared in the js file that has the dependency. These GAV parameters resolve to artifacts declared in the POM file.

Global Vars

Instead of the above @import, if a dependent file declares variables at the global scope then simply declaring any of those global symbols is all that is required. For example if a file requires jQuery:

var $;

... as $ is of course a global defined by jQuery.

Not all dependencies declare global symbols and that's why @import is proposed as well, but declaring the symbol required is, I think, nice and clean (and JSLint conforming!).

In conclusion

Ultimately the HTML file that requires a JS resource simply declares the immediate one it requires, and not all of its dependencies. My Maven plugin will run through all the JS files (source files and dependencies) and build a symbol tree. Any HTML file including a resource will have script elements injected by the plugin to ensure that all dependencies are included. This will all happen in the magical Maven way when a project's phases are executed e.g. prior to a test, or resources phase executes.

So what do you think? Is this something that you might use in your JS RIA project?


Source: (StackOverflow)

Mojo development - Handling unresolved dependencies in multi module projects

I have a mojo annotated with @requiresDependencyResolution test.

It works for multi-module projects with a single layer of nesting, but a user has reported an issue with a structure such as below.

 -- my_project
    |
    -- pom.xml
    -- submodule1
       |
       -- pom.xml
    -- submodule2
       |
       -- pom.xml
       -- submodule21
         |
         -- pom.xml
       -- submodule22
         |
         -- pom.xml

If submodule21 depends on submodule1 maven reports

Failed to execute goal on project submodule21: Could not resolve dependencies for project org.my:submodule21:jar:1.0-SNAPSHOT: Could not find artifact org.my:submodule1:jar:1.0-SNAPSHOT

Removing the requiresDependencyResolution=test annotation prevents this problem but then I do not have access to the information I require for the mojo to run.

From brief scan of the surefire code on github, it looks to also use requiresDependencyResolution=test but is able to run against this project without issue.

https://github.com/apache/maven-surefire/blob/master/maven-surefire-plugin/src/main/java/org/apache/maven/plugin/surefire/SurefirePlugin.java

https://github.com/apache/maven-surefire/blob/master/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/AbstractSurefireMojo.java

The only obvious difference from my own code is that it uses java annotations rather than old style javadoc ones.

How is the surefire mojo achieving this?

My code is

http://code.google.com/p/pitestrunner/source/browse/pitest-maven/src/main/java/org/pitest/maven/PitMojo.java

Example project displaying issue

http://code.google.com/p/pitestrunner/issues/detail?id=71


Source: (StackOverflow)

Perl Mojolicious & Socket.IO doesn't play well

I was trying to experiment with Socket.IO and Perl's Mojolicious. while I was able to perform the same with WebSockets I tried to do the same with Socket.IO (due to wider browser support that I need) it didn't play well.

I'm using the Morbo server. the code is:

#!/usr/bin/env perl
use Mojolicious::Lite;

get '/' => sub {
    my $self = shift;

    $self->render('index');
};

websocket '/echo' => sub {
    my $self       = shift;
    state $counter = 1;

    $self->res->headers->header('Access-Control-Allow-Origin' => "*");
    Mojo::IOLoop->recurring(1.5 => sub {
          my $loop = shift;
          $self->send(sprintf("Websocket request: %d\n",$counter++));

  });
};

app->start;

__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
  <head>
     <title>Socket.IO test</title>
     <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
     <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
  </head>
  <body>
  <div id="dumper"></div>
<script>
   var ws = new WebSocket('<%= url_for('echo')->to_abs %>');

   ws.onmessage = function(e) {
      var message = e.data;
      console.log(message);
      $("#dumper").text(message);
    };
 // var socket = io.connect('<%= url_for('echo')->to_abs %>');
//  socket.on('data', function (data) {
//    console.log(data);
//  });
</script>


  </body>
</html>

This code part work well (WebSocket), when I uncomment the Socket.IO part, it fails on the io.connect(...) with the following error (Header and Response):

Request:

GET /socket.io/1/?t=1385234823089 HTTP/1.1
Host: 127.0.0.1:3000
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31
Accept: */*
Referer: http://127.0.0.1:3000/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

Response:

HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Type: text/html;charset=UTF-8
Date: Sat, 23 Nov 2013 19:27:03 GMT
Content-Length: 6163
Server: Mojolicious (Perl)

The Request I get from the client while using the WebSocket is this:

GET ws://127.0.0.1:3000/echo HTTP/1.1
Pragma: no-cache
Origin: http://127.0.0.1:3000
Host: 127.0.0.1:3000
Sec-WebSocket-Key: zgob5gss5XTr9vzYwYNe+A==
Upgrade: websocket
Sec-WebSocket-Extensions: x-webkit-deflate-frame
Cache-Control: no-cache
Connection: Upgrade
Sec-WebSocket-Version: 13

it seems that Socket.IO doenst request for the socket upgrade? Also, Mojo is not aware of this route:

/socket.io/1

I also tried replacing:

io.connect('<%= url_for('echo')->to_abs %>');

with io.connect('http://localhost:300/echo');


Source: (StackOverflow)

Is it possible to use Mojolicious tag helpers in external JS files?

I am currently working on cleaning up a little web app I've written in Mojolicious. As part of that cleanup I am separating out my javascript into the public directory from my html.ep files.

The problem I have though is I don't seem to be able to reference tag helpers any more, like 'url_for' or even referencing values in the stash such as '<% $stashvalue %>'.

Any idea's on how or if I can do this is very much appreciated.

cheers.


Source: (StackOverflow)

Maven docs after codehaus terminated?

Where can I get all the org.codehaus.mojo Maven plugins docs and sources once Codehaus.org was terminated?


Source: (StackOverflow)

lighttpd + perl + mojolicious =?

Does mojolicious working under the lighttpd web-server? How to cofigure? Does I need setup the FastCGI? It's my first usage of lighttpd.


Source: (StackOverflow)